@athenna/http 1.1.4 → 1.1.5

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.1.4",
3
+ "version": "1.1.5",
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,8 @@
160
160
  "dependencies": {
161
161
  "@athenna/config": "1.0.6",
162
162
  "@athenna/ioc": "1.1.1",
163
- "@secjs/utils": "1.8.2",
163
+ "@athenna/logger": "1.1.2",
164
+ "@secjs/utils": "1.8.3",
164
165
  "fastify": "3.27.4",
165
166
  "reflect-metadata": "0.1.13",
166
167
  "tscpaths": "0.0.9"
@@ -9,19 +9,95 @@
9
9
  import { FastifyRequest } from 'fastify';
10
10
  import { RequestContract } from '../Contracts/Context/RequestContract';
11
11
  export declare class Request implements RequestContract {
12
- private request;
12
+ private readonly request;
13
+ /**
14
+ * Create a new instance of Request.
15
+ *
16
+ * @return Request
17
+ */
13
18
  constructor(request: FastifyRequest);
19
+ /**
20
+ * Get the request ip.
21
+ *
22
+ * @return string
23
+ */
14
24
  get ip(): string;
25
+ /**
26
+ * Get the request method.
27
+ *
28
+ * @return string
29
+ */
15
30
  get method(): string;
31
+ /**
32
+ * Get the host url from request.
33
+ *
34
+ * @return string
35
+ */
16
36
  get hostUrl(): string;
37
+ /**
38
+ * Get the base request url.
39
+ *
40
+ * @return string
41
+ */
17
42
  get baseUrl(): string;
43
+ /**
44
+ * Get the original request url.
45
+ *
46
+ * @return string
47
+ */
18
48
  get originalUrl(): string;
19
- get body(): Record<string, any>;
20
- get params(): Record<string, string>;
21
- get queries(): Record<string, string>;
22
- get headers(): Record<string, string>;
23
- param(param: string, defaultValue?: string): string | undefined;
24
- query(query: string, defaultValue?: string): string | undefined;
25
- header(header: string, defaultValue?: string): string | undefined;
49
+ /**
50
+ * Get all body from request.
51
+ *
52
+ * @return any
53
+ */
54
+ get body(): any;
55
+ /**
56
+ * Get all params from request.
57
+ *
58
+ * @return any
59
+ */
60
+ get params(): any;
61
+ /**
62
+ * Get all queries from request.
63
+ *
64
+ * @return any
65
+ */
66
+ get queries(): any;
67
+ /**
68
+ * Get all headers from request.
69
+ *
70
+ * @return any
71
+ */
72
+ get headers(): any;
73
+ /**
74
+ * Get a value from the request params or the default value.
75
+ *
76
+ * @return any
77
+ */
78
+ param(param: string, defaultValue?: string): any;
79
+ /**
80
+ * Get a value from the request query param or the default value.
81
+ *
82
+ * @return any
83
+ */
84
+ query(query: string, defaultValue?: string): any;
85
+ /**
86
+ * Get a value from the request header or the default value.
87
+ *
88
+ * @return any
89
+ */
90
+ header(header: string, defaultValue?: string): any;
91
+ /**
92
+ * Get a value from the request body or the default value.
93
+ *
94
+ * @return any
95
+ */
26
96
  payload(payload: string, defaultValue?: string): any;
97
+ /**
98
+ * Get the default fastify request object.
99
+ *
100
+ * @return FastifyRequest
101
+ */
102
+ getFastifyRequest(): FastifyRequest;
27
103
  }
@@ -13,56 +13,135 @@ const utils_1 = require("@secjs/utils");
13
13
  const config_1 = require("@athenna/config");
14
14
  const removeSlash_1 = require("../Utils/removeSlash");
15
15
  class Request {
16
+ /**
17
+ * Create a new instance of Request.
18
+ *
19
+ * @return Request
20
+ */
16
21
  constructor(request) {
17
22
  this.request = request;
18
23
  }
24
+ /**
25
+ * Get the request ip.
26
+ *
27
+ * @return string
28
+ */
19
29
  get ip() {
20
30
  return this.request.ip;
21
31
  }
32
+ /**
33
+ * Get the request method.
34
+ *
35
+ * @return string
36
+ */
22
37
  get method() {
23
38
  return this.request.method;
24
39
  }
40
+ /**
41
+ * Get the host url from request.
42
+ *
43
+ * @return string
44
+ */
25
45
  get hostUrl() {
26
46
  const url = this.request.url;
27
- const port = config_1.Env('PORT', '1335');
28
- let host = config_1.Env('APP_DOMAIN', `http://localhost:${port}`);
29
- if (!utils_1.Is.Ip(host))
47
+ const port = config_1.Config.get('http.port', 1335);
48
+ let host = config_1.Config.get('http.domain', `http://localhost:${port}`);
49
+ if (!utils_1.Is.Ip(host) && !host.includes('localhost')) {
30
50
  host = host.replace(`:${port}`, '');
51
+ }
31
52
  return removeSlash_1.removeSlash(`${host}${url}`);
32
53
  }
54
+ /**
55
+ * Get the base request url.
56
+ *
57
+ * @return string
58
+ */
33
59
  get baseUrl() {
34
60
  return this.request.url.split('?')[0];
35
61
  }
62
+ /**
63
+ * Get the original request url.
64
+ *
65
+ * @return string
66
+ */
36
67
  get originalUrl() {
37
68
  return this.request.url;
38
69
  }
70
+ /**
71
+ * Get all body from request.
72
+ *
73
+ * @return any
74
+ */
39
75
  get body() {
40
76
  return this.request.body;
41
77
  }
78
+ /**
79
+ * Get all params from request.
80
+ *
81
+ * @return any
82
+ */
42
83
  get params() {
43
84
  return this.request.params;
44
85
  }
86
+ /**
87
+ * Get all queries from request.
88
+ *
89
+ * @return any
90
+ */
45
91
  get queries() {
46
92
  return this.request.query;
47
93
  }
94
+ /**
95
+ * Get all headers from request.
96
+ *
97
+ * @return any
98
+ */
48
99
  get headers() {
49
100
  return this.request.headers;
50
101
  }
102
+ /**
103
+ * Get a value from the request params or the default value.
104
+ *
105
+ * @return any
106
+ */
51
107
  param(param, defaultValue) {
52
108
  const params = this.request.params;
53
109
  return params[param] || defaultValue;
54
110
  }
111
+ /**
112
+ * Get a value from the request query param or the default value.
113
+ *
114
+ * @return any
115
+ */
55
116
  query(query, defaultValue) {
56
117
  const queries = this.request.query;
57
118
  return queries[query] || defaultValue;
58
119
  }
120
+ /**
121
+ * Get a value from the request header or the default value.
122
+ *
123
+ * @return any
124
+ */
59
125
  header(header, defaultValue) {
60
126
  const headers = this.request.headers;
61
127
  return headers[header] || defaultValue;
62
128
  }
129
+ /**
130
+ * Get a value from the request body or the default value.
131
+ *
132
+ * @return any
133
+ */
63
134
  payload(payload, defaultValue) {
64
135
  const body = this.request.body;
65
136
  return body[payload] || defaultValue;
66
137
  }
138
+ /**
139
+ * Get the default fastify request object.
140
+ *
141
+ * @return FastifyRequest
142
+ */
143
+ getFastifyRequest() {
144
+ return this.request;
145
+ }
67
146
  }
68
147
  exports.Request = Request;
@@ -9,13 +9,69 @@
9
9
  import { FastifyReply } from 'fastify';
10
10
  import { ResponseContract } from '../Contracts/Context/ResponseContract';
11
11
  export declare class Response implements ResponseContract {
12
- private response;
12
+ private readonly response;
13
+ /**
14
+ * Create a new instance of Response.
15
+ *
16
+ * @return Response
17
+ */
13
18
  constructor(response: FastifyReply);
14
- send(data?: Record<string, any>): void;
15
- json(data?: Record<string, any>): void;
19
+ /**
20
+ * Terminate the request sending the response body.
21
+ *
22
+ * @param data
23
+ * @return void
24
+ */
25
+ send(data?: any): void;
26
+ /**
27
+ * Terminate the request sending the response body.
28
+ *
29
+ * @param data
30
+ * @return void
31
+ */
32
+ json(data?: any): void;
33
+ /**
34
+ * Set the response status code.
35
+ *
36
+ * @param code
37
+ * @return Response
38
+ */
16
39
  status(code: number): this;
40
+ /**
41
+ * Remove some header from the response.
42
+ *
43
+ * @param header
44
+ * @return Response
45
+ */
17
46
  removeHeader(header: string): this;
47
+ /**
48
+ * Add some header to the response.
49
+ *
50
+ * @param header
51
+ * @param value
52
+ * @return Response
53
+ */
18
54
  header(header: string, value: any): this;
55
+ /**
56
+ * Only add some header to the response if it's not defined yet.
57
+ *
58
+ * @param header
59
+ * @param value
60
+ * @return Response
61
+ */
19
62
  safeHeader(header: string, value: any): this;
20
- redirectTo(url: string, statusCode?: number): this;
63
+ /**
64
+ * Redirect the response to other url with different status code.
65
+ *
66
+ * @param url
67
+ * @param statusCode
68
+ * @return void
69
+ */
70
+ redirectTo(url: string, statusCode?: number): void;
71
+ /**
72
+ * Get the default fastify response object.
73
+ *
74
+ * @return FastifyReply
75
+ */
76
+ getFastifyResponse(): FastifyReply;
21
77
  }
@@ -10,40 +10,96 @@
10
10
  Object.defineProperty(exports, "__esModule", { value: true });
11
11
  exports.Response = void 0;
12
12
  class Response {
13
+ /**
14
+ * Create a new instance of Response.
15
+ *
16
+ * @return Response
17
+ */
13
18
  constructor(response) {
14
19
  this.response = response;
15
20
  }
21
+ /**
22
+ * Terminate the request sending the response body.
23
+ *
24
+ * @param data
25
+ * @return void
26
+ */
16
27
  send(data) {
17
28
  this.response.send(data);
18
29
  }
30
+ /**
31
+ * Terminate the request sending the response body.
32
+ *
33
+ * @param data
34
+ * @return void
35
+ */
19
36
  json(data) {
20
- this.response.serialize(data);
37
+ this.response.send(this.response.serialize(data));
21
38
  }
39
+ /**
40
+ * Set the response status code.
41
+ *
42
+ * @param code
43
+ * @return Response
44
+ */
22
45
  status(code) {
23
46
  this.response.status(code);
24
47
  return this;
25
48
  }
49
+ /**
50
+ * Remove some header from the response.
51
+ *
52
+ * @param header
53
+ * @return Response
54
+ */
26
55
  removeHeader(header) {
27
56
  this.response.removeHeader(header);
28
57
  return this;
29
58
  }
59
+ /**
60
+ * Add some header to the response.
61
+ *
62
+ * @param header
63
+ * @param value
64
+ * @return Response
65
+ */
30
66
  header(header, value) {
31
67
  this.response.header(header, value);
32
68
  return this;
33
69
  }
70
+ /**
71
+ * Only add some header to the response if it's not defined yet.
72
+ *
73
+ * @param header
74
+ * @param value
75
+ * @return Response
76
+ */
34
77
  safeHeader(header, value) {
35
78
  if (!this.response.hasHeader(header)) {
36
79
  this.response.header(header, value);
37
80
  }
38
81
  return this;
39
82
  }
83
+ /**
84
+ * Redirect the response to other url with different status code.
85
+ *
86
+ * @param url
87
+ * @param statusCode
88
+ * @return void
89
+ */
40
90
  redirectTo(url, statusCode) {
41
91
  if (statusCode) {
42
92
  this.response.redirect(statusCode, url);
43
- return this;
44
93
  }
45
94
  this.response.redirect(url);
46
- return this;
95
+ }
96
+ /**
97
+ * Get the default fastify response object.
98
+ *
99
+ * @return FastifyReply
100
+ */
101
+ getFastifyResponse() {
102
+ return this.response;
47
103
  }
48
104
  }
49
105
  exports.Response = Response;
@@ -11,7 +11,7 @@ import { ResponseContract } from './ResponseContract';
11
11
  export interface ContextContract {
12
12
  request: RequestContract;
13
13
  response: ResponseContract;
14
- params: Record<string, string>;
15
- queries: Record<string, string>;
16
- data: Record<string, any>;
14
+ data: any;
15
+ params: any;
16
+ queries: any;
17
17
  }
@@ -12,8 +12,8 @@ import { ResponseContract } from '../../ResponseContract';
12
12
  export interface HandleContextContract {
13
13
  request: RequestContract;
14
14
  response: ResponseContract;
15
- params: Record<string, string>;
16
- queries: Record<string, string>;
17
- data: Record<string, any>;
15
+ data: any;
16
+ params: any;
17
+ queries: any;
18
18
  next: NextContract;
19
19
  }
@@ -9,8 +9,8 @@
9
9
  import { RequestContract } from '../../RequestContract';
10
10
  export interface InterceptContextContract {
11
11
  request: RequestContract;
12
- params: Record<string, string>;
13
- queries: Record<string, string>;
12
+ params: any;
13
+ queries: any;
14
14
  body: any;
15
15
  status: number;
16
16
  data: Record<string, any>;
@@ -12,8 +12,8 @@ import { ResponseContract } from '../../ResponseContract';
12
12
  export interface TerminateContextContract {
13
13
  request: RequestContract;
14
14
  response: ResponseContract;
15
- params: Record<string, string>;
16
- queries: Record<string, string>;
17
- data?: Record<string, any>;
15
+ data?: any;
16
+ params: any;
17
+ queries: any;
18
18
  next: NextContract;
19
19
  }
@@ -6,18 +6,20 @@
6
6
  * For the full copyright and license information, please view the LICENSE
7
7
  * file that was distributed with this source code.
8
8
  */
9
+ import { FastifyRequest } from 'fastify';
9
10
  export interface RequestContract {
10
11
  ip: string;
11
12
  method: string;
12
13
  hostUrl: string;
13
14
  baseUrl: string;
14
15
  originalUrl: string;
15
- body: Record<string, any>;
16
- params: Record<string, string>;
17
- queries: Record<string, string>;
18
- headers: Record<string, string>;
16
+ body: any;
17
+ params: any;
18
+ queries: any;
19
+ headers: any;
19
20
  param(param: string, defaultValue?: string): string | undefined;
20
21
  query(query: string, defaultValue?: string): string | undefined;
21
22
  header(header: string, defaultValue?: string): string | string[] | undefined;
22
23
  payload(payload: string, defaultValue?: string): any | undefined;
24
+ getFastifyRequest(): FastifyRequest;
23
25
  }
@@ -1,3 +1,4 @@
1
+ import { FastifyReply } from 'fastify';
1
2
  /**
2
3
  * @athenna/http
3
4
  *
@@ -7,12 +8,13 @@
7
8
  * file that was distributed with this source code.
8
9
  */
9
10
  export interface ResponseContract {
10
- send(data?: Record<string, any>): Promise<void> | void;
11
- json(data?: Record<string, any>): Promise<void> | void;
11
+ send(data?: any): Promise<void> | void;
12
+ json(data?: any): Promise<void> | void;
12
13
  status(code: number): this;
13
14
  removeHeader(header: string): this;
14
15
  header(header: string, value: any): this;
15
16
  safeHeader(header: string, value: any): this;
16
- redirectTo(url: string): this;
17
- redirectTo(url: string, statusCode: number): this;
17
+ redirectTo(url: string): Promise<void> | void;
18
+ redirectTo(url: string, statusCode: number): Promise<void> | void;
19
+ getFastifyResponse(): FastifyReply;
18
20
  }
@@ -1,10 +1,2 @@
1
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
2
  Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,12 @@
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 { ErrorContextContract } from '../Contracts/Context/Error/ErrorContextContract';
10
+ export declare class HttpErrorHandler {
11
+ static handler({ error, request, response }: ErrorContextContract): void | Promise<void>;
12
+ }
@@ -0,0 +1,45 @@
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.HttpErrorHandler = void 0;
12
+ const utils_1 = require("@secjs/utils");
13
+ const logger_1 = require("@athenna/logger");
14
+ const config_1 = require("@athenna/config");
15
+ class HttpErrorHandler {
16
+ static handler({ error, request, response }) {
17
+ const code = error.code || error.name;
18
+ const statusCode = error.statusCode || error.status || 500;
19
+ const body = {
20
+ code: utils_1.String.toSnakeCase(code).toUpperCase(),
21
+ path: request.baseUrl,
22
+ method: request.method,
23
+ status: statusCode <= 399 ? 'SUCCESS' : 'ERROR',
24
+ statusCode: statusCode,
25
+ error: {
26
+ name: error.name,
27
+ message: error.message,
28
+ stack: error.stack,
29
+ },
30
+ };
31
+ const isInternalServerError = statusCode === 500;
32
+ const isNotDebugMode = !config_1.Config.get('app.debug');
33
+ if (isInternalServerError && isNotDebugMode) {
34
+ body.error.name = 'Internal server error';
35
+ body.error.message =
36
+ 'An internal server exception has occurred. Please contact administration of this service.';
37
+ delete body.error.stack;
38
+ }
39
+ new logger_1.Logger().error(`Error: ${JSON.stringify(body.error, null, 2)}`, {
40
+ context: HttpErrorHandler.name,
41
+ });
42
+ return response.status(statusCode).send(body);
43
+ }
44
+ }
45
+ exports.HttpErrorHandler = HttpErrorHandler;
package/src/Http.d.ts CHANGED
@@ -16,22 +16,133 @@ import { HandleHandlerContract } from './Contracts/Context/Middlewares/Handle/Ha
16
16
  import { InterceptHandlerContract } from './Contracts/Context/Middlewares/Intercept/InterceptHandlerContract';
17
17
  import { TerminateHandlerContract } from './Contracts/Context/Middlewares/Terminate/TerminateHandlerContract';
18
18
  export declare class Http {
19
+ /**
20
+ * Holds the fastify server instance.
21
+ *
22
+ * @private
23
+ */
19
24
  private readonly server;
25
+ /**
26
+ * Instantiate Http class and fastify server.
27
+ *
28
+ * @return Http
29
+ */
20
30
  constructor();
31
+ /**
32
+ * Set the fastify error handler.
33
+ *
34
+ * @return Http
35
+ */
21
36
  setErrorHandler(handler: ErrorHandlerContract): void;
37
+ /**
38
+ * Get the fastify server instance.
39
+ *
40
+ * @return FastifyInstance
41
+ */
22
42
  getServer(): FastifyInstance;
43
+ /**
44
+ * Print all routes registered
45
+ *
46
+ * @param options {PrintRoutesOptions}
47
+ * @return string
48
+ */
23
49
  getRoutes(options?: PrintRoutesOptions): string;
50
+ /**
51
+ * Print all routes registered.
52
+ *
53
+ * @param handler {HandleHandlerContract,InterceptHandlerContract,TerminateHandlerContract}
54
+ * @param type {handle,intercept,terminate}
55
+ * @return void
56
+ */
24
57
  use(handler: HandleHandlerContract | InterceptHandlerContract | TerminateHandlerContract, type?: 'handle' | 'intercept' | 'terminate'): void;
25
58
  request(): LightMyRequest.Chain;
26
59
  request(options: InjectOptions | string): Promise<LightMyRequest.Response>;
60
+ /**
61
+ * Boot the http server to start listening on port and host defined.
62
+ *
63
+ * @param port {string,number}
64
+ * @param host {string}
65
+ * @return void
66
+ */
27
67
  listen(port?: string | number, host?: string): Promise<string>;
68
+ /**
69
+ * Close the http server.
70
+ *
71
+ * @param cb {any}
72
+ * @return Promise<void>
73
+ */
28
74
  close(cb?: any): Promise<void>;
75
+ /**
76
+ * Add a new route to the http server.
77
+ *
78
+ * @param url {string}
79
+ * @param methods {HttpMethodTypes[]}
80
+ * @param handler {HandlerContract}
81
+ * @param middlewares {MiddlewareTypesContract}
82
+ * @return void
83
+ */
29
84
  route(url: string, methods: HttpMethodTypes[], handler: HandlerContract, middlewares?: MiddlewareTypesContract): void;
85
+ /**
86
+ * Add a new GET route to the http server.
87
+ *
88
+ * @param url {string}
89
+ * @param handler {HandlerContract}
90
+ * @param middlewares {MiddlewareTypesContract}
91
+ * @return void
92
+ */
30
93
  get(url: string, handler: HandlerContract, middlewares?: MiddlewareTypesContract): void;
94
+ /**
95
+ * Add a new HEAD route to the http server.
96
+ *
97
+ * @param url {string}
98
+ * @param handler {HandlerContract}
99
+ * @param middlewares {MiddlewareTypesContract}
100
+ * @return void
101
+ */
31
102
  head(url: string, handler: HandlerContract, middlewares?: MiddlewareTypesContract): void;
103
+ /**
104
+ * Add a new POST route to the http server.
105
+ *
106
+ * @param url {string}
107
+ * @param handler {HandlerContract}
108
+ * @param middlewares {MiddlewareTypesContract}
109
+ * @return void
110
+ */
32
111
  post(url: string, handler: HandlerContract, middlewares?: MiddlewareTypesContract): void;
112
+ /**
113
+ * Add a new PUT route to the http server.
114
+ *
115
+ * @param url {string}
116
+ * @param handler {HandlerContract}
117
+ * @param middlewares {MiddlewareTypesContract}
118
+ * @return void
119
+ */
33
120
  put(url: string, handler: HandlerContract, middlewares?: MiddlewareTypesContract): void;
121
+ /**
122
+ * Add a new PATCH route to the http server.
123
+ *
124
+ * @param url {string}
125
+ * @param handler {HandlerContract}
126
+ * @param middlewares {MiddlewareTypesContract}
127
+ * @return void
128
+ */
34
129
  patch(url: string, handler: HandlerContract, middlewares?: MiddlewareTypesContract): void;
130
+ /**
131
+ * Add a new DELETE route to the http server.
132
+ *
133
+ * @param url {string}
134
+ * @param handler {HandlerContract}
135
+ * @param middlewares {MiddlewareTypesContract}
136
+ * @return void
137
+ */
35
138
  delete(url: string, handler: HandlerContract, middlewares?: MiddlewareTypesContract): void;
139
+ /**
140
+ * Add a new OPTIONS route to the http server.
141
+ *
142
+ * @param url {string}
143
+ * @param handler {HandlerContract}
144
+ * @param middlewares {MiddlewareTypesContract}
145
+ * @return void
146
+ */
36
147
  options(url: string, handler: HandlerContract, middlewares?: MiddlewareTypesContract): void;
37
148
  }
package/src/Http.js CHANGED
@@ -15,19 +15,47 @@ exports.Http = void 0;
15
15
  const fastify_1 = __importDefault(require("fastify"));
16
16
  const FastifyHandler_1 = require("./Utils/FastifyHandler");
17
17
  class Http {
18
+ /**
19
+ * Instantiate Http class and fastify server.
20
+ *
21
+ * @return Http
22
+ */
18
23
  constructor() {
19
24
  this.server = fastify_1.default();
20
25
  }
26
+ /**
27
+ * Set the fastify error handler.
28
+ *
29
+ * @return Http
30
+ */
21
31
  setErrorHandler(handler) {
22
32
  const fastifyErrorHandler = FastifyHandler_1.FastifyHandler.createErrorHandler(handler);
23
33
  this.server.setErrorHandler(fastifyErrorHandler);
24
34
  }
35
+ /**
36
+ * Get the fastify server instance.
37
+ *
38
+ * @return FastifyInstance
39
+ */
25
40
  getServer() {
26
41
  return this.server;
27
42
  }
43
+ /**
44
+ * Print all routes registered
45
+ *
46
+ * @param options {PrintRoutesOptions}
47
+ * @return string
48
+ */
28
49
  getRoutes(options) {
29
50
  return this.server.printRoutes(options);
30
51
  }
52
+ /**
53
+ * Print all routes registered.
54
+ *
55
+ * @param handler {HandleHandlerContract,InterceptHandlerContract,TerminateHandlerContract}
56
+ * @param type {handle,intercept,terminate}
57
+ * @return void
58
+ */
31
59
  use(handler, type = 'handle') {
32
60
  let hookName = 'preHandler';
33
61
  let handlerType = 'createDoneHandler';
@@ -43,6 +71,12 @@ class Http {
43
71
  }
44
72
  this.server.addHook(hookName, FastifyHandler_1.FastifyHandler[handlerType](handler));
45
73
  }
74
+ /**
75
+ * Return a request handler to make internal requests to the Http server.
76
+ *
77
+ * @param options {InjectOptions,string}
78
+ * @return {LightMyRequest.Chain,Promise<LightMyRequest.Response>}
79
+ */
46
80
  request(options) {
47
81
  const server = this.getServer();
48
82
  if (!options) {
@@ -50,9 +84,22 @@ class Http {
50
84
  }
51
85
  return server.inject(options);
52
86
  }
87
+ /**
88
+ * Boot the http server to start listening on port and host defined.
89
+ *
90
+ * @param port {string,number}
91
+ * @param host {string}
92
+ * @return void
93
+ */
53
94
  async listen(port, host) {
54
95
  return this.server.listen(port || 1335, host || 'localhost');
55
96
  }
97
+ /**
98
+ * Close the http server.
99
+ *
100
+ * @param cb {any}
101
+ * @return Promise<void>
102
+ */
56
103
  // eslint-disable-next-line @typescript-eslint/no-empty-function
57
104
  async close(cb) {
58
105
  if (cb) {
@@ -60,6 +107,15 @@ class Http {
60
107
  }
61
108
  return this.server.close();
62
109
  }
110
+ /**
111
+ * Add a new route to the http server.
112
+ *
113
+ * @param url {string}
114
+ * @param methods {HttpMethodTypes[]}
115
+ * @param handler {HandlerContract}
116
+ * @param middlewares {MiddlewareTypesContract}
117
+ * @return void
118
+ */
63
119
  route(url, methods, handler, middlewares) {
64
120
  const { handlers, terminators, interceptors } = Object.assign({}, { handlers: [], terminators: [], interceptors: [] }, middlewares);
65
121
  this.server.route({
@@ -71,24 +127,80 @@ class Http {
71
127
  onSend: interceptors.map(m => FastifyHandler_1.FastifyHandler.createOnSendHandler(m)),
72
128
  });
73
129
  }
130
+ /**
131
+ * Add a new GET route to the http server.
132
+ *
133
+ * @param url {string}
134
+ * @param handler {HandlerContract}
135
+ * @param middlewares {MiddlewareTypesContract}
136
+ * @return void
137
+ */
74
138
  get(url, handler, middlewares) {
75
139
  this.route(url, ['GET'], handler, middlewares);
76
140
  }
141
+ /**
142
+ * Add a new HEAD route to the http server.
143
+ *
144
+ * @param url {string}
145
+ * @param handler {HandlerContract}
146
+ * @param middlewares {MiddlewareTypesContract}
147
+ * @return void
148
+ */
77
149
  head(url, handler, middlewares) {
78
150
  this.route(url, ['HEAD'], handler, middlewares);
79
151
  }
152
+ /**
153
+ * Add a new POST route to the http server.
154
+ *
155
+ * @param url {string}
156
+ * @param handler {HandlerContract}
157
+ * @param middlewares {MiddlewareTypesContract}
158
+ * @return void
159
+ */
80
160
  post(url, handler, middlewares) {
81
161
  this.route(url, ['POST'], handler, middlewares);
82
162
  }
163
+ /**
164
+ * Add a new PUT route to the http server.
165
+ *
166
+ * @param url {string}
167
+ * @param handler {HandlerContract}
168
+ * @param middlewares {MiddlewareTypesContract}
169
+ * @return void
170
+ */
83
171
  put(url, handler, middlewares) {
84
172
  this.route(url, ['PUT'], handler, middlewares);
85
173
  }
174
+ /**
175
+ * Add a new PATCH route to the http server.
176
+ *
177
+ * @param url {string}
178
+ * @param handler {HandlerContract}
179
+ * @param middlewares {MiddlewareTypesContract}
180
+ * @return void
181
+ */
86
182
  patch(url, handler, middlewares) {
87
183
  this.route(url, ['PATCH'], handler, middlewares);
88
184
  }
185
+ /**
186
+ * Add a new DELETE route to the http server.
187
+ *
188
+ * @param url {string}
189
+ * @param handler {HandlerContract}
190
+ * @param middlewares {MiddlewareTypesContract}
191
+ * @return void
192
+ */
89
193
  delete(url, handler, middlewares) {
90
194
  this.route(url, ['DELETE'], handler, middlewares);
91
195
  }
196
+ /**
197
+ * Add a new OPTIONS route to the http server.
198
+ *
199
+ * @param url {string}
200
+ * @param handler {HandlerContract}
201
+ * @param middlewares {MiddlewareTypesContract}
202
+ * @return void
203
+ */
92
204
  options(url, handler, middlewares) {
93
205
  this.route(url, ['OPTIONS'], handler, middlewares);
94
206
  }
@@ -8,11 +8,25 @@ export declare abstract class HttpKernel {
8
8
  *
9
9
  * This middlewares are run during every request to your http server.
10
10
  */
11
- protected abstract globalMiddlewares: MiddlewareContractClass[];
11
+ protected abstract globalMiddlewares: MiddlewareContractClass[] | Promise<any>[];
12
12
  /**
13
13
  * The application's named HTTP middlewares.
14
14
  *
15
15
  * Here you define all your named middlewares to use inside routes/http file.
16
16
  */
17
- protected abstract namedMiddlewares: Record<string, MiddlewareContractClass>;
17
+ protected abstract namedMiddlewares: Record<string, Promise<any> | MiddlewareContractClass>;
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.
22
+ *
23
+ * @return HttpKernel
24
+ */
25
+ constructor();
26
+ /**
27
+ * Register all global and named middlewares to the server.
28
+ *
29
+ * @return void
30
+ */
31
+ registerMiddlewares(): Promise<void>;
18
32
  }
@@ -1,6 +1,66 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.HttpKernel = void 0;
4
+ const config_1 = require("@athenna/config");
5
+ const logger_1 = require("@athenna/logger");
6
+ const HttpErrorHandler_1 = require("../Handlers/HttpErrorHandler");
7
+ const utils_1 = require("@secjs/utils");
4
8
  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 new logger_1.Logger().channel('requests').log(ctx);
22
+ return ctx.body;
23
+ }, 'intercept');
24
+ }
25
+ }
26
+ /**
27
+ * Register all global and named middlewares to the server.
28
+ *
29
+ * @return void
30
+ */
31
+ async registerMiddlewares() {
32
+ const httpServer = ioc.safeUse('Athenna/Core/HttpServer');
33
+ /**
34
+ * Binding the named middlewares inside the container and
35
+ * creating a simple alias to use it inside Route.
36
+ */
37
+ for (const key of Object.keys(this.namedMiddlewares)) {
38
+ 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);
41
+ }
42
+ ioc.alias(`App/Middlewares/Names/${key}`, `App/Middlewares/${Middleware.name}`);
43
+ }
44
+ /**
45
+ * Binding the global middlewares inside the container and
46
+ * resolving it inside the Http server using "use" method.
47
+ */
48
+ for (const module of this.globalMiddlewares) {
49
+ let Middleware = utils_1.resolveModule(await module);
50
+ if (!ioc.hasDependency(`App/Middlewares/${Middleware.name}`)) {
51
+ ioc.bind(`App/Middlewares/${Middleware.name}`, Middleware);
52
+ }
53
+ Middleware = ioc.safeUse(`App/Middlewares/${Middleware.name}`);
54
+ if (Middleware.handle) {
55
+ httpServer.use(Middleware.handle, 'handle');
56
+ }
57
+ if (Middleware.intercept) {
58
+ httpServer.use(Middleware.intercept, 'intercept');
59
+ }
60
+ if (Middleware.terminate) {
61
+ httpServer.use(Middleware.terminate, 'terminate');
62
+ }
63
+ }
64
+ }
5
65
  }
6
66
  exports.HttpKernel = HttpKernel;
@@ -20,7 +20,7 @@ declare module 'fastify' {
20
20
  export declare class FastifyHandler {
21
21
  static createOnSendHandler(handler: InterceptHandlerContract): (req: any, _res: any, payload: any) => Promise<any>;
22
22
  static createDoneHandler(handler: HandleHandlerContract): (req: any, res: any, done: any) => any;
23
- static createResponseHandler(handler: TerminateHandlerContract): (req: any, res: any, done: any) => any;
23
+ static createResponseHandler(handler: TerminateHandlerContract): (req: any, res: FastifyReply, done: any) => any;
24
24
  static createErrorHandler(handler: ErrorHandlerContract): (error: any, req: FastifyRequest, res: FastifyReply) => any;
25
25
  static createRequestHandler(handler: HandlerContract): (req: FastifyRequest, res: FastifyReply) => Promise<any>;
26
26
  }