Skip to content

Commit e7c4b08

Browse files
committed
feat(node-utils): add option to deactivate route handlers
1 parent e12be00 commit e7c4b08

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

packages/node-utils/src/http.ts

+24
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,7 @@ type Route = {
7373
pathname: string;
7474
params: string[];
7575
handler: AnyRequestHandler[];
76+
isActive: boolean;
7677
};
7778
/**
7879
* Events that may be emitted or listened to by HttpServer
@@ -219,6 +220,7 @@ export class HttpServer<T extends EventMap> extends TypedEmitter<T & BaseEvents>
219220
pathname: `/${basePathname}`,
220221
params: paramsSegments,
221222
handler,
223+
isActive: true,
222224
});
223225
}
224226

@@ -244,9 +246,24 @@ export class HttpServer<T extends EventMap> extends TypedEmitter<T & BaseEvents>
244246
pathname: '*',
245247
handler,
246248
params: [],
249+
isActive: true,
247250
});
248251
}
249252

253+
public activateRoute(pathname: string) {
254+
const route = this.routes.find(r => r.pathname === pathname);
255+
if (route) {
256+
route.isActive = true;
257+
}
258+
}
259+
260+
public deactivateRoute(pathname: string) {
261+
const route = this.routes.find(r => r.pathname === pathname);
262+
if (route) {
263+
route.isActive = false;
264+
}
265+
}
266+
250267
/**
251268
* pathname could be /a/b/c/d
252269
* return route with highest number of matching segments
@@ -329,6 +346,13 @@ export class HttpServer<T extends EventMap> extends TypedEmitter<T & BaseEvents>
329346

330347
return;
331348
}
349+
350+
if (!route.isActive) {
351+
response.statusCode = 404;
352+
response.end();
353+
return;
354+
}
355+
332356
const paramsSegments = pathname
333357
.replace(route.pathname, '')
334358
.split('/')

packages/node-utils/src/tests/http.test.ts

+21
Original file line numberDiff line numberDiff line change
@@ -391,4 +391,25 @@ describe('HttpServer', () => {
391391
);
392392
expect(res.status).toEqual(403);
393393
});
394+
395+
test('any registered route is active by default and can be deactivated', async () => {
396+
const handler = jest.fn((_request, response) => {
397+
response.end('ok');
398+
});
399+
server.get('/foo', [handler]);
400+
server.get('/bar', [handler]);
401+
await server.start();
402+
const address = server.getServerAddress();
403+
expect(address).toBeDefined();
404+
let res = await fetch(`http://${address.address}:${address.port}/foo`);
405+
expect(res.status).toEqual(200);
406+
res = await fetch(`http://${address.address}:${address.port}/bar`);
407+
expect(res.status).toEqual(200);
408+
409+
server.deactivateRoute('/foo');
410+
res = await fetch(`http://${address.address}:${address.port}/foo`);
411+
expect(res.status).toEqual(404);
412+
res = await fetch(`http://${address.address}:${address.port}/bar`);
413+
expect(res.status).toEqual(200);
414+
});
394415
});

0 commit comments

Comments
 (0)