File tree Expand file tree Collapse file tree 3 files changed +45
-3
lines changed Expand file tree Collapse file tree 3 files changed +45
-3
lines changed Original file line number Diff line number Diff line change 1
1
import { RestApiErrorResponse , RestApiSuccessResponse } from 'rest-api-support' ;
2
2
3
3
import type { Service , ServiceLocals } from '../../../src/types' ;
4
+ import { useService } from '../../../src' ;
4
5
5
6
export interface FakeServLocals extends ServiceLocals {
6
7
services : {
@@ -11,16 +12,21 @@ export interface FakeServLocals extends ServiceLocals {
11
12
}
12
13
13
14
export function service ( ) : Service < FakeServLocals > {
15
+ const base = useService < FakeServLocals > ( ) ;
14
16
return {
15
- start ( app ) {
17
+ ...base ,
18
+ async start ( app ) {
19
+ await base . start ( app ) ;
16
20
app . locals . services . fakeServ = {
17
21
get_something ( ) { throw new Error ( 'Should not be called.' ) ; } ,
18
22
} ;
19
23
} ,
20
- onRequest ( req , res ) {
24
+ async onRequest ( req , res ) {
25
+ await base . onRequest ?.( req , res ) ;
21
26
res . locals . rawBody = true ;
22
27
} ,
23
- async healthy ( ) {
28
+ async healthy ( app ) {
29
+ await base . healthy ?.( app ) ;
24
30
return new Promise ( ( accept ) => {
25
31
setTimeout ( accept , 1000 ) ;
26
32
} ) ;
Original file line number Diff line number Diff line change
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
+ }
Original file line number Diff line number Diff line change @@ -6,3 +6,4 @@ export * from './env';
6
6
export * from './config' ;
7
7
export * from './error' ;
8
8
export * from './bootstrap' ;
9
+ export * from './hook' ;
You can’t perform that action at this time.
0 commit comments