@zyrohub/module-fastify 0.0.1 → 0.0.2

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/README.md ADDED
@@ -0,0 +1,83 @@
1
+ <div align="center">
2
+ <img src="https://i.imgur.com/KVVR2dM.png">
3
+ </div>
4
+
5
+ ## ZyroHub - Fastify Module
6
+
7
+ This is the Fastify module for ZyroHub ecosystem. It allows you to easily create a Fastify server and integrate it with [`@zyrohub/module-router`](https://www.npmjs.com/package/@zyrohub/module-router).
8
+
9
+ ## Table of Contents
10
+
11
+ - [ZyroHub - Fastify Module](#zyrohub---fastify-module)
12
+ - [Table of Contents](#table-of-contents)
13
+ - [Getting Started](#getting-started)
14
+ - [Required Dependencies](#required-dependencies)
15
+ - [Using Module](#using-module)
16
+
17
+ ## Getting Started
18
+
19
+ To install the fastify module, use one of the following package managers:
20
+
21
+ [NPM Repository](https://www.npmjs.com/package/@zyrohub/module-fastify)
22
+
23
+ ```bash
24
+ # npm
25
+ npm install @zyrohub/module-fastify
26
+ # yarn
27
+ yarn add @zyrohub/module-fastify
28
+ # pnpm
29
+ pnpm add @zyrohub/module-fastify
30
+ # bun
31
+ bun add @zyrohub/module-fastify
32
+ ```
33
+
34
+ ### Required Dependencies
35
+
36
+ You also need to install `fastify`, [`@zyrohub/module-router`](https://www.npmjs.com/package/@zyrohub/module-router) and [`@zyrohub/core`](https://www.npmjs.com/package/@zyrohub/core) dependencies:
37
+
38
+ ```bash
39
+ # npm
40
+ npm install fastify @zyrohub/module-router @zyrohub/core
41
+
42
+ # yarn
43
+ yarn add fastify @zyrohub/module-router @zyrohub/core
44
+
45
+ # pnpm
46
+ pnpm add fastify @zyrohub/module-router @zyrohub/core
47
+
48
+ # bun
49
+ bun add fastify @zyrohub/module-router @zyrohub/core
50
+ ```
51
+
52
+ ### Using Module
53
+
54
+ ```typescript
55
+ import { Core } from '@zyrohub/core';
56
+ import { FastifyModule } from '@zyrohub/module-fastify';
57
+ import { RouterModule } from '@zyrohub/module-router';
58
+
59
+ const core = new Core({
60
+ modules: [
61
+ RouterModule.mount({
62
+ // RouterModule options here (see @zyrohub/module-router documentation)
63
+ }),
64
+ FastifyModule.mount({
65
+ port: 3000,
66
+ host: 'localhost', // optional
67
+
68
+ rawOptions: {
69
+ // Fastify server options here (see https://www.fastify.io/docs/latest/Reference/Server/)
70
+ },
71
+ rawListenOptions: {
72
+ // Fastify listen options here (see https://www.fastify.io/docs/latest/Reference/Server/#listen)
73
+ },
74
+
75
+ onSetup(server, core) {
76
+ // called once the Fastify server is being set up and before registering routes
77
+ }
78
+ })
79
+ ]
80
+ });
81
+
82
+ core.init();
83
+ ```
@@ -0,0 +1,26 @@
1
+ import { Core, BaseModule } from '@zyrohub/core';
2
+ import { FastifyBaseLogger, FastifyHttpOptions, FastifyInstance, FastifyListenOptions, RawServerDefault } from 'fastify';
3
+ export interface FastifyModuleOptions {
4
+ port?: number | string;
5
+ host?: string;
6
+ rawOptions?: FastifyHttpOptions<RawServerDefault, FastifyBaseLogger> | undefined;
7
+ rawListenOptions?: FastifyListenOptions;
8
+ onSetup?(server: FastifyInstance, core: Core): void;
9
+ }
10
+ export declare class FastifyModule extends BaseModule {
11
+ static options: FastifyModuleOptions;
12
+ server?: FastifyInstance;
13
+ port: number;
14
+ constructor();
15
+ private handleLoadController;
16
+ private handleLoadControllers;
17
+ private handleAddHandlers;
18
+ init(data: {
19
+ core: Core;
20
+ options: FastifyModuleOptions;
21
+ }): Promise<void>;
22
+ }
23
+ declare const _default: {
24
+ FastifyModule: typeof FastifyModule;
25
+ };
26
+ export default _default;
package/dist/Module.js ADDED
@@ -0,0 +1,149 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __metadata = (this && this.__metadata) || function (k, v) {
8
+ if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
9
+ };
10
+ import { BaseModule, Module } from '@zyrohub/core';
11
+ import { HttpResponse, ROUTER_CONTROLLERS_STORAGE_KEY } from '@zyrohub/module-router';
12
+ import { Ansi, Terminal, Validator } from '@zyrohub/utilities';
13
+ import fastify from 'fastify';
14
+ let FastifyModule = class FastifyModule extends BaseModule {
15
+ static options;
16
+ server;
17
+ port = 3000;
18
+ constructor() {
19
+ super();
20
+ }
21
+ async handleLoadController(controller) {
22
+ if (!this.core || !this.server)
23
+ return;
24
+ const core = this.core;
25
+ const controllerInstance = core.instantiate(controller.data.constructor);
26
+ const prefix = controller.data.path || '/';
27
+ const controllerMiddlewares = controller.data.middlewares || [];
28
+ for (const route of controller.routes) {
29
+ const rawUrl = `${prefix}${route.path}`.replace(/\/+/g, '/');
30
+ const url = rawUrl.length > 1 && rawUrl.endsWith('/') ? rawUrl.slice(0, -1) : rawUrl;
31
+ const method = route.method.toLowerCase();
32
+ this.server[method](url, async (request, reply) => {
33
+ const context = {
34
+ request,
35
+ response: reply,
36
+ body: request.body,
37
+ query: request.query,
38
+ params: request.params
39
+ };
40
+ if (route.schema?.validators.body) {
41
+ const result = await Validator.validate(route.schema.validators.body, request.body);
42
+ if (!result.success)
43
+ return reply
44
+ .status(400)
45
+ .send(HttpResponse.error(400, 'VALIDATION_ERROR_BODY', result.errors).toObject());
46
+ context.body = result.data;
47
+ }
48
+ if (route.schema?.validators.query) {
49
+ const result = await Validator.validate(route.schema.validators.query, request.query);
50
+ if (!result.success)
51
+ return reply
52
+ .status(400)
53
+ .send(HttpResponse.error(400, 'VALIDATION_ERROR_QUERY', result.errors).toObject());
54
+ context.query = result.data;
55
+ }
56
+ if (route.schema?.validators.params) {
57
+ const result = await Validator.validate(route.schema.validators.params, request.params);
58
+ if (!result.success)
59
+ return reply
60
+ .status(400)
61
+ .send(HttpResponse.error(400, 'VALIDATION_ERROR_PARAMS', result.errors).toObject());
62
+ context.params = result.data;
63
+ }
64
+ const allMiddlewares = [...controllerMiddlewares, ...(route.middlewares || [])];
65
+ for (const middleware of allMiddlewares) {
66
+ const middlewareInstance = core.instantiate(middleware.constructor);
67
+ if (middlewareInstance && typeof middlewareInstance.execute === 'function') {
68
+ let middlewareReturn = await middlewareInstance.execute(context, middleware.options);
69
+ if (middlewareReturn !== undefined) {
70
+ if (middlewareReturn instanceof HttpResponse) {
71
+ return reply.status(middlewareReturn.status).send(middlewareReturn.toObject());
72
+ }
73
+ reply.send(middlewareReturn);
74
+ }
75
+ }
76
+ }
77
+ const routeHandler = controllerInstance[route.handlerName];
78
+ const routeReturn = await routeHandler.call(controllerInstance, context);
79
+ if (reply.sent)
80
+ return;
81
+ if (routeReturn instanceof HttpResponse) {
82
+ return reply.status(routeReturn.status).send(routeReturn.toObject());
83
+ }
84
+ return reply.send(routeReturn);
85
+ });
86
+ }
87
+ }
88
+ async handleLoadControllers() {
89
+ if (!this.core)
90
+ return;
91
+ const controllers = this.core.storage.get(ROUTER_CONTROLLERS_STORAGE_KEY) || [];
92
+ if (controllers.length === 0)
93
+ return;
94
+ for (const controller of controllers) {
95
+ await this.handleLoadController(controller);
96
+ }
97
+ Terminal.info('FASTIFY', `Loaded ${Ansi.green(controllers.length)} controller(s) into Fastify module.`);
98
+ }
99
+ async handleAddHandlers() {
100
+ if (!this.server)
101
+ return;
102
+ this.server.setNotFoundHandler((request, reply) => {
103
+ reply.status(404).send({
104
+ success: false,
105
+ status: 404,
106
+ code: 'NOT_FOUND',
107
+ data: {
108
+ message: 'The requested resource was not found.'
109
+ }
110
+ });
111
+ });
112
+ this.server.setErrorHandler((error, request, reply) => {
113
+ if (error instanceof HttpResponse)
114
+ return reply.status(error.status).send(error.toObject());
115
+ reply.status(500).send({
116
+ success: false,
117
+ status: 500,
118
+ code: 'INTERNAL_SERVER_ERROR',
119
+ data: {
120
+ message: 'An internal server error occurred.'
121
+ }
122
+ });
123
+ });
124
+ }
125
+ async init(data) {
126
+ this.server = fastify({
127
+ logger: false,
128
+ ...data.options.rawOptions
129
+ });
130
+ if (data.options.onSetup)
131
+ data.options.onSetup(this.server, data.core);
132
+ const parsedPort = typeof data.options.port === 'string' ? parseInt(data.options.port, 10) : data.options.port;
133
+ this.port = parsedPort || 3000;
134
+ await this.handleLoadControllers();
135
+ await this.handleAddHandlers();
136
+ this.server.listen({
137
+ port: this.port,
138
+ host: data.options.host,
139
+ ...data.options.rawListenOptions
140
+ });
141
+ Terminal.info('FASTIFY', `Server is listening on port: ${Ansi.green(this.port.toString())}`);
142
+ }
143
+ };
144
+ FastifyModule = __decorate([
145
+ Module(),
146
+ __metadata("design:paramtypes", [])
147
+ ], FastifyModule);
148
+ export { FastifyModule };
149
+ export default { FastifyModule };
@@ -0,0 +1 @@
1
+ export * from './Module.js';
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ export * from './Module.js';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zyrohub/module-fastify",
3
- "version": "0.0.1",
3
+ "version": "0.0.2",
4
4
  "author": "DMVMarcio",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",