@thzero/library_server_fastify 0.15.44 → 0.16.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/boot/index.js CHANGED
@@ -1,350 +1,350 @@
1
- import path from 'path';
2
-
3
- import Fastify from 'fastify';
4
- // import fastifyAuth from 'fastify-auth';
5
- import fastifyAuth from '../plugins/auth';
6
- import fastifyCors from 'fastify-cors';
7
- import fastifyHelmet from 'fastify-helmet';
8
- import fastifyRoutes from 'fastify-routes';
9
- import fastifyStatic from 'fastify-static';
10
-
11
- import LibraryConstants from '@thzero/library_server/constants';
12
-
13
- import injector from '@thzero/library_common/utility/injector';
14
-
15
- import BootMain from '@thzero/library_server/boot';
16
-
17
- import pluginApiKey from '@thzero/library_server_fastify/plugins/apiKey';
18
- import pluginResponseTime from '@thzero/library_server_fastify/plugins/responseTime';
19
- import pluginSettings from '@thzero/library_server_fastify/plugins/settings';
20
- import pluginUsageMetrics from '@thzero/library_server_fastify/plugins/usageMetrics';
21
-
22
- import authenticationDefault from '../middleware/authentication';
23
- import authorizationDefault from '../middleware/authorization';
24
-
25
- class FastifyBootMain extends BootMain {
26
- async _initApp(args, plugins) {
27
-
28
- // const serverFactory = (handler, opts) => {
29
- // const server = http.createServer((req, res) => {
30
- // handler(req, res)
31
- // });
32
-
33
- // return server;
34
- // };
35
-
36
- let http2 = this._appConfig.get('http2', false);
37
- http2 = http2 === 'true' ? true : false;
38
- this.loggerServiceI.info2(`config.http2.override: ${http2}`);
39
-
40
- // const fastify = Fastify({ serverFactory, logger: true });
41
- const fastify = Fastify({
42
- http2: http2,
43
- logger: true
44
- });
45
- const serverHttp = fastify.server;
46
-
47
- await fastify.register(fastifyRoutes);
48
-
49
- // // https://github.com/koajs/cors
50
- // app.use(koaCors({
51
- // allowMethods: 'GET,POST,DELETE',
52
- // maxAge : 7200,
53
- // allowHeaders: `${LibraryConstants.Headers.AuthKeys.API}, ${LibraryConstants.Headers.AuthKeys.AUTH}, ${LibraryConstants.Headers.CorrelationId}, Content-Type`,
54
- // credentials: true,
55
- // origin: '*'
56
- // }));
57
- // https://github.com/fastify/fastify-cors
58
- // fastify.register(fastifyCors, {
59
- // allowMethods: 'GET,POST,DELETE',
60
- // maxAge : 7200,
61
- // allowHeaders: `${LibraryConstants.Headers.AuthKeys.API}, ${LibraryConstants.Headers.AuthKeys.AUTH}, ${LibraryConstants.Headers.CorrelationId}, Content-Type`,
62
- // credentials: true,
63
- // origin: '*'
64
- // });
65
- const corsOptionsDefault = this._initCors({
66
- allowHeaders: [ LibraryConstants.Headers.AuthKeys.API, LibraryConstants.Headers.AuthKeys.AUTH, LibraryConstants.Headers.CorrelationId, 'Content-Type' ],
67
- credentials: true,
68
- maxAge : 7200,
69
- methods: ['GET', 'POST', 'DELETE'],
70
- origin: '*'
71
- });
72
- await fastify.register(fastifyCors, (instance) => {
73
- return (req, callback) => {
74
- let corsOptions = corsOptionsDefault;
75
- callback(null, corsOptions) // callback expects two parameters: error and options
76
- }
77
- });
78
-
79
- // // https://www.npmjs.com/package/koa-helmet
80
- // app.use(koaHelmet());
81
- // https://github.com/fastify/fastify-helmet
82
- const helmetOptions = this._initHelmet({
83
- // Example disables the `contentSecurityPolicy` middleware but keeps the rest.
84
- // contentSecurityPolicy: false
85
- });
86
- await fastify.register(
87
- fastifyHelmet,
88
- helmetOptions
89
- );
90
-
91
- // // error
92
- // app.use(async (ctx, next) => {
93
- // try {
94
- // await next();
95
- // }
96
- // catch (err) {
97
- // ctx.status = err.status || 500;
98
- // if (err instanceof TokenExpiredError) {
99
- // ctx.status = 401;
100
- // ctx.response.header['WWW-Authenticate'] = 'Bearer error="invalid_token", error_description="The access token expired"'
101
- // }
102
- // ctx.app.emit('error', err, ctx);
103
- // await this.usageMetricsServiceI.register(ctx, err).catch(() => {
104
- // this.loggerServiceI.exception('KoaBootMain', 'start', err);
105
- // });
106
- // }
107
- // });
108
- await fastify.register(async (instance, opts, done) => {
109
- // try {
110
- // done();
111
- // }
112
- // catch (err) {
113
- // let status = err.status || 500;
114
- // if (err instanceof TokenExpiredError) {
115
- // status = 401;
116
- // response.header['WWW-Authenticate'] = 'Bearer error="invalid_token", error_description="The access token expired"'
117
- // }
118
- // app.emit('error', err, ctx);
119
- // await this.usageMetricsServiceI.register(ctx, err).catch(() => {
120
- // this.loggerServiceI.exception('KoaBootMain', 'start', err);
121
- // });
122
- // }
123
- });
124
-
125
- // app.on('error', (err, ctx) => {
126
- // this.loggerServiceI.error('KoaBootMain', 'start', 'Uncaught Exception', err);
127
- // });
128
-
129
- // // config
130
- // app.use(async (ctx, next) => {
131
- // ctx.config = this._appConfig;
132
- // await next();
133
- // });
134
- // // correlationId
135
- // app.use(async (ctx, next) => {
136
- // ctx.correlationId = ctx.request.header[LibraryConstants.Headers.CorrelationId];
137
- // await next();
138
- // });
139
- // fastify.register(async (instance, opts, done) => {
140
- // instance.addHook('onRequest', (request, reply, next) => {
141
- // request.config = this._appConfig;
142
- // request.correlationId = ctx.request.header[LibraryConstants.Headers.CorrelationId];
143
- // next();
144
- // });
145
-
146
- // done();
147
- // });
148
- await fastify.register(pluginSettings, {
149
- config: this._appConfig
150
- });
151
-
152
- // // logger
153
- // app.use(async (ctx, next) => {
154
- // await next();
155
- // const rt = ctx.response.get(ResponseTime);
156
- // this.loggerServiceI.info2(`${ctx.method} ${ctx.url} - ${rt}`);
157
- // });
158
-
159
- // // x-response-time
160
- // app.use(async (ctx, next) => {
161
- // const start = Utility.timerStart();
162
- // await next();
163
- // const delta = Utility.timerStop(start, true);
164
- // ctx.set(ResponseTime, delta);
165
- // });
166
- // https://github.com/lolo32/fastify-response-time
167
- await fastify.register(pluginResponseTime, {
168
- logger: this.loggerServiceI
169
- });
170
-
171
- // app.use(koaStatic('./public'));
172
- // https://github.com/fastify/fastify-static
173
- const __dirname = path.resolve();
174
- await fastify.register(fastifyStatic, {
175
- root: path.join(__dirname, 'public'),
176
- prefix: '/public/', // optional: default '/'
177
- });
178
-
179
- this._initPreAuth(fastify);
180
-
181
- // // auth-api-token
182
- // app.use(async (ctx, next) => {
183
- // if (ctx.originalUrl === '/favicon.ico') {
184
- // await next();
185
- // return;
186
- // }
187
-
188
- // const key = ctx.get(LibraryConstants.Headers.AuthKeys.API);
189
- // // this.loggerServiceI.debug('KoaBootMain', 'start', 'auth-api-token.key', key);
190
- // if (!String.isNullOrEmpty(key)) {
191
- // const auth = ctx.config.get('auth');
192
- // if (auth) {
193
- // const apiKey = auth.apiKey;
194
- // // this.loggerServiceI.debug('KoaBootMain', 'start', 'auth-api-token.apiKey', apiKey);
195
- // // this.loggerServiceI.debug('KoaBootMain', 'start', 'auth-api-token.key===apiKey', (key === apiKey));
196
- // if (key === apiKey) {
197
- // ctx.state.apiKey = key;
198
- // await next();
199
- // return;
200
- // }
201
- // }
202
- // }
203
-
204
- // (async () => {
205
- // await this.usageMetricsServiceI.register(ctx).catch((err) => {
206
- // this.loggerServiceI.error('KoaBootMain', 'start', 'usageMetrics', err);
207
- // });
208
- // })();
209
-
210
- // console.log('Unauthorized... auth-api-token failure');
211
- // ctx.throw(401);
212
- // });
213
- // fastify.register((instance, opts, done) => {
214
- // instance.addHook('onRequest', (request, reply, next) => {
215
- // if (request.originalUrl === '/favicon.ico') {
216
- // next();
217
- // return;
218
- // }
219
-
220
- // const key = request.get(LibraryConstants.Headers.AuthKeys.API);
221
- // // this.loggerServiceI.debug('KoaBootMain', 'start', 'auth-api-token.key', key);
222
- // if (!String.isNullOrEmpty(key)) {
223
- // const auth = request.config.get('auth');
224
- // if (auth) {
225
- // const apiKey = auth.apiKey;
226
- // // this.loggerServiceI.debug('KoaBootMain', 'start', 'auth-api-token.apiKey', apiKey);
227
- // // this.loggerServiceI.debug('KoaBootMain', 'start', 'auth-api-token.key===apiKey', (key === apiKey));
228
- // if (key === apiKey) {
229
- // request.state.apiKey = key;
230
- // next();
231
- // return;
232
- // }
233
- // }
234
- // }
235
-
236
- // (async () => {
237
- // await this.usageMetricsServiceI.register(ctx).catch((err) => {
238
- // this.loggerServiceI.error('FastifyBootMain', 'start', 'usageMetrics', err);
239
- // });
240
- // })();
241
-
242
- // console.log('Unauthorized... auth-api-token failure');
243
- // request.throw(401);
244
- // next();
245
- // });
246
-
247
- // done();
248
- // });
249
- await fastify.register(pluginApiKey, {
250
- logger: this.loggerServiceI,
251
- usageMetrics: this.usageMetricsServiceI
252
- });
253
-
254
- await fastify.register(fastifyAuth);
255
-
256
- const capitalize = (word) => {
257
- return word[0].toUpperCase() + word.slice(1).toLowerCase();
258
- };
259
-
260
- let item;
261
- for (let [key, value] of this._initAuthentication(new Map()).entries()) {
262
- item = value.init(injector);
263
- fastify.decorate('authentication' + capitalize(key), item.callback);
264
- fastify.decorate('authenticationMiddleware' + capitalize(key), item.service);
265
- }
266
- for (let [key, value] of this._initAuthorization(new Map()).entries()) {
267
- item = value.init(injector);
268
- fastify.decorate('authorization' + capitalize(key), item.callback);
269
- fastify.decorate('authorizationMiddleware' + capitalize(key), item.service);
270
- }
271
-
272
- this._initPostAuth(fastify);
273
-
274
- this._routes = [];
275
-
276
- this._initPreRoutes(fastify);
277
-
278
- for (const pluginRoute of plugins)
279
- await pluginRoute.initRoutes(this._routes);
280
-
281
- await this._initRoutes();
282
-
283
- console.log();
284
-
285
- for (const route of this._routes) {
286
- console.log(route);
287
- await route.init(injector, fastify, this._appConfig);
288
- }
289
-
290
- let methods;
291
- for (let [key, value] of fastify.routes.entries()) {
292
- methods = [];
293
- for (let item of value)
294
- methods.push(item.method);
295
- console.log([ key, methods ]);
296
- }
297
- console.log();
298
-
299
- // // usage metrics
300
- // app.use(async (ctx, next) => {
301
- // await next();
302
- // await this.usageMetricsServiceI.register(ctx).catch((err) => {
303
- // this.loggerServiceI.error('KoaBootMain', 'start', 'usageMetrics', err);
304
- // });
305
- // });
306
- await fastify.register(pluginUsageMetrics, {
307
- logger: this.loggerServiceI,
308
- usageMetrics: this.usageMetricsServiceI
309
- });
310
-
311
- return {
312
- app: fastify,
313
- server: serverHttp,
314
- listen: fastify.listen
315
- };
316
- }
317
-
318
- _initAuthentication(map) {
319
- map.set('default', new authenticationDefault());
320
- return map;
321
- }
322
-
323
- _initAuthorization(map) {
324
- map.set('default', new authorizationDefault());
325
- return map;
326
- }
327
-
328
- _initAppListen(app, server, address, port, err) {
329
- app.listen(port, address, err);
330
- }
331
-
332
- async _initAppPost(app, args) {
333
- this._initPostRoutes(app);
334
- }
335
-
336
- _initCors(options) {
337
- // https://github.com/fastify/fastify-cors
338
- return options;
339
- }
340
-
341
- _initHelmet(options) {
342
- return options;
343
- }
344
-
345
- _initRoute(route) {
346
- this._routes.push(route);
347
- }
348
- }
349
-
350
- export default FastifyBootMain;
1
+ import path from 'path';
2
+
3
+ import Fastify from 'fastify';
4
+ // import fastifyAuth from 'fastify-auth';
5
+ import fastifyAuth from '../plugins/auth.js';
6
+ import fastifyCors from '@fastify/cors';
7
+ import fastifyHelmet from '@fastify/helmet';
8
+ import fastifyRoutes from '@fastify/routes';
9
+ import fastifyStatic from '@fastify/static';
10
+
11
+ import LibraryConstants from '@thzero/library_server/constants.js';
12
+
13
+ import injector from '@thzero/library_common/utility/injector.js';
14
+
15
+ import BootMain from '@thzero/library_server/boot/index.js';
16
+
17
+ import pluginApiKey from '@thzero/library_server_fastify/plugins/apiKey.js';
18
+ import pluginResponseTime from '@thzero/library_server_fastify/plugins/responseTime.js';
19
+ import pluginSettings from '@thzero/library_server_fastify/plugins/settings.js';
20
+ import pluginUsageMetrics from '@thzero/library_server_fastify/plugins/usageMetrics.js';
21
+
22
+ import authenticationDefault from '../middleware/authentication.js';
23
+ import authorizationDefault from '../middleware/authorization.js';
24
+
25
+ class FastifyBootMain extends BootMain {
26
+ async _initApp(args, plugins) {
27
+
28
+ // const serverFactory = (handler, opts) => {
29
+ // const server = http.createServer((req, res) => {
30
+ // handler(req, res)
31
+ // });
32
+
33
+ // return server;
34
+ // };
35
+
36
+ let http2 = this._appConfig.get('http2', false);
37
+ http2 = http2 === 'true' ? true : false;
38
+ this.loggerServiceI.info2(`config.http2.override: ${http2}`);
39
+
40
+ // const fastify = Fastify({ serverFactory, logger: true });
41
+ const fastify = Fastify({
42
+ http2: http2,
43
+ logger: true
44
+ });
45
+ const serverHttp = fastify.server;
46
+
47
+ await fastify.register(fastifyRoutes);
48
+
49
+ // // https://github.com/koajs/cors
50
+ // app.use(koaCors({
51
+ // allowMethods: 'GET,POST,DELETE',
52
+ // maxAge : 7200,
53
+ // allowHeaders: `${LibraryConstants.Headers.AuthKeys.API}, ${LibraryConstants.Headers.AuthKeys.AUTH}, ${LibraryConstants.Headers.CorrelationId}, Content-Type`,
54
+ // credentials: true,
55
+ // origin: '*'
56
+ // }));
57
+ // https://github.com/fastify/fastify-cors
58
+ // fastify.register(fastifyCors, {
59
+ // allowMethods: 'GET,POST,DELETE',
60
+ // maxAge : 7200,
61
+ // allowHeaders: `${LibraryConstants.Headers.AuthKeys.API}, ${LibraryConstants.Headers.AuthKeys.AUTH}, ${LibraryConstants.Headers.CorrelationId}, Content-Type`,
62
+ // credentials: true,
63
+ // origin: '*'
64
+ // });
65
+ const corsOptionsDefault = this._initCors({
66
+ allowHeaders: [ LibraryConstants.Headers.AuthKeys.API, LibraryConstants.Headers.AuthKeys.AUTH, LibraryConstants.Headers.CorrelationId, 'Content-Type' ],
67
+ credentials: true,
68
+ maxAge : 7200,
69
+ methods: ['GET', 'POST', 'DELETE'],
70
+ origin: '*'
71
+ });
72
+ await fastify.register(fastifyCors, (instance) => {
73
+ return (req, callback) => {
74
+ let corsOptions = corsOptionsDefault;
75
+ callback(null, corsOptions) // callback expects two parameters: error and options
76
+ }
77
+ });
78
+
79
+ // // https://www.npmjs.com/package/koa-helmet
80
+ // app.use(koaHelmet());
81
+ // https://github.com/fastify/fastify-helmet
82
+ const helmetOptions = this._initHelmet({
83
+ // Example disables the `contentSecurityPolicy` middleware but keeps the rest.
84
+ // contentSecurityPolicy: false
85
+ });
86
+ await fastify.register(
87
+ fastifyHelmet,
88
+ helmetOptions
89
+ );
90
+
91
+ // // error
92
+ // app.use(async (ctx, next) => {
93
+ // try {
94
+ // await next();
95
+ // }
96
+ // catch (err) {
97
+ // ctx.status = err.status || 500;
98
+ // if (err instanceof TokenExpiredError) {
99
+ // ctx.status = 401;
100
+ // ctx.response.header['WWW-Authenticate'] = 'Bearer error="invalid_token", error_description="The access token expired"'
101
+ // }
102
+ // ctx.app.emit('error', err, ctx);
103
+ // await this.usageMetricsServiceI.register(ctx, err).catch(() => {
104
+ // this.loggerServiceI.exception('KoaBootMain', 'start', err);
105
+ // });
106
+ // }
107
+ // });
108
+ await fastify.register(async (instance, opts, done) => {
109
+ // try {
110
+ // done();
111
+ // }
112
+ // catch (err) {
113
+ // let status = err.status || 500;
114
+ // if (err instanceof TokenExpiredError) {
115
+ // status = 401;
116
+ // response.header['WWW-Authenticate'] = 'Bearer error="invalid_token", error_description="The access token expired"'
117
+ // }
118
+ // app.emit('error', err, ctx);
119
+ // await this.usageMetricsServiceI.register(ctx, err).catch(() => {
120
+ // this.loggerServiceI.exception('KoaBootMain', 'start', err);
121
+ // });
122
+ // }
123
+ });
124
+
125
+ // app.on('error', (err, ctx) => {
126
+ // this.loggerServiceI.error('KoaBootMain', 'start', 'Uncaught Exception', err);
127
+ // });
128
+
129
+ // // config
130
+ // app.use(async (ctx, next) => {
131
+ // ctx.config = this._appConfig;
132
+ // await next();
133
+ // });
134
+ // // correlationId
135
+ // app.use(async (ctx, next) => {
136
+ // ctx.correlationId = ctx.request.header[LibraryConstants.Headers.CorrelationId];
137
+ // await next();
138
+ // });
139
+ // fastify.register(async (instance, opts, done) => {
140
+ // instance.addHook('onRequest', (request, reply, next) => {
141
+ // request.config = this._appConfig;
142
+ // request.correlationId = ctx.request.header[LibraryConstants.Headers.CorrelationId];
143
+ // next();
144
+ // });
145
+
146
+ // done();
147
+ // });
148
+ await fastify.register(pluginSettings, {
149
+ config: this._appConfig
150
+ });
151
+
152
+ // // logger
153
+ // app.use(async (ctx, next) => {
154
+ // await next();
155
+ // const rt = ctx.response.get(ResponseTime);
156
+ // this.loggerServiceI.info2(`${ctx.method} ${ctx.url} - ${rt}`);
157
+ // });
158
+
159
+ // // x-response-time
160
+ // app.use(async (ctx, next) => {
161
+ // const start = Utility.timerStart();
162
+ // await next();
163
+ // const delta = Utility.timerStop(start, true);
164
+ // ctx.set(ResponseTime, delta);
165
+ // });
166
+ // https://github.com/lolo32/fastify-response-time
167
+ await fastify.register(pluginResponseTime, {
168
+ logger: this.loggerServiceI
169
+ });
170
+
171
+ // app.use(koaStatic('./public'));
172
+ // https://github.com/fastify/fastify-static
173
+ const __dirname = path.resolve();
174
+ await fastify.register(fastifyStatic, {
175
+ root: path.join(__dirname, 'public'),
176
+ prefix: '/public/', // optional: default '/'
177
+ });
178
+
179
+ this._initPreAuth(fastify);
180
+
181
+ // // auth-api-token
182
+ // app.use(async (ctx, next) => {
183
+ // if (ctx.originalUrl === '/favicon.ico') {
184
+ // await next();
185
+ // return;
186
+ // }
187
+
188
+ // const key = ctx.get(LibraryConstants.Headers.AuthKeys.API);
189
+ // // this.loggerServiceI.debug('KoaBootMain', 'start', 'auth-api-token.key', key);
190
+ // if (!String.isNullOrEmpty(key)) {
191
+ // const auth = ctx.config.get('auth');
192
+ // if (auth) {
193
+ // const apiKey = auth.apiKey;
194
+ // // this.loggerServiceI.debug('KoaBootMain', 'start', 'auth-api-token.apiKey', apiKey);
195
+ // // this.loggerServiceI.debug('KoaBootMain', 'start', 'auth-api-token.key===apiKey', (key === apiKey));
196
+ // if (key === apiKey) {
197
+ // ctx.state.apiKey = key;
198
+ // await next();
199
+ // return;
200
+ // }
201
+ // }
202
+ // }
203
+
204
+ // (async () => {
205
+ // await this.usageMetricsServiceI.register(ctx).catch((err) => {
206
+ // this.loggerServiceI.error('KoaBootMain', 'start', 'usageMetrics', err);
207
+ // });
208
+ // })();
209
+
210
+ // console.log('Unauthorized... auth-api-token failure');
211
+ // ctx.throw(401);
212
+ // });
213
+ // fastify.register((instance, opts, done) => {
214
+ // instance.addHook('onRequest', (request, reply, next) => {
215
+ // if (request.originalUrl === '/favicon.ico') {
216
+ // next();
217
+ // return;
218
+ // }
219
+
220
+ // const key = request.get(LibraryConstants.Headers.AuthKeys.API);
221
+ // // this.loggerServiceI.debug('KoaBootMain', 'start', 'auth-api-token.key', key);
222
+ // if (!String.isNullOrEmpty(key)) {
223
+ // const auth = request.config.get('auth');
224
+ // if (auth) {
225
+ // const apiKey = auth.apiKey;
226
+ // // this.loggerServiceI.debug('KoaBootMain', 'start', 'auth-api-token.apiKey', apiKey);
227
+ // // this.loggerServiceI.debug('KoaBootMain', 'start', 'auth-api-token.key===apiKey', (key === apiKey));
228
+ // if (key === apiKey) {
229
+ // request.state.apiKey = key;
230
+ // next();
231
+ // return;
232
+ // }
233
+ // }
234
+ // }
235
+
236
+ // (async () => {
237
+ // await this.usageMetricsServiceI.register(ctx).catch((err) => {
238
+ // this.loggerServiceI.error('FastifyBootMain', 'start', 'usageMetrics', err);
239
+ // });
240
+ // })();
241
+
242
+ // console.log('Unauthorized... auth-api-token failure');
243
+ // request.throw(401);
244
+ // next();
245
+ // });
246
+
247
+ // done();
248
+ // });
249
+ await fastify.register(pluginApiKey, {
250
+ logger: this.loggerServiceI,
251
+ usageMetrics: this.usageMetricsServiceI
252
+ });
253
+
254
+ await fastify.register(fastifyAuth);
255
+
256
+ const capitalize = (word) => {
257
+ return word[0].toUpperCase() + word.slice(1).toLowerCase();
258
+ };
259
+
260
+ let item;
261
+ for (let [key, value] of this._initAuthentication(new Map()).entries()) {
262
+ item = value.init(injector);
263
+ fastify.decorate('authentication' + capitalize(key), item.callback);
264
+ fastify.decorate('authenticationMiddleware' + capitalize(key), item.service);
265
+ }
266
+ for (let [key, value] of this._initAuthorization(new Map()).entries()) {
267
+ item = value.init(injector);
268
+ fastify.decorate('authorization' + capitalize(key), item.callback);
269
+ fastify.decorate('authorizationMiddleware' + capitalize(key), item.service);
270
+ }
271
+
272
+ this._initPostAuth(fastify);
273
+
274
+ this._routes = [];
275
+
276
+ this._initPreRoutes(fastify);
277
+
278
+ for (const pluginRoute of plugins)
279
+ await pluginRoute.initRoutes(this._routes);
280
+
281
+ await this._initRoutes();
282
+
283
+ console.log();
284
+
285
+ for (const route of this._routes) {
286
+ console.log(route);
287
+ await route.init(injector, fastify, this._appConfig);
288
+ }
289
+
290
+ let methods;
291
+ for (let [key, value] of fastify.routes.entries()) {
292
+ methods = [];
293
+ for (let item of value)
294
+ methods.push(item.method);
295
+ console.log([ key, methods ]);
296
+ }
297
+ console.log();
298
+
299
+ // // usage metrics
300
+ // app.use(async (ctx, next) => {
301
+ // await next();
302
+ // await this.usageMetricsServiceI.register(ctx).catch((err) => {
303
+ // this.loggerServiceI.error('KoaBootMain', 'start', 'usageMetrics', err);
304
+ // });
305
+ // });
306
+ await fastify.register(pluginUsageMetrics, {
307
+ logger: this.loggerServiceI,
308
+ usageMetrics: this.usageMetricsServiceI
309
+ });
310
+
311
+ return {
312
+ app: fastify,
313
+ server: serverHttp,
314
+ listen: fastify.listen
315
+ };
316
+ }
317
+
318
+ _initAuthentication(map) {
319
+ map.set('default', new authenticationDefault());
320
+ return map;
321
+ }
322
+
323
+ _initAuthorization(map) {
324
+ map.set('default', new authorizationDefault());
325
+ return map;
326
+ }
327
+
328
+ _initAppListen(app, server, address, port, err) {
329
+ app.listen(port, address, err);
330
+ }
331
+
332
+ async _initAppPost(app, args) {
333
+ this._initPostRoutes(app);
334
+ }
335
+
336
+ _initCors(options) {
337
+ // https://github.com/fastify/fastify-cors
338
+ return options;
339
+ }
340
+
341
+ _initHelmet(options) {
342
+ return options;
343
+ }
344
+
345
+ _initRoute(route) {
346
+ this._routes.push(route);
347
+ }
348
+ }
349
+
350
+ export default FastifyBootMain;