@thzero/library_server_fastify 0.18.11 → 0.18.13

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.
@@ -1,112 +1,112 @@
1
- // https://github.com/lolo32/fastify-response-time
2
- import fastifyPlugin from 'fastify-plugin';
3
-
4
- const symbolRequestTime = Symbol('RequestTimer');
5
- const symbolServerTiming = Symbol('ServerTiming');
6
-
7
- /**
8
- *
9
- * @param {string} name
10
- * @param {number|string} duration
11
- * @param {string} description
12
- * @return {string}
13
- */
14
- const genTick = (name, duration, description) => {
15
- let val = name;
16
- // Parse duration. If could not be converted to float, does not add it
17
- duration = parseFloat(duration);
18
- if (!isNaN(duration)) {
19
- val += `;dur=${duration}`;
20
- }
21
- // Parse the description. If empty, doest not add it. If string with space, double quote value
22
- if ('string' === typeof description) {
23
- val += `;desc=${description.includes(' ') ? `'${description}'` : description}`;
24
- }
25
-
26
- return val;
27
- };
28
-
29
- /**
30
- * Decorators
31
- *
32
- * @param {fastify} instance
33
- * @param {function} instance.decorateReply
34
- * @param {Object} opts
35
- * @param {function} next
36
- */
37
- export default fastifyPlugin((instance, opts, done) => {
38
- // Check the options, and corrects with the default values if inadequate
39
- if (isNaN(opts.digits) || 0 > opts.digits) {
40
- opts.digits = 2;
41
- }
42
- opts.header = opts.header || 'X-Response-Time';
43
-
44
- // Hook to be triggered on request (start time)
45
- instance.addHook('onRequest', (request, reply, next) => {
46
- // Store the start timer in nanoseconds resolution
47
- // istanbul ignore next
48
- if (request.raw && reply.raw) {
49
- // support fastify >= v2
50
- request.raw[symbolRequestTime] = process.hrtime();
51
- reply.raw[symbolServerTiming] = {};
52
- }
53
- else if (request.req && reply.res) {
54
- // support fastify >= v2
55
- request.req[symbolRequestTime] = process.hrtime();
56
- reply.res[symbolServerTiming] = {};
57
- }
58
- else {
59
- request[symbolRequestTime] = process.hrtime();
60
- reply[symbolServerTiming] = {};
61
- }
62
-
63
- next();
64
- });
65
-
66
- // Hook to be triggered just before response to be send
67
- instance.addHook('onSend', (request, reply, payload, next) => {
68
- const headers = [];
69
-
70
- // check if Server-Timing need to be added
71
- const serverTiming = (reply.raw ? reply.raw[symbolServerTiming] : reply.res[symbolServerTiming]);
72
- if (serverTiming) {
73
- for (const name of Object.keys(serverTiming)) {
74
- headers.push(serverTiming[name]);
75
- }
76
- if (headers.length) {
77
- reply.header('Server-Timing', headers.join(','));
78
- }
79
- }
80
-
81
- // Calculate the duration, in nanoseconds …
82
- const hrDuration = (request.raw ? request.raw[symbolRequestTime] : request.req[symbolRequestTime]);
83
- if (hrDuration) {
84
- // … convert it to milliseconds …
85
- const duration = (hrDuration[0] * 1e3 + hrDuration[1] / 1e6).toFixed(opts.digits);
86
- // … add the header to the response
87
- reply.header(opts.header, duration);
88
-
89
- opts.logger.info2(`${request.method} ${request.url} - ${duration}`);
90
- }
91
-
92
- next();
93
- });
94
-
95
- // Can be used to add custom timing information
96
- instance.decorateReply('setServerTiming', function (name, duration, description) {
97
- // Reference to the res object storing values …
98
- const serverTiming = this.res[symbolServerTiming];
99
- // … return if value already exists (all subsequent occurrences MUST be ignored without signaling an error) …
100
- if (serverTiming.hasOwnProperty(name)) {
101
- return false;
102
- }
103
- // … add the value the the list to send later
104
- serverTiming[name] = genTick(name, duration, description);
105
- // … return true, the value was added to the list
106
- return true;
107
- });
108
-
109
- done();
110
- });
111
- // Not before 0.31 (onSend hook added to this version)
1
+ // https://github.com/lolo32/fastify-response-time
2
+ import fastifyPlugin from 'fastify-plugin';
3
+
4
+ const symbolRequestTime = Symbol('RequestTimer');
5
+ const symbolServerTiming = Symbol('ServerTiming');
6
+
7
+ /**
8
+ *
9
+ * @param {string} name
10
+ * @param {number|string} duration
11
+ * @param {string} description
12
+ * @return {string}
13
+ */
14
+ const genTick = (name, duration, description) => {
15
+ let val = name;
16
+ // Parse duration. If could not be converted to float, does not add it
17
+ duration = parseFloat(duration);
18
+ if (!isNaN(duration)) {
19
+ val += `;dur=${duration}`;
20
+ }
21
+ // Parse the description. If empty, doest not add it. If string with space, double quote value
22
+ if ('string' === typeof description) {
23
+ val += `;desc=${description.includes(' ') ? `'${description}'` : description}`;
24
+ }
25
+
26
+ return val;
27
+ };
28
+
29
+ /**
30
+ * Decorators
31
+ *
32
+ * @param {fastify} instance
33
+ * @param {function} instance.decorateReply
34
+ * @param {Object} opts
35
+ * @param {function} next
36
+ */
37
+ export default fastifyPlugin((instance, opts, done) => {
38
+ // Check the options, and corrects with the default values if inadequate
39
+ if (isNaN(opts.digits) || 0 > opts.digits) {
40
+ opts.digits = 2;
41
+ }
42
+ opts.header = opts.header || 'X-Response-Time';
43
+
44
+ // Hook to be triggered on request (start time)
45
+ instance.addHook('onRequest', (request, reply, next) => {
46
+ // Store the start timer in nanoseconds resolution
47
+ // istanbul ignore next
48
+ if (request.raw && reply.raw) {
49
+ // support fastify >= v2
50
+ request.raw[symbolRequestTime] = process.hrtime();
51
+ reply.raw[symbolServerTiming] = {};
52
+ }
53
+ else if (request.req && reply.res) {
54
+ // support fastify >= v2
55
+ request.req[symbolRequestTime] = process.hrtime();
56
+ reply.res[symbolServerTiming] = {};
57
+ }
58
+ else {
59
+ request[symbolRequestTime] = process.hrtime();
60
+ reply[symbolServerTiming] = {};
61
+ }
62
+
63
+ next();
64
+ });
65
+
66
+ // Hook to be triggered just before response to be send
67
+ instance.addHook('onSend', (request, reply, payload, next) => {
68
+ const headers = [];
69
+
70
+ // check if Server-Timing need to be added
71
+ const serverTiming = (reply.raw ? reply.raw[symbolServerTiming] : reply.res[symbolServerTiming]);
72
+ if (serverTiming) {
73
+ for (const name of Object.keys(serverTiming)) {
74
+ headers.push(serverTiming[name]);
75
+ }
76
+ if (headers.length) {
77
+ reply.header('Server-Timing', headers.join(','));
78
+ }
79
+ }
80
+
81
+ // Calculate the duration, in nanoseconds …
82
+ const hrDuration = (request.raw ? request.raw[symbolRequestTime] : request.req[symbolRequestTime]);
83
+ if (hrDuration) {
84
+ // … convert it to milliseconds …
85
+ const duration = (hrDuration[0] * 1e3 + hrDuration[1] / 1e6).toFixed(opts.digits);
86
+ // … add the header to the response
87
+ reply.header(opts.header, duration);
88
+
89
+ opts.logger.info2(`${request.method} ${request.url} - ${duration}`);
90
+ }
91
+
92
+ next();
93
+ });
94
+
95
+ // Can be used to add custom timing information
96
+ instance.decorateReply('setServerTiming', function (name, duration, description) {
97
+ // Reference to the res object storing values …
98
+ const serverTiming = this.res[symbolServerTiming];
99
+ // … return if value already exists (all subsequent occurrences MUST be ignored without signaling an error) …
100
+ if (serverTiming.hasOwnProperty(name)) {
101
+ return false;
102
+ }
103
+ // … add the value the the list to send later
104
+ serverTiming[name] = genTick(name, duration, description);
105
+ // … return true, the value was added to the list
106
+ return true;
107
+ });
108
+
109
+ done();
110
+ });
111
+ // Not before 0.31 (onSend hook added to this version)
112
112
  // }, '>= 0.31');
@@ -1,13 +1,13 @@
1
- import fastifyPlugin from 'fastify-plugin';
2
-
3
- import LibraryServerConstants from '@thzero/library_server/constants.js';
4
-
5
- export default fastifyPlugin((instance, opts, done) => {
6
- instance.addHook('onRequest', (request, reply, next) => {
7
- request.config = opts.config;
8
- request.correlationId = request.headers[LibraryServerConstants.Headers.CorrelationId];
9
- next();
10
- });
11
-
12
- done();
1
+ import fastifyPlugin from 'fastify-plugin';
2
+
3
+ import LibraryServerConstants from '@thzero/library_server/constants.js';
4
+
5
+ export default fastifyPlugin((instance, opts, done) => {
6
+ instance.addHook('onRequest', (request, reply, next) => {
7
+ request.config = opts.config;
8
+ request.correlationId = request.headers[LibraryServerConstants.Headers.CorrelationId];
9
+ next();
10
+ });
11
+
12
+ done();
13
13
  });
@@ -1,25 +1,25 @@
1
- import fastifyPlugin from 'fastify-plugin';
2
-
3
- export default fastifyPlugin((instance, opts, done) => {
4
- instance.addHook('onSend', (request, reply, payload, next) => {
5
- (async () => {
6
- const usageMetrics = {
7
- url: request.routeOptions.url,
8
- correlationId: request.correlationId,
9
- href: request.url,
10
- headers: request.headers,
11
- host: request.hostname,
12
- hostname: request.hostname,
13
- querystring: request.query,
14
- token: request.token
15
- };
16
- await opts.usageMetrics.register(usageMetrics).catch((err) => {
17
- opts.logger.error('usageMetrics', 'start', 'usageMetrics', err);
18
- });
19
- })();
20
-
21
- next();
22
- });
23
-
24
- done();
1
+ import fastifyPlugin from 'fastify-plugin';
2
+
3
+ export default fastifyPlugin((instance, opts, done) => {
4
+ instance.addHook('onSend', (request, reply, payload, next) => {
5
+ (async () => {
6
+ const usageMetrics = {
7
+ url: request.routeOptions.url,
8
+ correlationId: request.correlationId,
9
+ href: request.url,
10
+ headers: request.headers,
11
+ host: request.hostname,
12
+ hostname: request.hostname,
13
+ querystring: request.query,
14
+ token: request.token
15
+ };
16
+ await opts.usageMetrics.register(usageMetrics).catch((err) => {
17
+ opts.logger.error('usageMetrics', 'start', 'usageMetrics', err);
18
+ });
19
+ })();
20
+
21
+ next();
22
+ });
23
+
24
+ done();
25
25
  });
@@ -1,140 +1,140 @@
1
- import BaseRoute from '../index.js';
2
-
3
- class AdminBaseRoute extends BaseRoute {
4
- constructor(urlFragment, role, serviceKey) {
5
- if (!urlFragment)
6
- throw Error('Invalid url fragment');
7
-
8
- super(`/admin/${urlFragment}`);
9
-
10
- this._options = {
11
- role: role,
12
- serviceKey: serviceKey
13
- }
14
-
15
- // this._service = null;
16
- }
17
-
18
- async init(injector, app, config) {
19
- await super.init(injector, app, config);
20
- this._inject(app, injector, this._options.serviceKey, this._options.serviceKey);
21
- }
22
-
23
- _allowsCreate() {
24
- return true;
25
- }
26
-
27
- _allowsDelete() {
28
- return true;
29
- }
30
-
31
- _allowsUpdate() {
32
- return true;
33
- }
34
-
35
- _initializeRoutesCreate(router) {
36
- const self = this;
37
- router.post(this._join(''),
38
- // authentication(true),
39
- // authorization([ `${self._options.role}.create` ]),
40
- {
41
- preHandler: router.auth([
42
- router.authenticationDefault,
43
- router.authorizationDefault
44
- ],
45
- {
46
- relation: 'and',
47
- roles: [ `${self._options.role}.create` ]
48
- }),
49
- },
50
- // eslint-disable-next-line
51
- async (request, reply) => {
52
- const response = (await router[this._options.serviceKey].create(request.correlationId, request.user, request.body)).check(request);
53
- // https://github.com/fastify/fastify-compress/issues/215#issuecomment-1210598312
54
- return this._jsonResponse(reply, response);
55
- }
56
- );
57
- }
58
-
59
- _initializeRoutesDelete(router) {
60
- router.delete(this._join('/:id'),
61
- // authentication(true),
62
- // authorization([ `${this._options.role}.delete` ]),
63
- {
64
- preHandler: router.auth([
65
- router.authenticationDefault,
66
- router.authorizationDefault
67
- ],
68
- {
69
- relation: 'and',
70
- roles: [ `${this._options.role}.delete` ]
71
- }),
72
- },
73
- // eslint-disable-next-line
74
- async (request, reply) => {
75
- const response = (await router[this._options.serviceKey].delete(request.correlationId, request.user, request.params.id)).check(request);
76
- // https://github.com/fastify/fastify-compress/issues/215#issuecomment-1210598312
77
- return this._jsonResponse(reply, response);
78
- }
79
- );
80
- }
81
-
82
- _initializeRoutesUpdate(router) {
83
- router.post(this._join('/:id'),
84
- // authentication(true),
85
- // authorization([ `${this._options.role}.update` ]),
86
- {
87
- preHandler: router.auth([
88
- router.authenticationDefault,
89
- router.authorizationDefault
90
- ],
91
- {
92
- relation: 'and',
93
- roles: [ `${this._options.role}.update` ]
94
- }),
95
- },
96
- // eslint-disable-next-line
97
- async (request, reply) => {
98
- const response = (await router[this._options.serviceKey].update(request.correlationId, request.user, request.params.id, request.body)).check(request);
99
- // https://github.com/fastify/fastify-compress/issues/215#issuecomment-1210598312
100
- return this._jsonResponse(reply, response);
101
- }
102
- );
103
- }
104
-
105
- _initializeRoutes(router) {
106
- if (this._allowsDelete)
107
- this._initializeRoutesDelete(router);
108
-
109
- router.post(this._join('/search'),
110
- // authentication(true),
111
- // authorization([ `${this._options.role}.search` ]),
112
- {
113
- preHandler: router.auth([
114
- router.authenticationDefault,
115
- router.authorizationDefault
116
- ],
117
- {
118
- relation: 'and',
119
- roles: [ `${this._options.role}.search` ]
120
- }),
121
- },
122
- // eslint-disable-next-line
123
- async (request, reply) => {
124
- const response = (await router[this._options.serviceKey].search(request.correlationId, request.user, request.body)).check(request);
125
- // https://github.com/fastify/fastify-compress/issues/215#issuecomment-1210598312
126
- return this._jsonResponse(reply, response);
127
- }
128
- );
129
-
130
- if (this._allowsUpdate())
131
- this._initializeRoutesUpdate(router);
132
-
133
- if (this._allowsCreate())
134
- this._initializeRoutesCreate(router);
135
-
136
- return router;
137
- }
138
- }
139
-
140
- export default AdminBaseRoute;
1
+ import BaseRoute from '../index.js';
2
+
3
+ class AdminBaseRoute extends BaseRoute {
4
+ constructor(urlFragment, role, serviceKey) {
5
+ if (!urlFragment)
6
+ throw Error('Invalid url fragment');
7
+
8
+ super(`/admin/${urlFragment}`);
9
+
10
+ this._options = {
11
+ role: role,
12
+ serviceKey: serviceKey
13
+ }
14
+
15
+ // this._service = null;
16
+ }
17
+
18
+ async init(injector, app, config) {
19
+ await super.init(injector, app, config);
20
+ this._inject(app, injector, this._options.serviceKey, this._options.serviceKey);
21
+ }
22
+
23
+ _allowsCreate() {
24
+ return true;
25
+ }
26
+
27
+ _allowsDelete() {
28
+ return true;
29
+ }
30
+
31
+ _allowsUpdate() {
32
+ return true;
33
+ }
34
+
35
+ _initializeRoutesCreate(router) {
36
+ const self = this;
37
+ router.post(this._join(''),
38
+ // authentication(true),
39
+ // authorization([ `${self._options.role}.create` ]),
40
+ {
41
+ preHandler: router.auth([
42
+ router.authenticationDefault,
43
+ router.authorizationDefault
44
+ ],
45
+ {
46
+ relation: 'and',
47
+ roles: [ `${self._options.role}.create` ]
48
+ }),
49
+ },
50
+ // eslint-disable-next-line
51
+ async (request, reply) => {
52
+ const response = (await router[this._options.serviceKey].create(request.correlationId, request.user, request.body)).check(request);
53
+ // https://github.com/fastify/fastify-compress/issues/215#issuecomment-1210598312
54
+ return this._jsonResponse(reply, response);
55
+ }
56
+ );
57
+ }
58
+
59
+ _initializeRoutesDelete(router) {
60
+ router.delete(this._join('/:id'),
61
+ // authentication(true),
62
+ // authorization([ `${this._options.role}.delete` ]),
63
+ {
64
+ preHandler: router.auth([
65
+ router.authenticationDefault,
66
+ router.authorizationDefault
67
+ ],
68
+ {
69
+ relation: 'and',
70
+ roles: [ `${this._options.role}.delete` ]
71
+ }),
72
+ },
73
+ // eslint-disable-next-line
74
+ async (request, reply) => {
75
+ const response = (await router[this._options.serviceKey].delete(request.correlationId, request.user, request.params.id)).check(request);
76
+ // https://github.com/fastify/fastify-compress/issues/215#issuecomment-1210598312
77
+ return this._jsonResponse(reply, response);
78
+ }
79
+ );
80
+ }
81
+
82
+ _initializeRoutesUpdate(router) {
83
+ router.post(this._join('/:id'),
84
+ // authentication(true),
85
+ // authorization([ `${this._options.role}.update` ]),
86
+ {
87
+ preHandler: router.auth([
88
+ router.authenticationDefault,
89
+ router.authorizationDefault
90
+ ],
91
+ {
92
+ relation: 'and',
93
+ roles: [ `${this._options.role}.update` ]
94
+ }),
95
+ },
96
+ // eslint-disable-next-line
97
+ async (request, reply) => {
98
+ const response = (await router[this._options.serviceKey].update(request.correlationId, request.user, request.params.id, request.body)).check(request);
99
+ // https://github.com/fastify/fastify-compress/issues/215#issuecomment-1210598312
100
+ return this._jsonResponse(reply, response);
101
+ }
102
+ );
103
+ }
104
+
105
+ _initializeRoutes(router) {
106
+ if (this._allowsDelete)
107
+ this._initializeRoutesDelete(router);
108
+
109
+ router.post(this._join('/search'),
110
+ // authentication(true),
111
+ // authorization([ `${this._options.role}.search` ]),
112
+ {
113
+ preHandler: router.auth([
114
+ router.authenticationDefault,
115
+ router.authorizationDefault
116
+ ],
117
+ {
118
+ relation: 'and',
119
+ roles: [ `${this._options.role}.search` ]
120
+ }),
121
+ },
122
+ // eslint-disable-next-line
123
+ async (request, reply) => {
124
+ const response = (await router[this._options.serviceKey].search(request.correlationId, request.user, request.body)).check(request);
125
+ // https://github.com/fastify/fastify-compress/issues/215#issuecomment-1210598312
126
+ return this._jsonResponse(reply, response);
127
+ }
128
+ );
129
+
130
+ if (this._allowsUpdate())
131
+ this._initializeRoutesUpdate(router);
132
+
133
+ if (this._allowsCreate())
134
+ this._initializeRoutesCreate(router);
135
+
136
+ return router;
137
+ }
138
+ }
139
+
140
+ export default AdminBaseRoute;
@@ -1,22 +1,22 @@
1
- import LibraryServerConstants from '@thzero/library_server/constants.js';
2
-
3
- import AdminRoute from './index.js';
4
-
5
- class NewsAdminRoute extends AdminRoute {
6
- constructor(urlFragment, role, serviceKey) {
7
- urlFragment = urlFragment ? urlFragment : 'news';
8
- role = role ? role : 'news';
9
- serviceKey = serviceKey ? serviceKey : LibraryServerConstants.InjectorKeys.SERVICE_ADMIN_NEWS;
10
- super(urlFragment, role, serviceKey);
11
- }
12
-
13
- get id() {
14
- return 'admin-news';
15
- }
16
-
17
- get _version() {
18
- return 'v1';
19
- }
20
- }
21
-
22
- export default NewsAdminRoute;
1
+ import LibraryServerConstants from '@thzero/library_server/constants.js';
2
+
3
+ import AdminRoute from './index.js';
4
+
5
+ class NewsAdminRoute extends AdminRoute {
6
+ constructor(urlFragment, role, serviceKey) {
7
+ urlFragment = urlFragment ? urlFragment : 'news';
8
+ role = role ? role : 'news';
9
+ serviceKey = serviceKey ? serviceKey : LibraryServerConstants.InjectorKeys.SERVICE_ADMIN_NEWS;
10
+ super(urlFragment, role, serviceKey);
11
+ }
12
+
13
+ get id() {
14
+ return 'admin-news';
15
+ }
16
+
17
+ get _version() {
18
+ return 'v1';
19
+ }
20
+ }
21
+
22
+ export default NewsAdminRoute;