@sleekify/sleekify-fastify 1.0.0

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 [yyyy] [name of copyright owner]
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,127 @@
1
+ # <img src="resources/sleekify.png" height="27"> Sleekify Fastify Integration
2
+
3
+ This project's goal is to simplify the development of REST web services in NodeJS by bringing the best of the Java API for RESTful Web Services (JAX-RS) to TypeScript.
4
+ This is possible since TypeScript decorators may be used in a manner similar to Java annotations.
5
+ This project allows you to apply decorators to your resource classes to identify your REST resources and associate them with OpenAPI definitions.
6
+ This allows you to maintain your API documentation alongside your code using typed definitions.
7
+ If you ever had to maintain a large OpenAPI specification by hand, this should grab your attention.
8
+ Your API documentation will both match the OpenAPI specification's schema and be generated from your code.
9
+
10
+ ## Getting Started
11
+
12
+ 1. First, install Sleekify and the Fastify integration
13
+ ```bash
14
+ npm install @sleekify/sleekify
15
+ npm install @sleekify/sleekify-fastify
16
+ ```
17
+
18
+ 2. Create REST resources using the provided decorators
19
+ <br/><sub>_src/v1/users.ts_</sub>
20
+ ```TypeScript
21
+ @Path({
22
+ path: '/v1/users/{id}',
23
+ parameters: [
24
+ {
25
+ $ref: '#/components/parameters/id'
26
+ }
27
+ ]
28
+ })
29
+ @Schema({
30
+ $ref: '#/components/schemas/user'
31
+ })
32
+ export class UsersIdResource {
33
+ @GET()
34
+ async getOne () {
35
+ // TODO: your read user code here
36
+ }
37
+
38
+ @PUT()
39
+ async updateOne () {
40
+ // TODO: your update user code here
41
+ }
42
+
43
+ @DELETE()
44
+ async deleteOne () {
45
+ // TODO: your delete user code here
46
+ }
47
+ }
48
+ ```
49
+
50
+ 2. Create your base OpenAPI specification
51
+ <br/><sub>_src/openapi.ts_</sub>
52
+ ```TypeScript
53
+ import { OpenAPIObject } from '@sleekify/sleekify';
54
+
55
+ export const specification: OpenAPIObject = {
56
+ openapi: '3.1.1',
57
+ info: {
58
+ title: 'Test API',
59
+ version: '1.0.0'
60
+ },
61
+ components: {
62
+ parameters: {
63
+ id: {
64
+ description: 'The identifier of the resource',
65
+ name: 'id',
66
+ in: 'path',
67
+ required: true,
68
+ schema: {
69
+ $ref: '#/components/schemas/id'
70
+ }
71
+ },
72
+ schemas: {
73
+ id: {
74
+ description: 'The id path parameter schema',
75
+ type: ['integer']
76
+ },
77
+ user: {
78
+ type: ['object'],
79
+ properties: {
80
+ id: {
81
+ type: ['number']
82
+ },
83
+ name: {
84
+ type: ['string']
85
+ }
86
+ }
87
+ }
88
+ }
89
+ }
90
+ };
91
+ ```
92
+
93
+ 4. Register your OpenAPI specification and resources with Fastify
94
+ <br/><sub>_src/index.ts_</sub>
95
+ ```TypeScript
96
+ import Fastify from 'fastify';
97
+ import { Annotation, Path } from '@sleekify/sleekify';
98
+ import { Sleekify } from '@sleekify/sleekify-fastify';
99
+ import { specification } from './openapi';
100
+
101
+ const fastify = Fastify({
102
+ logger: true
103
+ });
104
+
105
+ async function run () {
106
+ // 1. Find all of your resource classes
107
+ const classList = await Annotation.getClassesAnnotatedWith('./v1', Path);
108
+ // 2. Create a Sleekify instance
109
+ const sleekify = new Sleekify(specification, classList);
110
+
111
+ // 3. Register Sleekify with Fastify
112
+ await fastify.register(sleekify.getPlugin());
113
+
114
+ fastify.listen({ port: 3000 }, function (error) {
115
+ if (error != null) {
116
+ fastify.log.error(error);
117
+ process.exit(1);
118
+ }
119
+ });
120
+ }
121
+
122
+ void run();
123
+ ```
124
+
125
+ ## API Documentation
126
+
127
+ For more information on the provided decorators, OpenAPI types, and web application errors see the [Sleekify API Reference](https://github.com/sleekify/sleekify).
@@ -0,0 +1,43 @@
1
+ import { type FastifyReply, type FastifyRequest } from 'fastify';
2
+ import { type OpenAPIObject } from '@sleekify/sleekify';
3
+ /**
4
+ * This class provides the Sleekify integration for Fastify.
5
+ */
6
+ export declare class Sleekify {
7
+ private readonly classArray;
8
+ private readonly specification;
9
+ private serviceHandlers?;
10
+ private plugin?;
11
+ /**
12
+ * Creates a new Sleekify instance.
13
+ *
14
+ * @param specification The OpenAPI base specification
15
+ * @param classArray The resource classes to include in the OpenAPI specification
16
+ */
17
+ constructor(specification: OpenAPIObject, classArray: any[]);
18
+ /**
19
+ * Get a Fastify plugin which you can register.
20
+ */
21
+ getPlugin(): (fastify: any, options: any) => Promise<any>;
22
+ /**
23
+ * Get the OpenAPI specification which may be passed to Fastify OpenAPI glue.
24
+ * @param options The options
25
+ * @param options.pretty Sort the specification path's etc.
26
+ */
27
+ getSpecification(options?: {
28
+ pretty?: boolean;
29
+ }): OpenAPIObject;
30
+ /**
31
+ * Get the service handlers which may be passed to Fastify OpenAPI glue.
32
+ */
33
+ getServiceHandlers(): Record<string, (request: FastifyRequest, reply: FastifyReply) => Promise<any>>;
34
+ private initialize;
35
+ private addComponents;
36
+ private addPath;
37
+ private addRequestBody;
38
+ private addResponses;
39
+ private addSchemas;
40
+ private addServiceHandlers;
41
+ private getSuccessStatusCodes;
42
+ private sortObject;
43
+ }
@@ -0,0 +1,318 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.Sleekify = void 0;
7
+ const fastify_plugin_1 = require("fastify-plugin");
8
+ const sleekify_1 = require("@sleekify/sleekify");
9
+ const tsimportlib_1 = require("tsimportlib");
10
+ const lodash_1 = __importDefault(require("lodash"));
11
+ const methodMapArray = [
12
+ {
13
+ decorator: sleekify_1.DELETE,
14
+ key: 'delete'
15
+ },
16
+ {
17
+ decorator: sleekify_1.GET,
18
+ key: 'get'
19
+ },
20
+ {
21
+ decorator: sleekify_1.HEAD,
22
+ key: 'head'
23
+ },
24
+ {
25
+ decorator: sleekify_1.OPTIONS,
26
+ key: 'options'
27
+ },
28
+ {
29
+ decorator: sleekify_1.PATCH,
30
+ key: 'patch'
31
+ },
32
+ {
33
+ decorator: sleekify_1.POST,
34
+ key: 'post'
35
+ },
36
+ {
37
+ decorator: sleekify_1.PUT,
38
+ key: 'put'
39
+ },
40
+ {
41
+ decorator: sleekify_1.TRACE,
42
+ key: 'trace'
43
+ }
44
+ ];
45
+ /**
46
+ * This class provides the Sleekify integration for Fastify.
47
+ */
48
+ class Sleekify {
49
+ classArray;
50
+ specification;
51
+ serviceHandlers;
52
+ plugin;
53
+ /**
54
+ * Creates a new Sleekify instance.
55
+ *
56
+ * @param specification The OpenAPI base specification
57
+ * @param classArray The resource classes to include in the OpenAPI specification
58
+ */
59
+ constructor(specification, classArray) {
60
+ this.classArray = classArray;
61
+ this.specification = JSON.parse(JSON.stringify(specification));
62
+ }
63
+ /**
64
+ * Get a Fastify plugin which you can register.
65
+ */
66
+ getPlugin() {
67
+ this.initialize();
68
+ if (this.plugin !== undefined) {
69
+ return this.plugin;
70
+ }
71
+ const plugin = async (fastify, options) => {
72
+ /* This is an ES module so we must import it dynamically */
73
+ const { fastifyOpenapiGlue } = (await (0, tsimportlib_1.dynamicImport)('fastify-openapi-glue', module));
74
+ await fastifyOpenapiGlue(fastify, {
75
+ ...options,
76
+ specification: this.getSpecification(),
77
+ serviceHandlers: this.serviceHandlers
78
+ });
79
+ };
80
+ this.plugin = (0, fastify_plugin_1.fastifyPlugin)(plugin, {
81
+ fastify: '>=4.0.0',
82
+ name: '@sleekify/sleekify-fastify'
83
+ });
84
+ return this.plugin;
85
+ }
86
+ /**
87
+ * Get the OpenAPI specification which may be passed to Fastify OpenAPI glue.
88
+ * @param options The options
89
+ * @param options.pretty Sort the specification path's etc.
90
+ */
91
+ getSpecification(options) {
92
+ this.initialize();
93
+ const result = JSON.parse(JSON.stringify(this.specification));
94
+ if (options?.pretty === true) {
95
+ this.sortObject(result, 'paths');
96
+ this.sortObject(result, 'webhooks');
97
+ this.sortObject(result, 'components');
98
+ const components = [
99
+ 'callbacks',
100
+ 'examples',
101
+ 'links',
102
+ 'parameters',
103
+ 'pathItems',
104
+ 'requestBodies',
105
+ 'responses',
106
+ 'schemas',
107
+ 'securitySchemes'
108
+ ];
109
+ for (const key of components) {
110
+ this.sortObject(result, `components.${key}`);
111
+ }
112
+ }
113
+ return result;
114
+ }
115
+ /**
116
+ * Get the service handlers which may be passed to Fastify OpenAPI glue.
117
+ */
118
+ getServiceHandlers() {
119
+ this.initialize();
120
+ return this.serviceHandlers;
121
+ }
122
+ initialize() {
123
+ if (this.serviceHandlers !== undefined) {
124
+ /* already initialized */
125
+ return;
126
+ }
127
+ this.serviceHandlers = {};
128
+ for (const clazz of this.classArray) {
129
+ const Clazz = clazz;
130
+ const classInstance = new Clazz();
131
+ const componentsObject = sleekify_1.Annotation.get(clazz, undefined, sleekify_1.Components);
132
+ const pathItemObject = sleekify_1.Annotation.get(clazz, undefined, sleekify_1.Path);
133
+ if (componentsObject !== undefined) {
134
+ this.addComponents(clazz, componentsObject);
135
+ }
136
+ if (pathItemObject !== undefined) {
137
+ this.addServiceHandlers(clazz, classInstance, pathItemObject);
138
+ }
139
+ }
140
+ // TODO - sort specification?
141
+ }
142
+ addComponents(clazz, componentsObject) {
143
+ if (this.specification.components === undefined) {
144
+ this.specification.components = {};
145
+ }
146
+ const propertyNameArray = [
147
+ 'schemas',
148
+ 'responses',
149
+ 'parameters',
150
+ 'examples',
151
+ 'requestBodies',
152
+ 'headers',
153
+ 'securitySchemes',
154
+ 'links',
155
+ 'callbacks',
156
+ 'pathItems'
157
+ ];
158
+ for (const propertyName of propertyNameArray) {
159
+ if (componentsObject[propertyName] === undefined) {
160
+ continue;
161
+ }
162
+ let componentsSection = this.specification.components[propertyName];
163
+ if (componentsSection === undefined) {
164
+ componentsSection = this.specification.components[propertyName] = {};
165
+ }
166
+ Object.assign(componentsSection, componentsObject[propertyName]);
167
+ }
168
+ }
169
+ addPath(path, pathItemObject, operationMap) {
170
+ if (lodash_1.default.isEmpty(operationMap)) {
171
+ return;
172
+ }
173
+ if (this.specification.paths === undefined) {
174
+ this.specification.paths = {};
175
+ }
176
+ if (this.specification.paths[path] === undefined) {
177
+ this.specification.paths[path] = {
178
+ ...lodash_1.default.omit(pathItemObject, 'path'),
179
+ ...operationMap
180
+ };
181
+ }
182
+ }
183
+ addRequestBody(operationObject, resolvedConsumes, resolvedSchema) {
184
+ if (operationObject.requestBody === undefined) {
185
+ operationObject.requestBody = {};
186
+ }
187
+ const referenceObject = operationObject.requestBody;
188
+ const requestBody = operationObject.requestBody;
189
+ if (referenceObject.$ref === undefined && requestBody.content === undefined) {
190
+ operationObject.requestBody = {
191
+ content: resolvedConsumes.reduce((content, mediaType) => {
192
+ content[mediaType] = {
193
+ schema: resolvedSchema
194
+ };
195
+ return content;
196
+ }, {})
197
+ };
198
+ }
199
+ }
200
+ addResponses(operationObject, resolvedProduces, resolvedSchema, resolvedStatusCodes) {
201
+ if (resolvedStatusCodes.length === 0) {
202
+ return;
203
+ }
204
+ if (operationObject.responses === undefined) {
205
+ operationObject.responses = {};
206
+ }
207
+ for (const resolvedStatusCode of resolvedStatusCodes) {
208
+ if (operationObject.responses[resolvedStatusCode] === undefined) {
209
+ /* add a new response object */
210
+ operationObject.responses[resolvedStatusCode] = {
211
+ description: 'Successful response',
212
+ content: resolvedProduces.reduce((content, mediaType) => {
213
+ content[mediaType] = {
214
+ schema: resolvedSchema
215
+ };
216
+ return content;
217
+ }, {})
218
+ };
219
+ }
220
+ else {
221
+ const referenceOrResponse = operationObject.responses[resolvedStatusCode];
222
+ if (referenceOrResponse.$ref === undefined && referenceOrResponse.content === undefined) {
223
+ const responseObject = operationObject.responses[resolvedStatusCode];
224
+ /* add content to an existing response object */
225
+ responseObject.content = resolvedProduces.reduce((content, mediaType) => {
226
+ content[mediaType] = {
227
+ schema: resolvedSchema
228
+ };
229
+ return content;
230
+ }, {});
231
+ }
232
+ }
233
+ }
234
+ }
235
+ addSchemas(clazz, propertyName, operationObject, methodKey) {
236
+ const classConsumes = sleekify_1.Annotation.get(clazz, undefined, sleekify_1.Consumes);
237
+ const classProduces = sleekify_1.Annotation.get(clazz, undefined, sleekify_1.Produces);
238
+ const classSchema = sleekify_1.Annotation.get(clazz, undefined, sleekify_1.Schema);
239
+ const methodConsumes = sleekify_1.Annotation.get(clazz, propertyName, sleekify_1.Consumes);
240
+ const methodProduces = sleekify_1.Annotation.get(clazz, propertyName, sleekify_1.Produces);
241
+ const methodSchema = sleekify_1.Annotation.get(clazz, propertyName, sleekify_1.Schema);
242
+ const resolvedConsumes = methodConsumes ?? classConsumes ?? ['application/json'];
243
+ const resolvedProduces = methodProduces ?? classProduces ?? ['application/json'];
244
+ const resolvedSchema = methodSchema ?? classSchema;
245
+ if (resolvedSchema === undefined) {
246
+ return;
247
+ }
248
+ if (['patch', 'post', 'put'].includes(methodKey)) {
249
+ this.addRequestBody(operationObject, resolvedConsumes, resolvedSchema);
250
+ }
251
+ const resolvedStatusCodes = this.getSuccessStatusCodes(operationObject);
252
+ this.addResponses(operationObject, resolvedProduces, resolvedSchema, resolvedStatusCodes);
253
+ }
254
+ addServiceHandlers(clazz, classInstance, pathItemObject) {
255
+ const path = pathItemObject.path;
256
+ const operationMap = {};
257
+ for (const propertyName of Object.getOwnPropertyNames(Object.getPrototypeOf(classInstance))) {
258
+ const propertyValue = classInstance[propertyName];
259
+ if (['constructor', 'function'].includes(propertyName) || !lodash_1.default.isFunction(propertyValue)) {
260
+ continue;
261
+ }
262
+ for (const methodMap of methodMapArray) {
263
+ const decorator = methodMap.decorator;
264
+ if (!sleekify_1.Annotation.exists(clazz, propertyName, decorator)) {
265
+ continue;
266
+ }
267
+ const methodKey = methodMap.key;
268
+ const operationObject = lodash_1.default.cloneDeep(sleekify_1.Annotation.get(clazz, propertyName, decorator) ?? {});
269
+ operationMap[methodKey] = operationObject;
270
+ if (operationObject.operationId === undefined) {
271
+ operationObject.operationId = lodash_1.default.camelCase(`${methodKey}${path}`.replace(/\//g, '_').replace(/{/g, '').replace(/}/g, ''));
272
+ }
273
+ this.addSchemas(clazz, propertyName, operationObject, methodKey);
274
+ this.serviceHandlers[operationObject.operationId] = async (request, reply) => {
275
+ const result = classInstance[propertyName](request, reply);
276
+ return result instanceof Promise ? await result : result;
277
+ };
278
+ }
279
+ }
280
+ this.addPath(path, pathItemObject, operationMap);
281
+ }
282
+ getSuccessStatusCodes(operationObject) {
283
+ const successStatusCodes = [];
284
+ if (operationObject.responses !== undefined) {
285
+ for (const responseKey in operationObject.responses) {
286
+ const statusCode = Number.parseInt(responseKey);
287
+ if (!Number.isNaN(statusCode) && statusCode >= 200 && statusCode < 300) {
288
+ successStatusCodes.push(statusCode);
289
+ }
290
+ }
291
+ }
292
+ const resolvedStatusCodes = [];
293
+ if (successStatusCodes.length > 0) {
294
+ for (const statusCode of [200, 201]) {
295
+ if (successStatusCodes.includes(statusCode)) {
296
+ resolvedStatusCodes.push(statusCode);
297
+ }
298
+ }
299
+ }
300
+ else {
301
+ resolvedStatusCodes.push(200);
302
+ }
303
+ return resolvedStatusCodes;
304
+ }
305
+ sortObject(root, path) {
306
+ const object = lodash_1.default.get(root, path);
307
+ if (object === undefined) {
308
+ return;
309
+ }
310
+ const result = {};
311
+ const sortedKeys = Object.keys(object).sort();
312
+ for (const key of sortedKeys) {
313
+ result[key] = object[key];
314
+ }
315
+ lodash_1.default.set(root, path, result);
316
+ }
317
+ }
318
+ exports.Sleekify = Sleekify;
package/package.json ADDED
@@ -0,0 +1,54 @@
1
+ {
2
+ "name": "@sleekify/sleekify-fastify",
3
+ "version": "1.0.0",
4
+ "description": "A TypeScript decorator driven approach for developing Fastify web applications.",
5
+ "scripts": {
6
+ "build": "tsc",
7
+ "lint": "eslint --ext .ts .",
8
+ "test": "node --experimental-vm-modules ./node_modules/.bin/jest",
9
+ "validate": "npm run build && npm run lint -- --fix && npm test"
10
+ },
11
+ "repository": {
12
+ "type": "git",
13
+ "url": "git+https://github.com/sleekify/sleekify-fastify.git"
14
+ },
15
+ "main": "dist/src/index.js",
16
+ "types": "dist/src/index.d.ts",
17
+ "files": [
18
+ "/dist/src"
19
+ ],
20
+ "author": "Jesse Walseth",
21
+ "license": "Apache License 2.0",
22
+ "bugs": {
23
+ "url": "https://github.com/sleekify/sleekify-fastify/issues"
24
+ },
25
+ "homepage": "https://github.com/sleekify/sleekify-fastify#readme",
26
+ "devDependencies": {
27
+ "@tsconfig/node18": "^18.2.0",
28
+ "@types/jest": "^29.5.3",
29
+ "@types/lodash": "^4.14.196",
30
+ "@types/uuid": "^9.0.2",
31
+ "@typescript-eslint/eslint-plugin": "^6.4.0",
32
+ "@typescript-eslint/parser": "^6.4.0",
33
+ "axios": "^1.5.0",
34
+ "eslint": "^8.47.0",
35
+ "eslint-config-standard-with-typescript": "^38.0.0",
36
+ "eslint-plugin-import": "^2.28.1",
37
+ "eslint-plugin-n": "^16.0.1",
38
+ "eslint-plugin-promise": "^6.1.1",
39
+ "jest": "^29.6.2",
40
+ "ts-jest": "^29.1.1",
41
+ "typescript": "^5.1.6"
42
+ },
43
+ "dependencies": {
44
+ "@sleekify/sleekify": "^1.0.0",
45
+ "@types/node": "^20.4.5",
46
+ "fastify": "^5.0.0",
47
+ "fastify-openapi-glue": "^4.7.1",
48
+ "fastify-plugin": "^5.0.1",
49
+ "lodash": "^4.17.21",
50
+ "openapi-types": "^12.1.3",
51
+ "tsimportlib": "^0.0.5",
52
+ "uuid": "^9.0.0"
53
+ }
54
+ }