@thzero/library_server_fastify 0.16.8 → 0.16.9

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