@thzero/library_server_fastify 0.17.17 → 0.17.18

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,367 +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 fastifyCompression 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 LibraryServerConstants 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: `${LibraryServerConstants.Headers.AuthKeys.API}, ${LibraryServerConstants.Headers.AuthKeys.AUTH}, ${ServerConstants.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: `${LibraryServerConstants.Headers.AuthKeys.API}, ${LibraryServerConstants.Headers.AuthKeys.AUTH}, ${ServerConstants.Headers.CorrelationId}, Content-Type`,
63
- // credentials: true,
64
- // origin: '*'
65
- // });
66
- const corsOptionsDefault = this._initCors({
67
- allowHeaders: [ LibraryServerConstants.Headers.AuthKeys.API, LibraryServerConstants.Headers.AuthKeys.AUTH, LibraryServerConstants.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
- fastifyCompression,
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[LibraryServerConstants.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[LibraryServerConstants.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(LibraryServerConstants.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(LibraryServerConstants.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;
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 fastifyCompression 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 LibraryServerConstants 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: `${LibraryServerConstants.Headers.AuthKeys.API}, ${LibraryServerConstants.Headers.AuthKeys.AUTH}, ${ServerConstants.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: `${LibraryServerConstants.Headers.AuthKeys.API}, ${LibraryServerConstants.Headers.AuthKeys.AUTH}, ${ServerConstants.Headers.CorrelationId}, Content-Type`,
63
+ // credentials: true,
64
+ // origin: '*'
65
+ // });
66
+ const corsOptionsDefault = this._initCors({
67
+ allowHeaders: [ LibraryServerConstants.Headers.AuthKeys.API, LibraryServerConstants.Headers.AuthKeys.AUTH, LibraryServerConstants.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
+ fastifyCompression,
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[LibraryServerConstants.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[LibraryServerConstants.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(LibraryServerConstants.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(LibraryServerConstants.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;