Skip to content

Commit f1e461b

Browse files
committed
feat(hook): add a hook such that it's easier to use company-specific subclasses
1 parent cd402ca commit f1e461b

File tree

3 files changed

+45
-3
lines changed

3 files changed

+45
-3
lines changed

__tests__/fake-serv/src/index.ts

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { RestApiErrorResponse, RestApiSuccessResponse } from 'rest-api-support';
22

33
import type { Service, ServiceLocals } from '../../../src/types';
4+
import { useService } from '../../../src';
45

56
export interface FakeServLocals extends ServiceLocals {
67
services: {
@@ -11,16 +12,21 @@ export interface FakeServLocals extends ServiceLocals {
1112
}
1213

1314
export function service(): Service<FakeServLocals> {
15+
const base = useService<FakeServLocals>();
1416
return {
15-
start(app) {
17+
...base,
18+
async start(app) {
19+
await base.start(app);
1620
app.locals.services.fakeServ = {
1721
get_something() { throw new Error('Should not be called.'); },
1822
};
1923
},
20-
onRequest(req, res) {
24+
async onRequest(req, res) {
25+
await base.onRequest?.(req, res);
2126
res.locals.rawBody = true;
2227
},
23-
async healthy() {
28+
async healthy(app) {
29+
await base.healthy?.(app);
2430
return new Promise((accept) => {
2531
setTimeout(accept, 1000);
2632
});

src/hook.ts

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
import type { RequestLocals, Service, ServiceLocals } from './types';
2+
3+
/**
4+
* Your service should call this function and then "inherit"
5+
* the behavior in a functional way. So,
6+
*
7+
* const myServiceFn = () => {
8+
* const baseService = useService<YourService>();
9+
* return {
10+
* ...baseService,
11+
* async start(app) {
12+
* await baseService.start(app);
13+
* // your start stuff goes here
14+
* },
15+
* async onRequest(req, res) {
16+
* // This might throw (auth for example), so don't catch it
17+
* await baseService?.onRequest(req, res);
18+
* },
19+
* }
20+
* }
21+
*
22+
* @returns Service<SLocals, RLocals>
23+
*/
24+
export function useService<
25+
SLocals extends ServiceLocals = ServiceLocals,
26+
RLocals extends RequestLocals = RequestLocals,
27+
>(baseService?: Service<SLocals, RLocals>): Service<SLocals, RLocals> {
28+
return {
29+
async start(app) {
30+
await baseService?.start(app);
31+
// Do nothing. This hook exists mainly to reduce change required
32+
// to adopt your specific companies base service.
33+
},
34+
};
35+
}

src/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,3 +6,4 @@ export * from './env';
66
export * from './config';
77
export * from './error';
88
export * from './bootstrap';
9+
export * from './hook';

0 commit comments

Comments
 (0)