backend-app-api: deprecate plugin path configuration and fix /api/* 404

Signed-off-by: Patrik Oldsberg <poldsberg@gmail.com>
This commit is contained in:
Patrik Oldsberg
2024-04-06 15:30:01 +02:00
parent 31ee337a50
commit 10327fb855
6 changed files with 39 additions and 17 deletions
@@ -43,6 +43,7 @@ export const httpRouterServiceFactory = createServiceFactory(
deps: {
plugin: coreServices.pluginMetadata,
config: coreServices.rootConfig,
logger: coreServices.logger,
lifecycle: coreServices.lifecycle,
rootHttpRouter: coreServices.rootHttpRouter,
auth: coreServices.auth,
@@ -52,10 +53,16 @@ export const httpRouterServiceFactory = createServiceFactory(
auth,
httpAuth,
config,
logger,
plugin,
rootHttpRouter,
lifecycle,
}) {
if (options?.getPath) {
logger.warn(
`DEPRECATION WARNING: The 'getPath' option for HttpRouterService is deprecated. The ability to reconfigure the '/api/' path prefix for plugins will be removed in the future.`,
);
}
const getPath = options?.getPath ?? (id => `/api/${id}`);
const path = getPath(plugin.getId());
@@ -89,4 +89,20 @@ describe('DefaultRootHttpRouter', () => {
expect('test').toBe('test');
});
it('should treat unknown /api/ routes as 404', async () => {
const router = DefaultRootHttpRouter.create();
const app = express();
app.use(router.handler());
router.use('/api/app', (_req, res) => res.status(201).end());
router.use('/api/catalog', (_req, res) => res.status(202).end());
await request(app).get('/').expect(201);
await request(app).get('/api/catalog').expect(202);
await request(app).get('/unknown').expect(201);
await request(app).get('/api/unknown').expect(404);
expect('test').toBe('test');
});
});
@@ -66,6 +66,12 @@ export class DefaultRootHttpRouter implements RootHttpRouterService {
private constructor(indexPath?: string) {
this.#indexPath = indexPath;
this.#router.use(this.#namedRoutes);
// Any request with a /api/ prefix will skip the index router, even if no named router matches
this.#router.use('/api/', (_req, _res, next) => {
next('router');
});
if (this.#indexPath) {
this.#router.use(this.#indexRouter);
}