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 11import { RestApiErrorResponse , RestApiSuccessResponse } from 'rest-api-support' ;
22
33import type { Service , ServiceLocals } from '../../../src/types' ;
4+ import { useService } from '../../../src' ;
45
56export interface FakeServLocals extends ServiceLocals {
67 services : {
@@ -11,16 +12,21 @@ export interface FakeServLocals extends ServiceLocals {
1112}
1213
1314export 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 } ) ;
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';
66export * from './config' ;
77export * from './error' ;
88export * from './bootstrap' ;
9+ export * from './hook' ;
You can’t perform that action at this time.
0 commit comments