Skip to content

Commit

Permalink
feat(fastify): added middlewares option to forRoot of the module
Browse files Browse the repository at this point in the history
  • Loading branch information
Stradivario committed Jun 6, 2024
1 parent b31bbe5 commit 8db7907
Show file tree
Hide file tree
Showing 4 changed files with 22 additions and 2 deletions.
5 changes: 3 additions & 2 deletions packages/fastify/src/fastify.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { Module, ModuleWithProviders } from '@rhtml/di';
import fastify, { FastifyInstance } from 'fastify';

import { Fastify, FastifyListen, FastifyModuleOptions } from './fastify.tokens';
import { addSchema, globalErrorHandler, pipe } from './helpers';
import { addMiddlewares, addSchema, globalErrorHandler, pipe } from './helpers';

@Module()
export class FastifyModule {
Expand All @@ -26,7 +26,8 @@ export class FastifyModule {

return pipe(
addSchema(schemas),
globalErrorHandler(options.globalErrorHandler)
globalErrorHandler(options.globalErrorHandler),
addMiddlewares(options.middlewares)
)(instance);
},
},
Expand Down
3 changes: 3 additions & 0 deletions packages/fastify/src/fastify.tokens.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ import {
FastifySchema,
} from 'fastify';

import { Middleware } from './helpers';

export const Fastify = new InjectionToken<FastifyInstance>();
export const FastifyListen = new InjectionToken<string>();

Expand All @@ -33,4 +35,5 @@ export interface FastifyModuleOptions extends FastifyHttpOptions<never> {
schemas: FastifySchema[];
globalErrorHandler: GlobalErrorHandler;
server: FastifyListenOptions;
middlewares: Middleware[];
}
15 changes: 15 additions & 0 deletions packages/fastify/src/helpers/hooks/add-middlewares.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { Reader } from '@rhtml/di';
import { FastifyInstance } from 'fastify';

export type Middleware = (instance: FastifyInstance) => FastifyInstance;

export function addMiddlewares(
middlewares: Middleware[]
): Reader<FastifyInstance, FastifyInstance> {
return (instance) => {
for (const middleware of middlewares) {
instance = middleware(instance);
}
return instance;
};
}
1 change: 1 addition & 0 deletions packages/fastify/src/helpers/hooks/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
export * from './add-schema.hook';
export * from './global-error.hook';
export * from './add-middlewares';

0 comments on commit 8db7907

Please sign in to comment.