Skip to content

Commit

Permalink
feat: support get fastifyInstance in service
Browse files Browse the repository at this point in the history
  • Loading branch information
cxtom committed Apr 1, 2021
1 parent a22ea4e commit 2367f2b
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 14 deletions.
9 changes: 6 additions & 3 deletions example/hoth-quickstart/src/lib/calculator/index.service.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
import {Service} from '@hoth/decorators';
import {getFastifyInstanceByAppName, Service} from '@hoth/decorators';

@Service()
export default class Calculator {

private service = getFastifyInstanceByAppName('quickstart');

add(a: number, b: number) {
return a + b;
return a + b + this.service.$appConfig.get('test');
}
}
}
24 changes: 14 additions & 10 deletions packages/app-autoload/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,19 @@ async function load(appConfig: AppConfig, childInstance: FastifyInstance) {
...appConfig,
});

const configProxy = {
get(property: string | string[]) {
const props = Array.isArray(property)
? [appConfig.name, ...property]
: `${appConfig.name}.${property}`;
if (Config.has(props)) {
return Config.get(props);
}
},
};

childInstance.decorate('$appConfig', configProxy);

// register app plugins
const appEntryModule: FastifyPluginAsync = await loadModule(pluginAppConfig.entryPath);
await appEntryModule(childInstance, {...appConfig});
Expand All @@ -114,16 +127,7 @@ async function load(appConfig: AppConfig, childInstance: FastifyInstance) {
appName: appConfig.name,
});

childInstance.addHook('onRequest', onRequestFactory({
get(property: string | string[]) {
const props = Array.isArray(property)
? [appConfig.name, ...property]
: `${appConfig.name}.${property}`;
if (Config.has(props)) {
return Config.get(props);
}
},
}, childInstance));
childInstance.addHook('onRequest', onRequestFactory(configProxy, childInstance));

childInstance.addHook('preHandler', preHandlerFactory(appConfig.name));
childInstance.addHook('preHandler', loggerMiddleware);
Expand Down
8 changes: 7 additions & 1 deletion packages/decorators/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import 'reflect-metadata';
import type {FastifyInstance} from 'fastify';

import type {AutoLoadConfig} from 'fastify-decorators/interfaces/bootstrap-config';
import {bootstrap as bootstrapInner} from 'fastify-decorators';
import {bootstrap as bootstrapInner, FastifyInstanceToken} from 'fastify-decorators';

export {
Controller,
Expand Down Expand Up @@ -60,5 +60,11 @@ declare module 'fastify' {
addNotice: (key: string, value: string) => void;
addPerformance: (name: string, value: number) => void;
}

interface FastifyInstance {
readonly $appConfig: {
get: (property: string | string[]) => any;
};
}
}

0 comments on commit 2367f2b

Please sign in to comment.