@athenna/http 1.2.5 → 1.3.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@athenna/http",
3
- "version": "1.2.5",
3
+ "version": "1.3.0",
4
4
  "description": "The Athenna Http server. Built on top of fastify",
5
5
  "license": "MIT",
6
6
  "author": "João Lenon <lenon@athenna.io>",
@@ -160,7 +160,7 @@
160
160
  "dependencies": {
161
161
  "@athenna/config": "1.0.8",
162
162
  "@athenna/ioc": "1.1.3",
163
- "@athenna/logger": "1.1.7",
163
+ "@athenna/logger": "1.1.8",
164
164
  "@secjs/utils": "1.8.3",
165
165
  "fastify": "3.27.4",
166
166
  "fastify-cors": "6.0.3",
@@ -11,8 +11,8 @@ import { ResponseContract } from '../ResponseContract';
11
11
  export interface ErrorContextContract {
12
12
  request: RequestContract;
13
13
  response: ResponseContract;
14
- params: Record<string, string>;
15
- queries: Record<string, string>;
16
- data?: Record<string, any>;
14
+ params: any;
15
+ queries: any;
16
+ data: any;
17
17
  error: any;
18
18
  }
@@ -7,11 +7,13 @@
7
7
  * file that was distributed with this source code.
8
8
  */
9
9
  import { RequestContract } from '../../RequestContract';
10
+ import { ResponseContract } from '../../ResponseContract';
10
11
  export interface InterceptContextContract {
11
12
  request: RequestContract;
13
+ response: ResponseContract;
12
14
  params: any;
13
15
  queries: any;
14
16
  body: any;
15
17
  status: number;
16
- data: Record<string, any>;
18
+ data: any;
17
19
  }
@@ -12,7 +12,7 @@ import { ResponseContract } from '../../ResponseContract';
12
12
  export interface TerminateContextContract {
13
13
  request: RequestContract;
14
14
  response: ResponseContract;
15
- data?: any;
15
+ data: any;
16
16
  params: any;
17
17
  queries: any;
18
18
  body: any;
@@ -14,11 +14,11 @@ import { InterceptHandlerContract } from '../Contracts/Context/Middlewares/Inter
14
14
  import { TerminateHandlerContract } from '../Contracts/Context/Middlewares/Terminate/TerminateHandlerContract';
15
15
  declare module 'fastify' {
16
16
  interface FastifyRequest {
17
- data: Record<string, any>;
17
+ data: any;
18
18
  }
19
19
  }
20
20
  export declare class FastifyHandler {
21
- static createOnSendHandler(handler: InterceptHandlerContract): (req: FastifyRequest, _res: any, payload: any) => Promise<any>;
21
+ static createOnSendHandler(handler: InterceptHandlerContract): (req: FastifyRequest, res: FastifyReply, payload: any) => Promise<any>;
22
22
  static createDoneHandler(handler: HandleHandlerContract): (req: FastifyRequest, res: FastifyReply, done: any) => any;
23
23
  static createResponseHandler(handler: TerminateHandlerContract): (req: FastifyRequest, res: FastifyReply, done: any) => any;
24
24
  static createErrorHandler(handler: ErrorHandlerContract): (error: any, req: FastifyRequest, res: FastifyReply) => any;
@@ -15,8 +15,9 @@ const Request_1 = require("../Context/Request");
15
15
  const Response_1 = require("../Context/Response");
16
16
  class FastifyHandler {
17
17
  static createOnSendHandler(handler) {
18
- return async (req, _res, payload) => {
18
+ return async (req, res, payload) => {
19
19
  const request = new Request_1.Request(req);
20
+ const response = new Response_1.Response(res);
20
21
  if (!req.data)
21
22
  req.data = {};
22
23
  if (!req.query)
@@ -29,8 +30,9 @@ class FastifyHandler {
29
30
  }
30
31
  body = await handler({
31
32
  request,
33
+ response,
32
34
  body,
33
- status: _res.statusCode,
35
+ status: res.statusCode,
34
36
  params: req.params,
35
37
  queries: req.query,
36
38
  data: req.data,
@@ -16,17 +16,33 @@ export declare abstract class HttpKernel {
16
16
  */
17
17
  protected abstract namedMiddlewares: Record<string, Promise<any> | MiddlewareContractClass>;
18
18
  /**
19
- * Returns an instance of any class that extends HttpKernel.
20
- * Also configure the error handler, detect environment and
21
- * configure log intercept middleware for requests.
19
+ * Register all global and named middlewares to the server.
22
20
  *
23
- * @return HttpKernel
21
+ * @return void
24
22
  */
25
- constructor();
23
+ registerMiddlewares(): Promise<void>;
26
24
  /**
27
- * Register all global and named middlewares to the server.
25
+ * Register cors plugin
28
26
  *
29
27
  * @return void
30
28
  */
31
- registerMiddlewares(): Promise<void>;
29
+ registerCors(): Promise<void>;
30
+ /**
31
+ * Register rate limit plugin
32
+ *
33
+ * @return void
34
+ */
35
+ registerRateLimit(): Promise<void>;
36
+ /**
37
+ * Register the default error handler
38
+ *
39
+ * @return void
40
+ */
41
+ registerErrorHandler(): Promise<void>;
42
+ /**
43
+ * Register log terminate middleware
44
+ *
45
+ * @return void
46
+ */
47
+ registerLogMiddleware(): Promise<void>;
32
48
  }
@@ -3,43 +3,26 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.HttpKernel = void 0;
4
4
  const logger_1 = require("@athenna/logger");
5
5
  const config_1 = require("@athenna/config");
6
+ const Server_1 = require("../Facades/Server");
6
7
  const utils_1 = require("@secjs/utils");
7
8
  const HttpErrorHandler_1 = require("../Handlers/HttpErrorHandler");
8
9
  class HttpKernel {
9
- /**
10
- * Returns an instance of any class that extends HttpKernel.
11
- * Also configure the error handler, detect environment and
12
- * configure log intercept middleware for requests.
13
- *
14
- * @return HttpKernel
15
- */
16
- constructor() {
17
- const httpServer = ioc.safeUse('Athenna/Core/HttpServer');
18
- httpServer.setErrorHandler(HttpErrorHandler_1.HttpErrorHandler.handler);
19
- if (config_1.Config.get('http.log')) {
20
- httpServer.use(async (ctx) => {
21
- await logger_1.Log.channel('request').log(ctx);
22
- return ctx.next();
23
- }, 'terminate');
24
- }
25
- }
26
10
  /**
27
11
  * Register all global and named middlewares to the server.
28
12
  *
29
13
  * @return void
30
14
  */
31
15
  async registerMiddlewares() {
32
- const httpServer = ioc.safeUse('Athenna/Core/HttpServer');
33
16
  /**
34
17
  * Binding the named middlewares inside the container and
35
18
  * creating a simple alias to use it inside Route.
36
19
  */
37
20
  for (const key of Object.keys(this.namedMiddlewares)) {
38
21
  const Middleware = utils_1.resolveModule(await this.namedMiddlewares[key]);
39
- if (!ioc.hasDependency(`App/Middlewares/${Middleware.name}`)) {
40
- ioc.bind(`App/Middlewares/${Middleware.name}`, Middleware);
22
+ if (!ioc.hasDependency(`App/Http/Middlewares/${Middleware.name}`)) {
23
+ ioc.bind(`App/Http/Middlewares/${Middleware.name}`, Middleware);
41
24
  }
42
- ioc.alias(`App/Middlewares/Names/${key}`, `App/Middlewares/${Middleware.name}`);
25
+ ioc.alias(`App/Http/Middlewares/Names/${key}`, `App/Http/Middlewares/${Middleware.name}`);
43
26
  }
44
27
  /**
45
28
  * Binding the global middlewares inside the container and
@@ -47,20 +30,67 @@ class HttpKernel {
47
30
  */
48
31
  for (const module of this.globalMiddlewares) {
49
32
  let Middleware = utils_1.resolveModule(await module);
50
- if (!ioc.hasDependency(`App/Middlewares/${Middleware.name}`)) {
51
- ioc.bind(`App/Middlewares/${Middleware.name}`, Middleware);
33
+ if (!ioc.hasDependency(`App/Http/Middlewares/${Middleware.name}`)) {
34
+ ioc.bind(`App/Http/Middlewares/${Middleware.name}`, Middleware);
52
35
  }
53
- Middleware = ioc.safeUse(`App/Middlewares/${Middleware.name}`);
36
+ Middleware = ioc.safeUse(`App/Http/Middlewares/${Middleware.name}`);
54
37
  if (Middleware.handle) {
55
- httpServer.use(Middleware.handle, 'handle');
38
+ Server_1.Server.use(Middleware.handle, 'handle');
56
39
  }
57
40
  if (Middleware.intercept) {
58
- httpServer.use(Middleware.intercept, 'intercept');
41
+ Server_1.Server.use(Middleware.intercept, 'intercept');
59
42
  }
60
43
  if (Middleware.terminate) {
61
- httpServer.use(Middleware.terminate, 'terminate');
44
+ Server_1.Server.use(Middleware.terminate, 'terminate');
62
45
  }
63
46
  }
64
47
  }
48
+ /**
49
+ * Register cors plugin
50
+ *
51
+ * @return void
52
+ */
53
+ async registerCors() {
54
+ if (config_1.Config.get('http.noCors')) {
55
+ return;
56
+ }
57
+ Server_1.Server.registerCors(config_1.Config.get('http.cors'));
58
+ }
59
+ /**
60
+ * Register rate limit plugin
61
+ *
62
+ * @return void
63
+ */
64
+ async registerRateLimit() {
65
+ if (config_1.Config.get('http.noRateLimit')) {
66
+ return;
67
+ }
68
+ Server_1.Server.registerRateLimit(config_1.Config.get('http.rateLimit'));
69
+ }
70
+ /**
71
+ * Register the default error handler
72
+ *
73
+ * @return void
74
+ */
75
+ async registerErrorHandler() {
76
+ if (config_1.Config.get('http.noErrorHandler')) {
77
+ return;
78
+ }
79
+ Server_1.Server.setErrorHandler(HttpErrorHandler_1.HttpErrorHandler.handler);
80
+ }
81
+ /**
82
+ * Register log terminate middleware
83
+ *
84
+ * @return void
85
+ */
86
+ async registerLogMiddleware() {
87
+ if (!config_1.Config.get('http.logRequests')) {
88
+ return;
89
+ }
90
+ Server_1.Server.use(async (ctx) => {
91
+ await logger_1.Log.channel('request').log(ctx);
92
+ return ctx.next();
93
+ }, 'terminate');
94
+ }
65
95
  }
66
96
  exports.HttpKernel = HttpKernel;
@@ -0,0 +1,17 @@
1
+ /**
2
+ * @athenna/http
3
+ *
4
+ * (c) João Lenon <lenon@athenna.io>
5
+ *
6
+ * For the full copyright and license information, please view the LICENSE
7
+ * file that was distributed with this source code.
8
+ */
9
+ import { ServiceProvider } from '@athenna/ioc';
10
+ export declare class ControllerProvider extends ServiceProvider {
11
+ /**
12
+ * Bootstrap any application services.
13
+ *
14
+ * @return void
15
+ */
16
+ boot(): Promise<void>;
17
+ }
@@ -0,0 +1,49 @@
1
+ "use strict";
2
+ /**
3
+ * @athenna/http
4
+ *
5
+ * (c) João Lenon <lenon@athenna.io>
6
+ *
7
+ * For the full copyright and license information, please view the LICENSE
8
+ * file that was distributed with this source code.
9
+ */
10
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
11
+ if (k2 === undefined) k2 = k;
12
+ Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
13
+ }) : (function(o, m, k, k2) {
14
+ if (k2 === undefined) k2 = k;
15
+ o[k2] = m[k];
16
+ }));
17
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
18
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
19
+ }) : function(o, v) {
20
+ o["default"] = v;
21
+ });
22
+ var __importStar = (this && this.__importStar) || function (mod) {
23
+ if (mod && mod.__esModule) return mod;
24
+ var result = {};
25
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
26
+ __setModuleDefault(result, mod);
27
+ return result;
28
+ };
29
+ Object.defineProperty(exports, "__esModule", { value: true });
30
+ exports.ControllerProvider = void 0;
31
+ const ioc_1 = require("@athenna/ioc");
32
+ const utils_1 = require("@secjs/utils");
33
+ const getAppFiles_1 = require("../Utils/getAppFiles");
34
+ class ControllerProvider extends ioc_1.ServiceProvider {
35
+ /**
36
+ * Bootstrap any application services.
37
+ *
38
+ * @return void
39
+ */
40
+ async boot() {
41
+ let controllers = getAppFiles_1.getAppFiles(utils_1.Path.app('Http/Controllers'));
42
+ controllers = await Promise.all(controllers.map(File => Promise.resolve().then(() => __importStar(require(File.path)))));
43
+ controllers.forEach(Module => {
44
+ const Controller = utils_1.resolveModule(Module);
45
+ this.container.bind(`App/Http/Controllers/${Controller.name}`, Controller);
46
+ });
47
+ }
48
+ }
49
+ exports.ControllerProvider = ControllerProvider;
@@ -0,0 +1,17 @@
1
+ /**
2
+ * @athenna/http
3
+ *
4
+ * (c) João Lenon <lenon@athenna.io>
5
+ *
6
+ * For the full copyright and license information, please view the LICENSE
7
+ * file that was distributed with this source code.
8
+ */
9
+ import { ServiceProvider } from '@athenna/ioc';
10
+ export declare class MiddlewareProvider extends ServiceProvider {
11
+ /**
12
+ * Bootstrap any application services.
13
+ *
14
+ * @return void
15
+ */
16
+ boot(): Promise<void>;
17
+ }
@@ -0,0 +1,49 @@
1
+ "use strict";
2
+ /**
3
+ * @athenna/http
4
+ *
5
+ * (c) João Lenon <lenon@athenna.io>
6
+ *
7
+ * For the full copyright and license information, please view the LICENSE
8
+ * file that was distributed with this source code.
9
+ */
10
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
11
+ if (k2 === undefined) k2 = k;
12
+ Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
13
+ }) : (function(o, m, k, k2) {
14
+ if (k2 === undefined) k2 = k;
15
+ o[k2] = m[k];
16
+ }));
17
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
18
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
19
+ }) : function(o, v) {
20
+ o["default"] = v;
21
+ });
22
+ var __importStar = (this && this.__importStar) || function (mod) {
23
+ if (mod && mod.__esModule) return mod;
24
+ var result = {};
25
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
26
+ __setModuleDefault(result, mod);
27
+ return result;
28
+ };
29
+ Object.defineProperty(exports, "__esModule", { value: true });
30
+ exports.MiddlewareProvider = void 0;
31
+ const ioc_1 = require("@athenna/ioc");
32
+ const utils_1 = require("@secjs/utils");
33
+ const getAppFiles_1 = require("../Utils/getAppFiles");
34
+ class MiddlewareProvider extends ioc_1.ServiceProvider {
35
+ /**
36
+ * Bootstrap any application services.
37
+ *
38
+ * @return void
39
+ */
40
+ async boot() {
41
+ let middlewares = getAppFiles_1.getAppFiles(utils_1.Path.app('Http/Middlewares'));
42
+ middlewares = await Promise.all(middlewares.map(File => Promise.resolve().then(() => __importStar(require(File.path)))));
43
+ middlewares.forEach(Module => {
44
+ const Controller = utils_1.resolveModule(Module);
45
+ this.container.bind(`App/Http/Middlewares/${Controller.name}`, Controller);
46
+ });
47
+ }
48
+ }
49
+ exports.MiddlewareProvider = MiddlewareProvider;
@@ -47,8 +47,8 @@ class Route {
47
47
  };
48
48
  const insertionType = prepend ? 'unshift' : 'push';
49
49
  if (utils_1.Is.String(middleware)) {
50
- const mid = ioc.use(`App/Middlewares/Names/${middleware}`) ||
51
- ioc.safeUse(`App/Middlewares/${middleware}`);
50
+ const mid = ioc.use(`App/Http/Middlewares/Names/${middleware}`) ||
51
+ ioc.safeUse(`App/Http/Middlewares/${middleware}`);
52
52
  if (!mid) {
53
53
  throw new MiddlewareNotFoundException_1.MiddlewareNotFoundException(middleware);
54
54
  }
@@ -90,7 +90,7 @@ class Route {
90
90
  };
91
91
  if (utils_1.Is.String(this.handler)) {
92
92
  const [controller, method] = this.handler.split('.');
93
- const dependency = ioc.safeUse(`App/Controllers/${controller}`);
93
+ const dependency = ioc.safeUse(`App/Http/Controllers/${controller}`);
94
94
  if (!dependency[method]) {
95
95
  throw new UndefinedControllerMethodException_1.UndefinedControllerMethodException(method, controller);
96
96
  }
@@ -16,9 +16,9 @@ import { TerminateHandlerContract } from '../Contracts/Context/Middlewares/Termi
16
16
  export declare class RouteGroup {
17
17
  routes: (Route | RouteResource | RouteGroup)[];
18
18
  constructor(routes: (Route | RouteResource | RouteGroup)[]);
19
- private invoke;
20
19
  prefix(prefix: string): this;
21
20
  as(name: string): this;
22
21
  namespace(namespace: string): this;
23
22
  middleware(middleware: HandlerContract | MiddlewareContract | InterceptHandlerContract | TerminateHandlerContract | string, type?: MiddlewareTypes, prepend?: boolean): this;
23
+ private invoke;
24
24
  }
@@ -15,20 +15,6 @@ class RouteGroup {
15
15
  constructor(routes) {
16
16
  this.routes = routes;
17
17
  }
18
- invoke(route, method, params) {
19
- if (route instanceof RouteResource_1.RouteResource) {
20
- route.routes.forEach(child => this.invoke(child, method, params));
21
- return;
22
- }
23
- if (route instanceof RouteGroup) {
24
- route.routes.forEach(child => this.invoke(child, method, params));
25
- return;
26
- }
27
- if (method === 'as' && !route.name) {
28
- throw new CannotDefineGroupException_1.CannotDefineGroupException();
29
- }
30
- route[method](...params);
31
- }
32
18
  prefix(prefix) {
33
19
  this.routes.forEach(route => this.invoke(route, 'prefix', [prefix]));
34
20
  return this;
@@ -47,5 +33,19 @@ class RouteGroup {
47
33
  });
48
34
  return this;
49
35
  }
36
+ invoke(route, method, params) {
37
+ if (route instanceof RouteResource_1.RouteResource) {
38
+ route.routes.forEach(child => this.invoke(child, method, params));
39
+ return;
40
+ }
41
+ if (route instanceof RouteGroup) {
42
+ route.routes.forEach(child => this.invoke(child, method, params));
43
+ return;
44
+ }
45
+ if (method === 'as' && !route.name) {
46
+ throw new CannotDefineGroupException_1.CannotDefineGroupException();
47
+ }
48
+ route[method](...params);
49
+ }
50
50
  }
51
51
  exports.RouteGroup = RouteGroup;
@@ -8,10 +8,10 @@
8
8
  */
9
9
  import { Route } from './Route';
10
10
  import { MiddlewareTypes } from '../Contracts/MiddlewareTypes';
11
+ import { MiddlewareContract } from '../Contracts/MiddlewareContract';
11
12
  import { HandlerContract } from '../Contracts/Context/HandlerContract';
12
13
  import { InterceptHandlerContract } from '../Contracts/Context/Middlewares/Intercept/InterceptHandlerContract';
13
14
  import { TerminateHandlerContract } from '../Contracts/Context/Middlewares/Terminate/TerminateHandlerContract';
14
- import { MiddlewareContract } from '../Contracts/MiddlewareContract';
15
15
  export declare class RouteResource {
16
16
  routes: Route[];
17
17
  private resource;
@@ -0,0 +1,10 @@
1
+ /**
2
+ * @athenna/http
3
+ *
4
+ * (c) João Lenon <lenon@athenna.io>
5
+ *
6
+ * For the full copyright and license information, please view the LICENSE
7
+ * file that was distributed with this source code.
8
+ */
9
+ import { File } from '@secjs/utils';
10
+ export declare function getAppFiles(path: string): File[];
@@ -0,0 +1,22 @@
1
+ "use strict";
2
+ /**
3
+ * @athenna/http
4
+ *
5
+ * (c) João Lenon <lenon@athenna.io>
6
+ *
7
+ * For the full copyright and license information, please view the LICENSE
8
+ * file that was distributed with this source code.
9
+ */
10
+ Object.defineProperty(exports, "__esModule", { value: true });
11
+ exports.getAppFiles = void 0;
12
+ const fs_1 = require("fs");
13
+ const utils_1 = require("@secjs/utils");
14
+ function getAppFiles(path) {
15
+ if (!fs_1.existsSync(path))
16
+ return [];
17
+ return (new utils_1.Folder(path)
18
+ .loadSync()
19
+ // Get all .js and .ts files but not the .d.ts.
20
+ .getFilesByPattern('!(*.d)*.*(js|ts)'));
21
+ }
22
+ exports.getAppFiles = getAppFiles;