@athenna/http 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.
Files changed (75) hide show
  1. package/LICENSE.md +21 -0
  2. package/README.md +34 -0
  3. package/index.d.ts +23 -0
  4. package/index.js +35 -0
  5. package/package.json +167 -0
  6. package/src/Context/Request.d.ts +27 -0
  7. package/src/Context/Request.js +68 -0
  8. package/src/Context/Response.d.ts +21 -0
  9. package/src/Context/Response.js +49 -0
  10. package/src/Contracts/Context/ContextContract.d.ts +17 -0
  11. package/src/Contracts/Context/ContextContract.js +10 -0
  12. package/src/Contracts/Context/Error/ErrorContextContract.d.ts +18 -0
  13. package/src/Contracts/Context/Error/ErrorContextContract.js +10 -0
  14. package/src/Contracts/Context/Error/ErrorHandlerContract.d.ts +12 -0
  15. package/src/Contracts/Context/Error/ErrorHandlerContract.js +10 -0
  16. package/src/Contracts/Context/HandlerContract.d.ts +12 -0
  17. package/src/Contracts/Context/HandlerContract.js +10 -0
  18. package/src/Contracts/Context/Middlewares/Handle/HandleContextContract.d.ts +19 -0
  19. package/src/Contracts/Context/Middlewares/Handle/HandleContextContract.js +10 -0
  20. package/src/Contracts/Context/Middlewares/Handle/HandleHandlerContract.d.ts +12 -0
  21. package/src/Contracts/Context/Middlewares/Handle/HandleHandlerContract.js +10 -0
  22. package/src/Contracts/Context/Middlewares/Intercept/InterceptContextContract.d.ts +20 -0
  23. package/src/Contracts/Context/Middlewares/Intercept/InterceptContextContract.js +10 -0
  24. package/src/Contracts/Context/Middlewares/Intercept/InterceptHandlerContract.d.ts +12 -0
  25. package/src/Contracts/Context/Middlewares/Intercept/InterceptHandlerContract.js +10 -0
  26. package/src/Contracts/Context/Middlewares/Intercept/NextInterceptContract.d.ts +11 -0
  27. package/src/Contracts/Context/Middlewares/Intercept/NextInterceptContract.js +10 -0
  28. package/src/Contracts/Context/Middlewares/Terminate/TerminateContextContract.d.ts +19 -0
  29. package/src/Contracts/Context/Middlewares/Terminate/TerminateContextContract.js +10 -0
  30. package/src/Contracts/Context/Middlewares/Terminate/TerminateHandlerContract.d.ts +12 -0
  31. package/src/Contracts/Context/Middlewares/Terminate/TerminateHandlerContract.js +10 -0
  32. package/src/Contracts/Context/NextContract.d.ts +11 -0
  33. package/src/Contracts/Context/NextContract.js +10 -0
  34. package/src/Contracts/Context/RequestContract.d.ts +23 -0
  35. package/src/Contracts/Context/RequestContract.js +10 -0
  36. package/src/Contracts/Context/ResponseContract.d.ts +18 -0
  37. package/src/Contracts/Context/ResponseContract.js +10 -0
  38. package/src/Contracts/FastifyErrorHandlerContract.d.ts +12 -0
  39. package/src/Contracts/FastifyErrorHandlerContract.js +10 -0
  40. package/src/Contracts/FastifyHandlerContract.d.ts +12 -0
  41. package/src/Contracts/FastifyHandlerContract.js +10 -0
  42. package/src/Contracts/HttpMethodTypes.d.ts +9 -0
  43. package/src/Contracts/HttpMethodTypes.js +10 -0
  44. package/src/Contracts/MiddlewareContract.d.ts +16 -0
  45. package/src/Contracts/MiddlewareContract.js +10 -0
  46. package/src/Contracts/MiddlewareTypes.d.ts +9 -0
  47. package/src/Contracts/MiddlewareTypes.js +10 -0
  48. package/src/Contracts/MiddlewareTypesContract.d.ts +16 -0
  49. package/src/Contracts/MiddlewareTypesContract.js +10 -0
  50. package/src/Contracts/RouteContract.d.ts +16 -0
  51. package/src/Contracts/RouteContract.js +10 -0
  52. package/src/Exceptions/BadRequestException.d.ts +12 -0
  53. package/src/Exceptions/BadRequestException.js +18 -0
  54. package/src/Exceptions/CannotDefineGroupException.d.ts +12 -0
  55. package/src/Exceptions/CannotDefineGroupException.js +19 -0
  56. package/src/Exceptions/MiddlewareNotFoundException.d.ts +12 -0
  57. package/src/Exceptions/MiddlewareNotFoundException.js +19 -0
  58. package/src/Http.d.ts +34 -0
  59. package/src/Http.js +91 -0
  60. package/src/Router/Route.d.ts +42 -0
  61. package/src/Router/Route.js +99 -0
  62. package/src/Router/RouteGroup.d.ts +24 -0
  63. package/src/Router/RouteGroup.js +51 -0
  64. package/src/Router/RouteResource.d.ts +29 -0
  65. package/src/Router/RouteResource.js +84 -0
  66. package/src/Router/Router.d.ts +36 -0
  67. package/src/Router/Router.js +123 -0
  68. package/src/Utils/FastifyHandler.d.ts +24 -0
  69. package/src/Utils/FastifyHandler.js +106 -0
  70. package/src/Utils/defaultErrorHandler.d.ts +10 -0
  71. package/src/Utils/defaultErrorHandler.js +30 -0
  72. package/src/Utils/isMiddlewareContract.d.ts +10 -0
  73. package/src/Utils/isMiddlewareContract.js +15 -0
  74. package/src/Utils/removeSlash.d.ts +9 -0
  75. package/src/Utils/removeSlash.js +23 -0
@@ -0,0 +1,99 @@
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.Route = void 0;
12
+ require("@athenna/ioc");
13
+ const utils_1 = require("@secjs/utils");
14
+ const removeSlash_1 = require("../Utils/removeSlash");
15
+ const isMiddlewareContract_1 = require("../Utils/isMiddlewareContract");
16
+ const MiddlewareNotFoundException_1 = require("../Exceptions/MiddlewareNotFoundException");
17
+ class Route {
18
+ constructor(url, methods, handler) {
19
+ this.url = url;
20
+ this.deleted = false;
21
+ this.methods = methods;
22
+ this.prefixes = [];
23
+ this.deleted = false;
24
+ this.routeMiddlewares = { handlers: [], terminators: [], interceptors: [] };
25
+ if (utils_1.Is.String(handler)) {
26
+ const [controller, method] = handler.split('.');
27
+ handler = ioc.use(`App/Controllers/${controller}`)[method];
28
+ }
29
+ this.handler = handler;
30
+ }
31
+ getUrl() {
32
+ const url = removeSlash_1.removeSlash(this.url);
33
+ const prefix = this.prefixes
34
+ .slice()
35
+ .reverse()
36
+ .map(p => removeSlash_1.removeSlash(p))
37
+ .join('');
38
+ return prefix ? `${prefix}${url === '/' ? '' : url}` : url;
39
+ }
40
+ prefix(prefix) {
41
+ this.prefixes.push(prefix);
42
+ return this;
43
+ }
44
+ as(name, prepend = false) {
45
+ this.name = prepend ? `${name}.${this.name}` : name;
46
+ return this;
47
+ }
48
+ namespace(namespace, overwrite = false) {
49
+ if (!this.routeNamespace || overwrite) {
50
+ this.routeNamespace = namespace;
51
+ }
52
+ return this;
53
+ }
54
+ middleware(middleware, type = 'handle', prepend = false) {
55
+ const dictionary = {
56
+ handle: 'handlers',
57
+ terminate: 'terminators',
58
+ intercept: 'interceptors',
59
+ };
60
+ const insertionType = prepend ? 'unshift' : 'push';
61
+ if (utils_1.Is.String(middleware)) {
62
+ const mid = ioc.use(`App/Middlewares/${middleware}`);
63
+ if (!mid) {
64
+ throw new MiddlewareNotFoundException_1.MiddlewareNotFoundException(middleware);
65
+ }
66
+ if (mid.handle)
67
+ this.routeMiddlewares.handlers[insertionType](mid.handle);
68
+ if (mid.intercept)
69
+ this.routeMiddlewares.interceptors[insertionType](mid.intercept);
70
+ if (mid.terminate)
71
+ this.routeMiddlewares.terminators[insertionType](mid.terminate);
72
+ return this;
73
+ }
74
+ if (isMiddlewareContract_1.isMiddlewareContract(middleware)) {
75
+ if (middleware.handle)
76
+ this.routeMiddlewares.handlers[insertionType](middleware.handle);
77
+ if (middleware.intercept)
78
+ this.routeMiddlewares.interceptors[insertionType](middleware.intercept);
79
+ if (middleware.terminate)
80
+ this.routeMiddlewares.terminators[insertionType](middleware.terminate);
81
+ return this;
82
+ }
83
+ this.routeMiddlewares[dictionary[type]][insertionType](middleware);
84
+ return this;
85
+ }
86
+ toJSON() {
87
+ return {
88
+ name: this.name,
89
+ url: this.getUrl(),
90
+ handler: this.handler,
91
+ methods: this.methods,
92
+ middlewares: this.routeMiddlewares,
93
+ meta: {
94
+ namespace: this.routeNamespace,
95
+ },
96
+ };
97
+ }
98
+ }
99
+ exports.Route = Route;
@@ -0,0 +1,24 @@
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 { Route } from './Route';
10
+ import { RouteResource } from './RouteResource';
11
+ import { MiddlewareTypes } from '../Contracts/MiddlewareTypes';
12
+ import { MiddlewareContract } from '../Contracts/MiddlewareContract';
13
+ import { HandlerContract } from '../Contracts/Context/HandlerContract';
14
+ import { InterceptHandlerContract } from '../Contracts/Context/Middlewares/Intercept/InterceptHandlerContract';
15
+ import { TerminateHandlerContract } from '../Contracts/Context/Middlewares/Terminate/TerminateHandlerContract';
16
+ export declare class RouteGroup {
17
+ routes: (Route | RouteResource | RouteGroup)[];
18
+ constructor(routes: (Route | RouteResource | RouteGroup)[]);
19
+ private invoke;
20
+ prefix(prefix: string): this;
21
+ as(name: string): this;
22
+ namespace(namespace: string): this;
23
+ middleware(middleware: HandlerContract | MiddlewareContract | InterceptHandlerContract | TerminateHandlerContract | string, type?: MiddlewareTypes, prepend?: boolean): this;
24
+ }
@@ -0,0 +1,51 @@
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.RouteGroup = void 0;
12
+ const RouteResource_1 = require("./RouteResource");
13
+ const CannotDefineGroupException_1 = require("../Exceptions/CannotDefineGroupException");
14
+ class RouteGroup {
15
+ constructor(routes) {
16
+ this.routes = routes;
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
+ prefix(prefix) {
33
+ this.routes.forEach(route => this.invoke(route, 'prefix', [prefix]));
34
+ return this;
35
+ }
36
+ as(name) {
37
+ this.routes.forEach(route => this.invoke(route, 'as', [name, true]));
38
+ return this;
39
+ }
40
+ namespace(namespace) {
41
+ this.routes.forEach(route => this.invoke(route, 'namespace', [namespace]));
42
+ return this;
43
+ }
44
+ middleware(middleware, type = 'handle', prepend = false) {
45
+ this.routes.forEach(route => {
46
+ this.invoke(route, 'middleware', [middleware, type, prepend]);
47
+ });
48
+ return this;
49
+ }
50
+ }
51
+ exports.RouteGroup = RouteGroup;
@@ -0,0 +1,29 @@
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 { Route } from './Route';
10
+ import { MiddlewareTypes } from '../Contracts/MiddlewareTypes';
11
+ import { HandlerContract } from '../Contracts/Context/HandlerContract';
12
+ import { InterceptHandlerContract } from '../Contracts/Context/Middlewares/Intercept/InterceptHandlerContract';
13
+ import { TerminateHandlerContract } from '../Contracts/Context/Middlewares/Terminate/TerminateHandlerContract';
14
+ import { MiddlewareContract } from '../Contracts/MiddlewareContract';
15
+ export declare class RouteResource {
16
+ private resource;
17
+ private readonly controller;
18
+ private resourceName;
19
+ routes: Route[];
20
+ constructor(resource: string, controller: any);
21
+ private makeRoute;
22
+ private buildRoutes;
23
+ private filter;
24
+ middleware(middleware: HandlerContract | MiddlewareContract | InterceptHandlerContract | TerminateHandlerContract | string, type?: MiddlewareTypes): this;
25
+ only(names: string[]): this;
26
+ except(names: string[]): this;
27
+ namespace(namespace: string): this;
28
+ as(name: string): this;
29
+ }
@@ -0,0 +1,84 @@
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.RouteResource = void 0;
12
+ const Route_1 = require("./Route");
13
+ const utils_1 = require("@secjs/utils");
14
+ class RouteResource {
15
+ constructor(resource, controller) {
16
+ this.routes = [];
17
+ this.resource = resource;
18
+ this.controller = controller;
19
+ this.resourceName = this.resource
20
+ .split('.')
21
+ .map(string => utils_1.String.toSnakeCase(string))
22
+ .join('.');
23
+ this.buildRoutes();
24
+ }
25
+ makeRoute(url, methods, action) {
26
+ let handler = '';
27
+ if (utils_1.Is.String(this.controller)) {
28
+ handler = `${this.controller}.${action}`;
29
+ }
30
+ else {
31
+ handler = this.controller[action];
32
+ }
33
+ const route = new Route_1.Route(url, methods, handler);
34
+ route.as(`${this.resourceName}.${action}`);
35
+ this.routes.push(route);
36
+ }
37
+ buildRoutes() {
38
+ this.resource = this.resource.replace(/^\//, '').replace(/\/$/, '');
39
+ const resourceTokens = this.resource.split('.');
40
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
41
+ const mainResource = resourceTokens.pop();
42
+ const fullUrl = `${resourceTokens
43
+ .map(string => `${string}/:${utils_1.String.toSnakeCase(utils_1.String.singularize(string))}_id`)
44
+ .join('/')}/${mainResource}`;
45
+ this.makeRoute(fullUrl, ['HEAD', 'GET'], 'index');
46
+ this.makeRoute(fullUrl, ['POST'], 'store');
47
+ this.makeRoute(`${fullUrl}/:id`, ['HEAD', 'GET'], 'show');
48
+ this.makeRoute(`${fullUrl}/:id`, ['PUT', 'PATCH'], 'update');
49
+ this.makeRoute(`${fullUrl}/:id`, ['DELETE'], 'delete');
50
+ }
51
+ filter(names, inverse) {
52
+ return this.routes.filter(route => {
53
+ const match = names.find(name => route.name.endsWith(name));
54
+ return inverse ? !match : match;
55
+ });
56
+ }
57
+ middleware(middleware, type = 'handle') {
58
+ this.routes.forEach(route => route.middleware(middleware, type));
59
+ return this;
60
+ }
61
+ only(names) {
62
+ this.filter(names, true).forEach(route => (route.deleted = true));
63
+ return this;
64
+ }
65
+ except(names) {
66
+ this.filter(names, false).forEach(route => (route.deleted = true));
67
+ return this;
68
+ }
69
+ namespace(namespace) {
70
+ this.routes.forEach(route => {
71
+ route.namespace(namespace);
72
+ });
73
+ return this;
74
+ }
75
+ as(name) {
76
+ name = utils_1.String.toSnakeCase(name);
77
+ this.routes.forEach(route => {
78
+ route.as(route.name.replace(this.resourceName, name), false);
79
+ });
80
+ this.resourceName = name;
81
+ return this;
82
+ }
83
+ }
84
+ exports.RouteResource = RouteResource;
@@ -0,0 +1,36 @@
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 { Route } from './Route';
10
+ import { RouteGroup } from './RouteGroup';
11
+ import { RouteResource } from './RouteResource';
12
+ import { HttpMethodTypes } from '../Contracts/HttpMethodTypes';
13
+ import { HandlerContract } from '../Contracts/Context/HandlerContract';
14
+ export declare class Router {
15
+ routes: (Route | RouteResource | RouteGroup)[];
16
+ private readonly openedGroups;
17
+ private getRecentGroup;
18
+ private readonly http;
19
+ private controllerInstance;
20
+ constructor();
21
+ listRoutes(): any;
22
+ controller(controller: any): this;
23
+ route(url: string, methods: HttpMethodTypes[], handler: HandlerContract | string): Route;
24
+ group(callback: () => void): RouteGroup;
25
+ resource(resource: string, controller: any): RouteResource;
26
+ get(url: string, handler: HandlerContract | string): Route;
27
+ head(url: string, handler: HandlerContract | string): Route;
28
+ post(url: string, handler: HandlerContract | string): Route;
29
+ put(url: string, handler: HandlerContract | string): Route;
30
+ patch(url: string, handler: HandlerContract | string): Route;
31
+ delete(url: string, handler: HandlerContract | string): Route;
32
+ options(url: string, handler: HandlerContract | string): Route;
33
+ any(url: string, handler: HandlerContract | string): Route;
34
+ register(): void;
35
+ toRoutesJSON(routes?: any): any;
36
+ }
@@ -0,0 +1,123 @@
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.Router = void 0;
12
+ const Http_1 = require("../Http");
13
+ const Route_1 = require("./Route");
14
+ const utils_1 = require("@secjs/utils");
15
+ const ioc_1 = require("@athenna/ioc");
16
+ const RouteGroup_1 = require("./RouteGroup");
17
+ const RouteResource_1 = require("./RouteResource");
18
+ class Router {
19
+ constructor() {
20
+ this.http = new ioc_1.Ioc().use('App/HttpServer') || new Http_1.Http();
21
+ this.routes = [];
22
+ this.openedGroups = [];
23
+ }
24
+ getRecentGroup() {
25
+ return this.openedGroups[this.openedGroups.length - 1];
26
+ }
27
+ listRoutes() {
28
+ return this.toRoutesJSON(this.routes);
29
+ }
30
+ controller(controller) {
31
+ this.controllerInstance = controller;
32
+ return this;
33
+ }
34
+ route(url, methods, handler) {
35
+ if (this.controllerInstance &&
36
+ utils_1.Is.String(handler) &&
37
+ !handler.includes('.')) {
38
+ handler = this.controllerInstance[handler];
39
+ }
40
+ const route = new Route_1.Route(url, methods, handler);
41
+ const openedGroup = this.getRecentGroup();
42
+ if (openedGroup) {
43
+ openedGroup.routes.push(route);
44
+ }
45
+ else {
46
+ this.routes.push(route);
47
+ }
48
+ return route;
49
+ }
50
+ group(callback) {
51
+ const group = new RouteGroup_1.RouteGroup([]);
52
+ const openedGroup = this.getRecentGroup();
53
+ if (openedGroup) {
54
+ openedGroup.routes.push(group);
55
+ }
56
+ else {
57
+ this.routes.push(group);
58
+ }
59
+ this.openedGroups.push(group);
60
+ callback();
61
+ this.openedGroups.pop();
62
+ return group;
63
+ }
64
+ resource(resource, controller) {
65
+ const resourceInstance = new RouteResource_1.RouteResource(resource, controller);
66
+ const openedGroup = this.getRecentGroup();
67
+ if (openedGroup) {
68
+ openedGroup.routes.push(resourceInstance);
69
+ }
70
+ else {
71
+ this.routes.push(resourceInstance);
72
+ }
73
+ return resourceInstance;
74
+ }
75
+ get(url, handler) {
76
+ return this.route(url, ['GET', 'HEAD'], handler);
77
+ }
78
+ head(url, handler) {
79
+ return this.route(url, ['HEAD'], handler);
80
+ }
81
+ post(url, handler) {
82
+ return this.route(url, ['POST'], handler);
83
+ }
84
+ put(url, handler) {
85
+ return this.route(url, ['PUT'], handler);
86
+ }
87
+ patch(url, handler) {
88
+ return this.route(url, ['PATCH'], handler);
89
+ }
90
+ delete(url, handler) {
91
+ return this.route(url, ['DELETE'], handler);
92
+ }
93
+ options(url, handler) {
94
+ return this.route(url, ['OPTIONS'], handler);
95
+ }
96
+ any(url, handler) {
97
+ return this.route(url, ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'], handler);
98
+ }
99
+ register() {
100
+ this.toRoutesJSON(this.routes).forEach(route => {
101
+ route.methods.forEach(method => {
102
+ this.http[method.toLowerCase()](route.url, route.handler, route.middlewares);
103
+ });
104
+ });
105
+ }
106
+ toRoutesJSON(routes) {
107
+ return routes.reduce((list, route) => {
108
+ if (route instanceof RouteGroup_1.RouteGroup) {
109
+ list = list.concat(this.toRoutesJSON(route.routes));
110
+ return list;
111
+ }
112
+ if (route instanceof RouteResource_1.RouteResource) {
113
+ list = list.concat(this.toRoutesJSON(route.routes));
114
+ return list;
115
+ }
116
+ if (!route.deleted) {
117
+ list.push(route.toJSON());
118
+ }
119
+ return list;
120
+ }, []);
121
+ }
122
+ }
123
+ exports.Router = Router;
@@ -0,0 +1,24 @@
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 { FastifyReply, FastifyRequest } from 'fastify';
10
+ import { HandlerContract } from '../Contracts/Context/HandlerContract';
11
+ import { ErrorHandlerContract } from '../Contracts/Context/Error/ErrorHandlerContract';
12
+ import { HandleHandlerContract } from '../Contracts/Context/Middlewares/Handle/HandleHandlerContract';
13
+ import { InterceptHandlerContract } from '../Contracts/Context/Middlewares/Intercept/InterceptHandlerContract';
14
+ declare module 'fastify' {
15
+ interface FastifyRequest {
16
+ data: Record<string, any>;
17
+ }
18
+ }
19
+ export declare class FastifyHandler {
20
+ static createOnSendHandler(handler: InterceptHandlerContract): (req: any, res: any, payload: any, done: any) => any;
21
+ static createDoneHandler(handler: HandleHandlerContract): (req: any, res: any, done: any) => any;
22
+ static createErrorHandler(handler: ErrorHandlerContract): (error: any, req: FastifyRequest, res: FastifyReply) => any;
23
+ static createRequestHandler(handler: HandlerContract): (req: FastifyRequest, res: FastifyReply) => Promise<any>;
24
+ }
@@ -0,0 +1,106 @@
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.FastifyHandler = void 0;
12
+ /* eslint-disable @typescript-eslint/no-empty-function */
13
+ const utils_1 = require("@secjs/utils");
14
+ const Request_1 = require("../Context/Request");
15
+ const Response_1 = require("../Context/Response");
16
+ class FastifyHandler {
17
+ static createOnSendHandler(handler) {
18
+ return (req, res, payload, done) => {
19
+ const request = new Request_1.Request(req);
20
+ const response = new Response_1.Response(res);
21
+ if (!req.data)
22
+ req.data = {};
23
+ if (!req.query)
24
+ req.query = {};
25
+ if (!req.params)
26
+ req.params = {};
27
+ let body = payload;
28
+ if (utils_1.Is.Json(payload)) {
29
+ body = JSON.parse(body);
30
+ }
31
+ return handler({
32
+ request,
33
+ response,
34
+ body,
35
+ params: req.params,
36
+ queries: req.query,
37
+ data: req.data,
38
+ next: (body, error = null) => {
39
+ if (utils_1.Is.Object(body))
40
+ body = JSON.stringify(body);
41
+ done(error, body);
42
+ },
43
+ });
44
+ };
45
+ }
46
+ static createDoneHandler(handler) {
47
+ return (req, res, done) => {
48
+ const request = new Request_1.Request(req);
49
+ const response = new Response_1.Response(res);
50
+ if (!req.data)
51
+ req.data = {};
52
+ if (!req.query)
53
+ req.query = {};
54
+ if (!req.params)
55
+ req.params = {};
56
+ return handler({
57
+ request,
58
+ response,
59
+ params: req.params,
60
+ queries: req.query,
61
+ data: req.data,
62
+ next: done,
63
+ });
64
+ };
65
+ }
66
+ static createErrorHandler(handler) {
67
+ return (error, req, res) => {
68
+ const request = new Request_1.Request(req);
69
+ const response = new Response_1.Response(res);
70
+ if (!req.data)
71
+ req.data = {};
72
+ if (!req.query)
73
+ req.query = {};
74
+ if (!req.params)
75
+ req.params = {};
76
+ return handler({
77
+ request,
78
+ response,
79
+ params: req.params,
80
+ queries: req.query,
81
+ data: req.data,
82
+ error,
83
+ });
84
+ };
85
+ }
86
+ static createRequestHandler(handler) {
87
+ return async (req, res) => {
88
+ const request = new Request_1.Request(req);
89
+ const response = new Response_1.Response(res);
90
+ if (!req.data)
91
+ req.data = {};
92
+ if (!req.query)
93
+ req.query = {};
94
+ if (!req.params)
95
+ req.params = {};
96
+ return handler({
97
+ request,
98
+ response,
99
+ params: req.params,
100
+ queries: req.query,
101
+ data: req.data,
102
+ });
103
+ };
104
+ }
105
+ }
106
+ exports.FastifyHandler = FastifyHandler;
@@ -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 { ErrorContextContract } from '../Contracts/Context/Error/ErrorContextContract';
10
+ export declare function defaultErrorHandler({ error, request, response, }: ErrorContextContract): void;
@@ -0,0 +1,30 @@
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.defaultErrorHandler = void 0;
12
+ const utils_1 = require("@secjs/utils");
13
+ function defaultErrorHandler({ error, request, response, }) {
14
+ const code = error.code || error.name;
15
+ const statusCode = error.statusCode || error.status || 500;
16
+ const body = {
17
+ code: utils_1.String.toSnakeCase(code).toUpperCase(),
18
+ path: request.baseUrl,
19
+ method: request.method,
20
+ status: statusCode <= 399 ? 'SUCCESS' : 'ERROR',
21
+ statusCode: statusCode,
22
+ error: {
23
+ name: error.name,
24
+ message: error.message,
25
+ stack: error.stack,
26
+ },
27
+ };
28
+ response.status(statusCode).send(body);
29
+ }
30
+ exports.defaultErrorHandler = defaultErrorHandler;
@@ -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 { MiddlewareContract } from '../Contracts/MiddlewareContract';
10
+ export declare function isMiddlewareContract(object: any): object is MiddlewareContract;
@@ -0,0 +1,15 @@
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.isMiddlewareContract = void 0;
12
+ function isMiddlewareContract(object) {
13
+ return 'handle' in object || 'intercept' in object || 'terminate' in object;
14
+ }
15
+ exports.isMiddlewareContract = isMiddlewareContract;
@@ -0,0 +1,9 @@
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
+ export declare function removeSlash(url: string | string[]): string | string[];