@twin.org/api-server-fastify 0.0.1-next.10

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/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2024 IOTA Stiftung.
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,21 @@
1
+ # TWIN API Server Fastify
2
+
3
+ Use [Fastify](https://fastify.dev/) as the core web server for APIs.
4
+
5
+ ## Installation
6
+
7
+ ```shell
8
+ npm install @twin.org/api-server-fastify
9
+ ```
10
+
11
+ ## Examples
12
+
13
+ Usage of the APIs is shown in the examples [docs/examples.md](docs/examples.md)
14
+
15
+ ## Reference
16
+
17
+ Detailed reference documentation for the API can be found in [docs/reference/index.md](docs/reference/index.md)
18
+
19
+ ## Changelog
20
+
21
+ The changes between each version can be found in [docs/changelog.md](docs/changelog.md)
@@ -0,0 +1,297 @@
1
+ 'use strict';
2
+
3
+ var FastifyCompress = require('@fastify/compress');
4
+ var FastifyCors = require('@fastify/cors');
5
+ var apiModels = require('@twin.org/api-models');
6
+ var core = require('@twin.org/core');
7
+ var loggingModels = require('@twin.org/logging-models');
8
+ var web = require('@twin.org/web');
9
+ var Fastify = require('fastify');
10
+
11
+ // Copyright 2024 IOTA Stiftung.
12
+ // SPDX-License-Identifier: Apache-2.0.
13
+ /**
14
+ * Implementation of the web server using Fastify.
15
+ */
16
+ class FastifyWebServer {
17
+ /**
18
+ * Runtime name for the class in camel case.
19
+ * @internal
20
+ */
21
+ static _CLASS_NAME_CAMEL_CASE = core.StringHelper.camelCase("FastifyWebServer");
22
+ /**
23
+ * Default port for running the server.
24
+ * @internal
25
+ */
26
+ static _DEFAULT_PORT = 3000;
27
+ /**
28
+ * Default host for running the server.
29
+ * @internal
30
+ */
31
+ static _DEFAULT_HOST = "localhost";
32
+ /**
33
+ * Runtime name for the class.
34
+ */
35
+ CLASS_NAME = "FastifyWebServer";
36
+ /**
37
+ * The logging connector.
38
+ * @internal
39
+ */
40
+ _loggingConnector;
41
+ /**
42
+ * The options for the server.
43
+ * @internal
44
+ */
45
+ _options;
46
+ /**
47
+ * The Fastify instance.
48
+ * @internal
49
+ */
50
+ _fastify;
51
+ /**
52
+ * Whether the server has been started.
53
+ * @internal
54
+ */
55
+ _started;
56
+ /**
57
+ * Create a new instance of FastifyWebServer.
58
+ * @param options The options for the server.
59
+ * @param options.loggingConnectorType The type of the logging connector to use, if undefined, no logging will happen.
60
+ * @param options.config Additional options for the Fastify server.
61
+ */
62
+ constructor(options) {
63
+ this._loggingConnector = core.Is.stringValue(options?.loggingConnectorType)
64
+ ? loggingModels.LoggingConnectorFactory.get(options.loggingConnectorType)
65
+ : undefined;
66
+ this._fastify = Fastify({ maxParamLength: 2000, ...options?.config });
67
+ this._started = false;
68
+ }
69
+ /**
70
+ * Get the web server instance.
71
+ * @returns The web server instance.
72
+ */
73
+ getInstance() {
74
+ return this._fastify;
75
+ }
76
+ /**
77
+ * Build the server.
78
+ * @param restRouteProcessors The hooks to process the incoming requests.
79
+ * @param restRoutes The REST routes.
80
+ * @param options Options for building the server.
81
+ * @returns Nothing.
82
+ */
83
+ async build(restRouteProcessors, restRoutes, options) {
84
+ if (!core.Is.arrayValue(restRouteProcessors)) {
85
+ throw new core.GeneralError(this.CLASS_NAME, "noProcessors");
86
+ }
87
+ await this._loggingConnector?.log({
88
+ level: "info",
89
+ ts: Date.now(),
90
+ source: this.CLASS_NAME,
91
+ message: `${FastifyWebServer._CLASS_NAME_CAMEL_CASE}.building`
92
+ });
93
+ this._options = options;
94
+ await this._fastify.register(FastifyCompress);
95
+ await this.initCors(options);
96
+ this._fastify.setNotFoundHandler({}, async (request, reply) => this.handleRequest(restRouteProcessors, request, reply));
97
+ this._fastify.setErrorHandler(async (error, request, reply) => {
98
+ // If code property is set this is a fastify error
99
+ // otherwise it's from our framework
100
+ let httpStatusCode;
101
+ let err;
102
+ if (core.Is.number(error.code)) {
103
+ err = {
104
+ source: this.CLASS_NAME,
105
+ name: error.name,
106
+ message: `${error.code}: ${error.message}`
107
+ };
108
+ httpStatusCode = error.statusCode ?? web.HttpStatusCode.badRequest;
109
+ }
110
+ else {
111
+ const errorAndCode = apiModels.HttpErrorHelper.processError(error);
112
+ err = errorAndCode.error;
113
+ httpStatusCode = errorAndCode.httpStatusCode;
114
+ }
115
+ await this._loggingConnector?.log({
116
+ level: "error",
117
+ ts: Date.now(),
118
+ source: this.CLASS_NAME,
119
+ message: `${FastifyWebServer._CLASS_NAME_CAMEL_CASE}.badRequest`,
120
+ error: err
121
+ });
122
+ return reply.status(httpStatusCode).send({
123
+ error: err
124
+ });
125
+ });
126
+ // Add the routes to the server.
127
+ for (const restRoute of restRoutes) {
128
+ let path = core.StringHelper.trimTrailingSlashes(restRoute.path);
129
+ if (!path.startsWith("/")) {
130
+ path = `/${path}`;
131
+ }
132
+ await this._loggingConnector?.log({
133
+ level: "info",
134
+ ts: Date.now(),
135
+ source: this.CLASS_NAME,
136
+ message: `${FastifyWebServer._CLASS_NAME_CAMEL_CASE}.restRouteAdded`,
137
+ data: { route: path, method: restRoute.method }
138
+ });
139
+ const method = restRoute.method.toLowerCase();
140
+ this._fastify[method](path, async (request, reply) => this.handleRequest(restRouteProcessors, request, reply, restRoute));
141
+ }
142
+ }
143
+ /**
144
+ * Start the server.
145
+ * @returns Nothing.
146
+ */
147
+ async start() {
148
+ const host = this._options?.host ?? FastifyWebServer._DEFAULT_HOST;
149
+ const port = this._options?.port ?? FastifyWebServer._DEFAULT_PORT;
150
+ await this._loggingConnector?.log({
151
+ level: "info",
152
+ ts: Date.now(),
153
+ source: this.CLASS_NAME,
154
+ message: `${FastifyWebServer._CLASS_NAME_CAMEL_CASE}.starting`,
155
+ data: {
156
+ host,
157
+ port
158
+ }
159
+ });
160
+ if (!this._started) {
161
+ try {
162
+ await this._fastify.listen({ port, host });
163
+ const addresses = this._fastify.addresses();
164
+ const protocol = core.Is.object(this._fastify.initialConfig.https) ? "https://" : "http://";
165
+ await this._loggingConnector?.log({
166
+ level: "info",
167
+ ts: Date.now(),
168
+ source: this.CLASS_NAME,
169
+ message: `${FastifyWebServer._CLASS_NAME_CAMEL_CASE}.started`,
170
+ data: {
171
+ addresses: addresses
172
+ .map(a => `${protocol}${a.family === "IPv6" ? "[" : ""}${a.address}${a.family === "IPv6" ? "]" : ""}:${a.port}`)
173
+ .join(", ")
174
+ }
175
+ });
176
+ this._started = true;
177
+ }
178
+ catch (err) {
179
+ await this._loggingConnector?.log({
180
+ level: "error",
181
+ ts: Date.now(),
182
+ source: this.CLASS_NAME,
183
+ message: `${FastifyWebServer._CLASS_NAME_CAMEL_CASE}.startFailed`,
184
+ error: core.BaseError.fromError(err)
185
+ });
186
+ }
187
+ }
188
+ }
189
+ /**
190
+ * Stop the server.
191
+ * @returns Nothing.
192
+ */
193
+ async stop() {
194
+ if (this._started) {
195
+ this._started = false;
196
+ await this._fastify.close();
197
+ await this._loggingConnector?.log({
198
+ level: "info",
199
+ ts: Date.now(),
200
+ source: this.CLASS_NAME,
201
+ message: `${FastifyWebServer._CLASS_NAME_CAMEL_CASE}.stopped`
202
+ });
203
+ }
204
+ }
205
+ /**
206
+ * Handle the incoming request.
207
+ * @param restRouteProcessors The hooks to process the incoming requests.
208
+ * @param request The incoming request.
209
+ * @param reply The outgoing response.
210
+ * @param restRoute The REST route to handle.
211
+ * @internal
212
+ */
213
+ async handleRequest(restRouteProcessors, request, reply, restRoute) {
214
+ const httpServerRequest = {
215
+ method: request.method.toUpperCase(),
216
+ url: `${request.protocol}://${request.hostname}${request.url}`,
217
+ body: request.body,
218
+ query: request.query,
219
+ pathParams: request.params,
220
+ headers: request.headers
221
+ };
222
+ const httpResponse = {};
223
+ const httpRequestIdentity = {};
224
+ const processorState = {};
225
+ for (const restRouteProcessor of restRouteProcessors) {
226
+ if (core.Is.function(restRouteProcessor.pre)) {
227
+ await restRouteProcessor.pre(httpServerRequest, httpResponse, restRoute, httpRequestIdentity, processorState);
228
+ }
229
+ }
230
+ for (const restRouteProcessor of restRouteProcessors) {
231
+ if (core.Is.function(restRouteProcessor.process)) {
232
+ await restRouteProcessor.process(httpServerRequest, httpResponse, restRoute, httpRequestIdentity, processorState);
233
+ }
234
+ }
235
+ for (const restRouteProcessor of restRouteProcessors) {
236
+ if (core.Is.function(restRouteProcessor.post)) {
237
+ await restRouteProcessor.post(httpServerRequest, httpResponse, restRoute, httpRequestIdentity, processorState);
238
+ }
239
+ }
240
+ if (!core.Is.empty(httpResponse.headers)) {
241
+ for (const header of Object.keys(httpResponse.headers)) {
242
+ reply.header(header, httpResponse.headers[header]);
243
+ }
244
+ }
245
+ return reply
246
+ .status((httpResponse.statusCode ?? web.HttpStatusCode.ok))
247
+ .send(httpResponse.body);
248
+ }
249
+ /**
250
+ * Initialize the cors options.
251
+ * @param options The web server options.
252
+ * @internal
253
+ */
254
+ async initCors(options) {
255
+ let origins = ["*"];
256
+ if (core.Is.arrayValue(options?.corsOrigins)) {
257
+ origins = options?.corsOrigins;
258
+ }
259
+ else if (core.Is.stringValue(options?.corsOrigins)) {
260
+ origins = [options?.corsOrigins];
261
+ }
262
+ const hasWildcardOrigin = origins.includes("*");
263
+ const methods = options?.methods ?? [
264
+ web.HttpMethod.GET,
265
+ web.HttpMethod.PUT,
266
+ web.HttpMethod.POST,
267
+ web.HttpMethod.DELETE,
268
+ web.HttpMethod.OPTIONS
269
+ ];
270
+ const allowedHeaders = [
271
+ "Access-Control-Allow-Origin",
272
+ "Content-Encoding",
273
+ "Accept-Encoding",
274
+ web.HeaderTypes.ContentType,
275
+ web.HeaderTypes.Authorization,
276
+ web.HeaderTypes.Accept
277
+ ];
278
+ const exposedHeaders = [web.HeaderTypes.ContentDisposition, web.HeaderTypes.Location];
279
+ if (core.Is.arrayValue(options?.allowedHeaders)) {
280
+ allowedHeaders.push(...options.allowedHeaders);
281
+ }
282
+ if (core.Is.arrayValue(options?.exposedHeaders)) {
283
+ exposedHeaders.push(...options.exposedHeaders);
284
+ }
285
+ await this._fastify.register(FastifyCors, {
286
+ origin: (origin, callback) => {
287
+ callback(null, hasWildcardOrigin ? true : origins.includes(origin));
288
+ },
289
+ methods,
290
+ allowedHeaders,
291
+ exposedHeaders,
292
+ credentials: true
293
+ });
294
+ }
295
+ }
296
+
297
+ exports.FastifyWebServer = FastifyWebServer;
@@ -0,0 +1,295 @@
1
+ import FastifyCompress from '@fastify/compress';
2
+ import FastifyCors from '@fastify/cors';
3
+ import { HttpErrorHelper } from '@twin.org/api-models';
4
+ import { StringHelper, Is, GeneralError, BaseError } from '@twin.org/core';
5
+ import { LoggingConnectorFactory } from '@twin.org/logging-models';
6
+ import { HttpStatusCode, HttpMethod, HeaderTypes } from '@twin.org/web';
7
+ import Fastify from 'fastify';
8
+
9
+ // Copyright 2024 IOTA Stiftung.
10
+ // SPDX-License-Identifier: Apache-2.0.
11
+ /**
12
+ * Implementation of the web server using Fastify.
13
+ */
14
+ class FastifyWebServer {
15
+ /**
16
+ * Runtime name for the class in camel case.
17
+ * @internal
18
+ */
19
+ static _CLASS_NAME_CAMEL_CASE = StringHelper.camelCase("FastifyWebServer");
20
+ /**
21
+ * Default port for running the server.
22
+ * @internal
23
+ */
24
+ static _DEFAULT_PORT = 3000;
25
+ /**
26
+ * Default host for running the server.
27
+ * @internal
28
+ */
29
+ static _DEFAULT_HOST = "localhost";
30
+ /**
31
+ * Runtime name for the class.
32
+ */
33
+ CLASS_NAME = "FastifyWebServer";
34
+ /**
35
+ * The logging connector.
36
+ * @internal
37
+ */
38
+ _loggingConnector;
39
+ /**
40
+ * The options for the server.
41
+ * @internal
42
+ */
43
+ _options;
44
+ /**
45
+ * The Fastify instance.
46
+ * @internal
47
+ */
48
+ _fastify;
49
+ /**
50
+ * Whether the server has been started.
51
+ * @internal
52
+ */
53
+ _started;
54
+ /**
55
+ * Create a new instance of FastifyWebServer.
56
+ * @param options The options for the server.
57
+ * @param options.loggingConnectorType The type of the logging connector to use, if undefined, no logging will happen.
58
+ * @param options.config Additional options for the Fastify server.
59
+ */
60
+ constructor(options) {
61
+ this._loggingConnector = Is.stringValue(options?.loggingConnectorType)
62
+ ? LoggingConnectorFactory.get(options.loggingConnectorType)
63
+ : undefined;
64
+ this._fastify = Fastify({ maxParamLength: 2000, ...options?.config });
65
+ this._started = false;
66
+ }
67
+ /**
68
+ * Get the web server instance.
69
+ * @returns The web server instance.
70
+ */
71
+ getInstance() {
72
+ return this._fastify;
73
+ }
74
+ /**
75
+ * Build the server.
76
+ * @param restRouteProcessors The hooks to process the incoming requests.
77
+ * @param restRoutes The REST routes.
78
+ * @param options Options for building the server.
79
+ * @returns Nothing.
80
+ */
81
+ async build(restRouteProcessors, restRoutes, options) {
82
+ if (!Is.arrayValue(restRouteProcessors)) {
83
+ throw new GeneralError(this.CLASS_NAME, "noProcessors");
84
+ }
85
+ await this._loggingConnector?.log({
86
+ level: "info",
87
+ ts: Date.now(),
88
+ source: this.CLASS_NAME,
89
+ message: `${FastifyWebServer._CLASS_NAME_CAMEL_CASE}.building`
90
+ });
91
+ this._options = options;
92
+ await this._fastify.register(FastifyCompress);
93
+ await this.initCors(options);
94
+ this._fastify.setNotFoundHandler({}, async (request, reply) => this.handleRequest(restRouteProcessors, request, reply));
95
+ this._fastify.setErrorHandler(async (error, request, reply) => {
96
+ // If code property is set this is a fastify error
97
+ // otherwise it's from our framework
98
+ let httpStatusCode;
99
+ let err;
100
+ if (Is.number(error.code)) {
101
+ err = {
102
+ source: this.CLASS_NAME,
103
+ name: error.name,
104
+ message: `${error.code}: ${error.message}`
105
+ };
106
+ httpStatusCode = error.statusCode ?? HttpStatusCode.badRequest;
107
+ }
108
+ else {
109
+ const errorAndCode = HttpErrorHelper.processError(error);
110
+ err = errorAndCode.error;
111
+ httpStatusCode = errorAndCode.httpStatusCode;
112
+ }
113
+ await this._loggingConnector?.log({
114
+ level: "error",
115
+ ts: Date.now(),
116
+ source: this.CLASS_NAME,
117
+ message: `${FastifyWebServer._CLASS_NAME_CAMEL_CASE}.badRequest`,
118
+ error: err
119
+ });
120
+ return reply.status(httpStatusCode).send({
121
+ error: err
122
+ });
123
+ });
124
+ // Add the routes to the server.
125
+ for (const restRoute of restRoutes) {
126
+ let path = StringHelper.trimTrailingSlashes(restRoute.path);
127
+ if (!path.startsWith("/")) {
128
+ path = `/${path}`;
129
+ }
130
+ await this._loggingConnector?.log({
131
+ level: "info",
132
+ ts: Date.now(),
133
+ source: this.CLASS_NAME,
134
+ message: `${FastifyWebServer._CLASS_NAME_CAMEL_CASE}.restRouteAdded`,
135
+ data: { route: path, method: restRoute.method }
136
+ });
137
+ const method = restRoute.method.toLowerCase();
138
+ this._fastify[method](path, async (request, reply) => this.handleRequest(restRouteProcessors, request, reply, restRoute));
139
+ }
140
+ }
141
+ /**
142
+ * Start the server.
143
+ * @returns Nothing.
144
+ */
145
+ async start() {
146
+ const host = this._options?.host ?? FastifyWebServer._DEFAULT_HOST;
147
+ const port = this._options?.port ?? FastifyWebServer._DEFAULT_PORT;
148
+ await this._loggingConnector?.log({
149
+ level: "info",
150
+ ts: Date.now(),
151
+ source: this.CLASS_NAME,
152
+ message: `${FastifyWebServer._CLASS_NAME_CAMEL_CASE}.starting`,
153
+ data: {
154
+ host,
155
+ port
156
+ }
157
+ });
158
+ if (!this._started) {
159
+ try {
160
+ await this._fastify.listen({ port, host });
161
+ const addresses = this._fastify.addresses();
162
+ const protocol = Is.object(this._fastify.initialConfig.https) ? "https://" : "http://";
163
+ await this._loggingConnector?.log({
164
+ level: "info",
165
+ ts: Date.now(),
166
+ source: this.CLASS_NAME,
167
+ message: `${FastifyWebServer._CLASS_NAME_CAMEL_CASE}.started`,
168
+ data: {
169
+ addresses: addresses
170
+ .map(a => `${protocol}${a.family === "IPv6" ? "[" : ""}${a.address}${a.family === "IPv6" ? "]" : ""}:${a.port}`)
171
+ .join(", ")
172
+ }
173
+ });
174
+ this._started = true;
175
+ }
176
+ catch (err) {
177
+ await this._loggingConnector?.log({
178
+ level: "error",
179
+ ts: Date.now(),
180
+ source: this.CLASS_NAME,
181
+ message: `${FastifyWebServer._CLASS_NAME_CAMEL_CASE}.startFailed`,
182
+ error: BaseError.fromError(err)
183
+ });
184
+ }
185
+ }
186
+ }
187
+ /**
188
+ * Stop the server.
189
+ * @returns Nothing.
190
+ */
191
+ async stop() {
192
+ if (this._started) {
193
+ this._started = false;
194
+ await this._fastify.close();
195
+ await this._loggingConnector?.log({
196
+ level: "info",
197
+ ts: Date.now(),
198
+ source: this.CLASS_NAME,
199
+ message: `${FastifyWebServer._CLASS_NAME_CAMEL_CASE}.stopped`
200
+ });
201
+ }
202
+ }
203
+ /**
204
+ * Handle the incoming request.
205
+ * @param restRouteProcessors The hooks to process the incoming requests.
206
+ * @param request The incoming request.
207
+ * @param reply The outgoing response.
208
+ * @param restRoute The REST route to handle.
209
+ * @internal
210
+ */
211
+ async handleRequest(restRouteProcessors, request, reply, restRoute) {
212
+ const httpServerRequest = {
213
+ method: request.method.toUpperCase(),
214
+ url: `${request.protocol}://${request.hostname}${request.url}`,
215
+ body: request.body,
216
+ query: request.query,
217
+ pathParams: request.params,
218
+ headers: request.headers
219
+ };
220
+ const httpResponse = {};
221
+ const httpRequestIdentity = {};
222
+ const processorState = {};
223
+ for (const restRouteProcessor of restRouteProcessors) {
224
+ if (Is.function(restRouteProcessor.pre)) {
225
+ await restRouteProcessor.pre(httpServerRequest, httpResponse, restRoute, httpRequestIdentity, processorState);
226
+ }
227
+ }
228
+ for (const restRouteProcessor of restRouteProcessors) {
229
+ if (Is.function(restRouteProcessor.process)) {
230
+ await restRouteProcessor.process(httpServerRequest, httpResponse, restRoute, httpRequestIdentity, processorState);
231
+ }
232
+ }
233
+ for (const restRouteProcessor of restRouteProcessors) {
234
+ if (Is.function(restRouteProcessor.post)) {
235
+ await restRouteProcessor.post(httpServerRequest, httpResponse, restRoute, httpRequestIdentity, processorState);
236
+ }
237
+ }
238
+ if (!Is.empty(httpResponse.headers)) {
239
+ for (const header of Object.keys(httpResponse.headers)) {
240
+ reply.header(header, httpResponse.headers[header]);
241
+ }
242
+ }
243
+ return reply
244
+ .status((httpResponse.statusCode ?? HttpStatusCode.ok))
245
+ .send(httpResponse.body);
246
+ }
247
+ /**
248
+ * Initialize the cors options.
249
+ * @param options The web server options.
250
+ * @internal
251
+ */
252
+ async initCors(options) {
253
+ let origins = ["*"];
254
+ if (Is.arrayValue(options?.corsOrigins)) {
255
+ origins = options?.corsOrigins;
256
+ }
257
+ else if (Is.stringValue(options?.corsOrigins)) {
258
+ origins = [options?.corsOrigins];
259
+ }
260
+ const hasWildcardOrigin = origins.includes("*");
261
+ const methods = options?.methods ?? [
262
+ HttpMethod.GET,
263
+ HttpMethod.PUT,
264
+ HttpMethod.POST,
265
+ HttpMethod.DELETE,
266
+ HttpMethod.OPTIONS
267
+ ];
268
+ const allowedHeaders = [
269
+ "Access-Control-Allow-Origin",
270
+ "Content-Encoding",
271
+ "Accept-Encoding",
272
+ HeaderTypes.ContentType,
273
+ HeaderTypes.Authorization,
274
+ HeaderTypes.Accept
275
+ ];
276
+ const exposedHeaders = [HeaderTypes.ContentDisposition, HeaderTypes.Location];
277
+ if (Is.arrayValue(options?.allowedHeaders)) {
278
+ allowedHeaders.push(...options.allowedHeaders);
279
+ }
280
+ if (Is.arrayValue(options?.exposedHeaders)) {
281
+ exposedHeaders.push(...options.exposedHeaders);
282
+ }
283
+ await this._fastify.register(FastifyCors, {
284
+ origin: (origin, callback) => {
285
+ callback(null, hasWildcardOrigin ? true : origins.includes(origin));
286
+ },
287
+ methods,
288
+ allowedHeaders,
289
+ exposedHeaders,
290
+ credentials: true
291
+ });
292
+ }
293
+ }
294
+
295
+ export { FastifyWebServer };
@@ -0,0 +1,44 @@
1
+ import { type IHttpRestRouteProcessor, type IRestRoute, type IWebServer, type IWebServerOptions } from "@twin.org/api-models";
2
+ import { type FastifyServerOptions, type FastifyInstance } from "fastify";
3
+ /**
4
+ * Implementation of the web server using Fastify.
5
+ */
6
+ export declare class FastifyWebServer implements IWebServer<FastifyInstance> {
7
+ /**
8
+ * Runtime name for the class.
9
+ */
10
+ readonly CLASS_NAME: string;
11
+ /**
12
+ * Create a new instance of FastifyWebServer.
13
+ * @param options The options for the server.
14
+ * @param options.loggingConnectorType The type of the logging connector to use, if undefined, no logging will happen.
15
+ * @param options.config Additional options for the Fastify server.
16
+ */
17
+ constructor(options?: {
18
+ loggingConnectorType?: string;
19
+ config?: FastifyServerOptions;
20
+ });
21
+ /**
22
+ * Get the web server instance.
23
+ * @returns The web server instance.
24
+ */
25
+ getInstance(): FastifyInstance;
26
+ /**
27
+ * Build the server.
28
+ * @param restRouteProcessors The hooks to process the incoming requests.
29
+ * @param restRoutes The REST routes.
30
+ * @param options Options for building the server.
31
+ * @returns Nothing.
32
+ */
33
+ build(restRouteProcessors: IHttpRestRouteProcessor[], restRoutes: IRestRoute[], options?: IWebServerOptions): Promise<void>;
34
+ /**
35
+ * Start the server.
36
+ * @returns Nothing.
37
+ */
38
+ start(): Promise<void>;
39
+ /**
40
+ * Stop the server.
41
+ * @returns Nothing.
42
+ */
43
+ stop(): Promise<void>;
44
+ }
@@ -0,0 +1 @@
1
+ export * from "./fastifyWebServer";
@@ -0,0 +1,5 @@
1
+ # @twin.org/api-server-fastify - Changelog
2
+
3
+ ## v0.0.1-next.10
4
+
5
+ - Initial Release
@@ -0,0 +1 @@
1
+ # @twin.org/api-server-fastify - Examples
@@ -0,0 +1,127 @@
1
+ # Class: FastifyWebServer
2
+
3
+ Implementation of the web server using Fastify.
4
+
5
+ ## Implements
6
+
7
+ - `IWebServer`\<`FastifyInstance`\>
8
+
9
+ ## Constructors
10
+
11
+ ### new FastifyWebServer()
12
+
13
+ > **new FastifyWebServer**(`options`?): [`FastifyWebServer`](FastifyWebServer.md)
14
+
15
+ Create a new instance of FastifyWebServer.
16
+
17
+ #### Parameters
18
+
19
+ • **options?**
20
+
21
+ The options for the server.
22
+
23
+ • **options.loggingConnectorType?**: `string`
24
+
25
+ The type of the logging connector to use, if undefined, no logging will happen.
26
+
27
+ • **options.config?**: `FastifyServerOptions`
28
+
29
+ Additional options for the Fastify server.
30
+
31
+ #### Returns
32
+
33
+ [`FastifyWebServer`](FastifyWebServer.md)
34
+
35
+ ## Properties
36
+
37
+ ### CLASS\_NAME
38
+
39
+ > `readonly` **CLASS\_NAME**: `string`
40
+
41
+ Runtime name for the class.
42
+
43
+ ## Methods
44
+
45
+ ### getInstance()
46
+
47
+ > **getInstance**(): `FastifyInstance`\<`RawServerDefault`, `IncomingMessage`, `ServerResponse`\<`IncomingMessage`\>, `FastifyBaseLogger`, `FastifyTypeProviderDefault`\>
48
+
49
+ Get the web server instance.
50
+
51
+ #### Returns
52
+
53
+ `FastifyInstance`\<`RawServerDefault`, `IncomingMessage`, `ServerResponse`\<`IncomingMessage`\>, `FastifyBaseLogger`, `FastifyTypeProviderDefault`\>
54
+
55
+ The web server instance.
56
+
57
+ #### Implementation of
58
+
59
+ `IWebServer.getInstance`
60
+
61
+ ***
62
+
63
+ ### build()
64
+
65
+ > **build**(`restRouteProcessors`, `restRoutes`, `options`?): `Promise`\<`void`\>
66
+
67
+ Build the server.
68
+
69
+ #### Parameters
70
+
71
+ • **restRouteProcessors**: `IHttpRestRouteProcessor`[]
72
+
73
+ The hooks to process the incoming requests.
74
+
75
+ • **restRoutes**: `IRestRoute`\<`any`, `any`\>[]
76
+
77
+ The REST routes.
78
+
79
+ • **options?**: `IWebServerOptions`
80
+
81
+ Options for building the server.
82
+
83
+ #### Returns
84
+
85
+ `Promise`\<`void`\>
86
+
87
+ Nothing.
88
+
89
+ #### Implementation of
90
+
91
+ `IWebServer.build`
92
+
93
+ ***
94
+
95
+ ### start()
96
+
97
+ > **start**(): `Promise`\<`void`\>
98
+
99
+ Start the server.
100
+
101
+ #### Returns
102
+
103
+ `Promise`\<`void`\>
104
+
105
+ Nothing.
106
+
107
+ #### Implementation of
108
+
109
+ `IWebServer.start`
110
+
111
+ ***
112
+
113
+ ### stop()
114
+
115
+ > **stop**(): `Promise`\<`void`\>
116
+
117
+ Stop the server.
118
+
119
+ #### Returns
120
+
121
+ `Promise`\<`void`\>
122
+
123
+ Nothing.
124
+
125
+ #### Implementation of
126
+
127
+ `IWebServer.stop`
@@ -0,0 +1,5 @@
1
+ # @twin.org/api-server-fastify
2
+
3
+ ## Classes
4
+
5
+ - [FastifyWebServer](classes/FastifyWebServer.md)
@@ -0,0 +1,12 @@
1
+ {
2
+ "fastifyWebServer": {
3
+ "building": "Building Web Server",
4
+ "starting": "Starting Web Server at address \"{host}\" on port \"{port}\"",
5
+ "startFailed": "The Web Server failed to start",
6
+ "started": "The Web Server started on {addresses}",
7
+ "stopped": "The Web Server was stopped",
8
+ "badRequest": "The web server could not handle the request",
9
+ "restRouteAdded": "Added REST route \"{route}\" \"{method}\"",
10
+ "noProcessors": "You must configure at least one processor"
11
+ }
12
+ }
package/package.json ADDED
@@ -0,0 +1,44 @@
1
+ {
2
+ "name": "@twin.org/api-server-fastify",
3
+ "version": "0.0.1-next.10",
4
+ "description": "Use Fastify as the core web server for APIs",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "git+https://github.com/twinfoundation/api.git",
8
+ "directory": "packages/api-server-fastify"
9
+ },
10
+ "author": "martyn.janes@iota.org",
11
+ "license": "Apache-2.0",
12
+ "type": "module",
13
+ "engines": {
14
+ "node": ">=20.0.0"
15
+ },
16
+ "dependencies": {
17
+ "@fastify/compress": "8.0.1",
18
+ "@fastify/cors": "10.0.1",
19
+ "@twin.org/api-core": "0.0.1-next.10",
20
+ "@twin.org/api-models": "0.0.1-next.10",
21
+ "@twin.org/core": "next",
22
+ "@twin.org/logging-models": "next",
23
+ "@twin.org/nameof": "next",
24
+ "@twin.org/web": "next",
25
+ "fastify": "5.0.0"
26
+ },
27
+ "main": "./dist/cjs/index.cjs",
28
+ "module": "./dist/esm/index.mjs",
29
+ "types": "./dist/types/index.d.ts",
30
+ "exports": {
31
+ ".": {
32
+ "require": "./dist/cjs/index.cjs",
33
+ "import": "./dist/esm/index.mjs",
34
+ "types": "./dist/types/index.d.ts"
35
+ }
36
+ },
37
+ "files": [
38
+ "dist/cjs",
39
+ "dist/esm",
40
+ "dist/types",
41
+ "locales",
42
+ "docs"
43
+ ]
44
+ }