Skip to content

Commit 8db7907

Browse files
committed
feat(fastify): added middlewares option to forRoot of the module
1 parent b31bbe5 commit 8db7907

File tree

4 files changed

+22
-2
lines changed

4 files changed

+22
-2
lines changed

packages/fastify/src/fastify.module.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import { Module, ModuleWithProviders } from '@rhtml/di';
22
import fastify, { FastifyInstance } from 'fastify';
33

44
import { Fastify, FastifyListen, FastifyModuleOptions } from './fastify.tokens';
5-
import { addSchema, globalErrorHandler, pipe } from './helpers';
5+
import { addMiddlewares, addSchema, globalErrorHandler, pipe } from './helpers';
66

77
@Module()
88
export class FastifyModule {
@@ -26,7 +26,8 @@ export class FastifyModule {
2626

2727
return pipe(
2828
addSchema(schemas),
29-
globalErrorHandler(options.globalErrorHandler)
29+
globalErrorHandler(options.globalErrorHandler),
30+
addMiddlewares(options.middlewares)
3031
)(instance);
3132
},
3233
},

packages/fastify/src/fastify.tokens.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@ import {
1111
FastifySchema,
1212
} from 'fastify';
1313

14+
import { Middleware } from './helpers';
15+
1416
export const Fastify = new InjectionToken<FastifyInstance>();
1517
export const FastifyListen = new InjectionToken<string>();
1618

@@ -33,4 +35,5 @@ export interface FastifyModuleOptions extends FastifyHttpOptions<never> {
3335
schemas: FastifySchema[];
3436
globalErrorHandler: GlobalErrorHandler;
3537
server: FastifyListenOptions;
38+
middlewares: Middleware[];
3639
}
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
import { Reader } from '@rhtml/di';
2+
import { FastifyInstance } from 'fastify';
3+
4+
export type Middleware = (instance: FastifyInstance) => FastifyInstance;
5+
6+
export function addMiddlewares(
7+
middlewares: Middleware[]
8+
): Reader<FastifyInstance, FastifyInstance> {
9+
return (instance) => {
10+
for (const middleware of middlewares) {
11+
instance = middleware(instance);
12+
}
13+
return instance;
14+
};
15+
}
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,3 @@
11
export * from './add-schema.hook';
22
export * from './global-error.hook';
3+
export * from './add-middlewares';

0 commit comments

Comments
 (0)