@kaito-http/core 1.3.4 → 2.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/dist/declarations/src/index.d.ts +1 -0
- package/dist/declarations/src/server.d.ts +99 -0
- package/dist/kaito-http-core.cjs.d.ts +1 -0
- package/dist/kaito-http-core.cjs.dev.js +232 -0
- package/dist/kaito-http-core.cjs.js +7 -0
- package/dist/kaito-http-core.cjs.prod.js +232 -0
- package/dist/kaito-http-core.esm.js +220 -0
- package/package.json +18 -36
- package/dist/index.cjs +0 -254
- package/dist/index.d.ts +0 -115
- package/dist/index.js +0 -254
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
import fastify from 'fastify';
|
|
2
|
+
|
|
3
|
+
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
|
|
4
|
+
try {
|
|
5
|
+
var info = gen[key](arg);
|
|
6
|
+
var value = info.value;
|
|
7
|
+
} catch (error) {
|
|
8
|
+
reject(error);
|
|
9
|
+
return;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
if (info.done) {
|
|
13
|
+
resolve(value);
|
|
14
|
+
} else {
|
|
15
|
+
Promise.resolve(value).then(_next, _throw);
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function _asyncToGenerator(fn) {
|
|
20
|
+
return function () {
|
|
21
|
+
var self = this,
|
|
22
|
+
args = arguments;
|
|
23
|
+
return new Promise(function (resolve, reject) {
|
|
24
|
+
var gen = fn.apply(self, args);
|
|
25
|
+
|
|
26
|
+
function _next(value) {
|
|
27
|
+
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function _throw(err) {
|
|
31
|
+
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
_next(undefined);
|
|
35
|
+
});
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function _defineProperty(obj, key, value) {
|
|
40
|
+
if (key in obj) {
|
|
41
|
+
Object.defineProperty(obj, key, {
|
|
42
|
+
value: value,
|
|
43
|
+
enumerable: true,
|
|
44
|
+
configurable: true,
|
|
45
|
+
writable: true
|
|
46
|
+
});
|
|
47
|
+
} else {
|
|
48
|
+
obj[key] = value;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
return obj;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function ownKeys(object, enumerableOnly) {
|
|
55
|
+
var keys = Object.keys(object);
|
|
56
|
+
|
|
57
|
+
if (Object.getOwnPropertySymbols) {
|
|
58
|
+
var symbols = Object.getOwnPropertySymbols(object);
|
|
59
|
+
|
|
60
|
+
if (enumerableOnly) {
|
|
61
|
+
symbols = symbols.filter(function (sym) {
|
|
62
|
+
return Object.getOwnPropertyDescriptor(object, sym).enumerable;
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
keys.push.apply(keys, symbols);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
return keys;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function _objectSpread2(target) {
|
|
73
|
+
for (var i = 1; i < arguments.length; i++) {
|
|
74
|
+
var source = arguments[i] != null ? arguments[i] : {};
|
|
75
|
+
|
|
76
|
+
if (i % 2) {
|
|
77
|
+
ownKeys(Object(source), true).forEach(function (key) {
|
|
78
|
+
_defineProperty(target, key, source[key]);
|
|
79
|
+
});
|
|
80
|
+
} else if (Object.getOwnPropertyDescriptors) {
|
|
81
|
+
Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
|
|
82
|
+
} else {
|
|
83
|
+
ownKeys(Object(source)).forEach(function (key) {
|
|
84
|
+
Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
return target;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
var Method;
|
|
93
|
+
|
|
94
|
+
(function (Method) {
|
|
95
|
+
Method["GET"] = "GET";
|
|
96
|
+
Method["POST"] = "POST";
|
|
97
|
+
Method["PATCH"] = "PATCH";
|
|
98
|
+
Method["DELETE"] = "DELETE";
|
|
99
|
+
})(Method || (Method = {}));
|
|
100
|
+
|
|
101
|
+
function createGetContext(getContext) {
|
|
102
|
+
return getContext;
|
|
103
|
+
}
|
|
104
|
+
class Router {
|
|
105
|
+
constructor(procs) {
|
|
106
|
+
_defineProperty(this, "create", method => (name, proc) => {
|
|
107
|
+
return new Router(_objectSpread2(_objectSpread2({}, this.procs), {}, {
|
|
108
|
+
[name]: _objectSpread2(_objectSpread2({}, proc), {}, {
|
|
109
|
+
method,
|
|
110
|
+
name
|
|
111
|
+
})
|
|
112
|
+
}));
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
_defineProperty(this, "merge", router => new Router(_objectSpread2(_objectSpread2({}, this.procs), router.getProcs())));
|
|
116
|
+
|
|
117
|
+
_defineProperty(this, "get", this.create(Method.GET));
|
|
118
|
+
|
|
119
|
+
_defineProperty(this, "post", this.create(Method.POST));
|
|
120
|
+
|
|
121
|
+
_defineProperty(this, "patch", this.create(Method.PATCH));
|
|
122
|
+
|
|
123
|
+
_defineProperty(this, "delete", this.create(Method.DELETE));
|
|
124
|
+
|
|
125
|
+
this.procs = procs;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
getProcs() {
|
|
129
|
+
return this.procs;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
}
|
|
133
|
+
class KaitoError extends Error {
|
|
134
|
+
constructor(code, message, cause) {
|
|
135
|
+
super(message);
|
|
136
|
+
this.code = code;
|
|
137
|
+
this.cause = cause;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
}
|
|
141
|
+
function createRouter() {
|
|
142
|
+
return new Router({});
|
|
143
|
+
}
|
|
144
|
+
function createServer(config) {
|
|
145
|
+
var tree = config.router.getProcs();
|
|
146
|
+
var app = fastify();
|
|
147
|
+
app.setErrorHandler( /*#__PURE__*/function () {
|
|
148
|
+
var _ref = _asyncToGenerator(function* (error, req, res) {
|
|
149
|
+
if (error instanceof KaitoError) {
|
|
150
|
+
yield res.status(error.code).send({
|
|
151
|
+
success: false,
|
|
152
|
+
data: null,
|
|
153
|
+
message: error.message
|
|
154
|
+
});
|
|
155
|
+
return;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
var {
|
|
159
|
+
code,
|
|
160
|
+
message
|
|
161
|
+
} = yield config.onError({
|
|
162
|
+
error,
|
|
163
|
+
req,
|
|
164
|
+
res
|
|
165
|
+
}).catch(() => ({
|
|
166
|
+
code: 500,
|
|
167
|
+
message: 'Something went wrong'
|
|
168
|
+
}));
|
|
169
|
+
yield res.status(code).send({
|
|
170
|
+
success: false,
|
|
171
|
+
data: null,
|
|
172
|
+
message
|
|
173
|
+
});
|
|
174
|
+
});
|
|
175
|
+
|
|
176
|
+
return function (_x, _x2, _x3) {
|
|
177
|
+
return _ref.apply(this, arguments);
|
|
178
|
+
};
|
|
179
|
+
}());
|
|
180
|
+
app.all('*', /*#__PURE__*/function () {
|
|
181
|
+
var _ref2 = _asyncToGenerator(function* (req, res) {
|
|
182
|
+
var _handler$input$parse, _handler$input;
|
|
183
|
+
|
|
184
|
+
var logMessage = "".concat(req.hostname, " ").concat(req.method, " ").concat(req.routerPath);
|
|
185
|
+
|
|
186
|
+
if (config.log === undefined) {
|
|
187
|
+
console.log(logMessage);
|
|
188
|
+
} else if (config.log) {
|
|
189
|
+
config.log(logMessage);
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
var url = new URL("".concat(req.protocol, "://").concat(req.hostname).concat(req.url));
|
|
193
|
+
var handler = tree[url.pathname];
|
|
194
|
+
|
|
195
|
+
if (!handler) {
|
|
196
|
+
throw new KaitoError(404, "Cannot ".concat(req.method, " this route."));
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
var context = yield config.getContext(req, res); // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
|
200
|
+
|
|
201
|
+
var input = (_handler$input$parse = (_handler$input = handler.input) === null || _handler$input === void 0 ? void 0 : _handler$input.parse(req.method === 'GET' ? req.query : req.body)) !== null && _handler$input$parse !== void 0 ? _handler$input$parse : null;
|
|
202
|
+
yield res.send({
|
|
203
|
+
success: true,
|
|
204
|
+
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
|
205
|
+
data: yield handler.run({
|
|
206
|
+
ctx: context,
|
|
207
|
+
input
|
|
208
|
+
}),
|
|
209
|
+
message: 'OK'
|
|
210
|
+
});
|
|
211
|
+
});
|
|
212
|
+
|
|
213
|
+
return function (_x4, _x5) {
|
|
214
|
+
return _ref2.apply(this, arguments);
|
|
215
|
+
};
|
|
216
|
+
}());
|
|
217
|
+
return app;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
export { KaitoError, Method, Router, createGetContext, createRouter, createServer };
|
package/package.json
CHANGED
|
@@ -1,39 +1,22 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kaito-http/core",
|
|
3
|
-
"version": "
|
|
4
|
-
"description": "
|
|
3
|
+
"version": "2.0.0",
|
|
4
|
+
"description": "Functional HTTP Framework for TypeScript",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
7
7
|
"url": "git+https://github.com/kaito-http/kaito.git"
|
|
8
8
|
},
|
|
9
|
-
"author": "Alistair Smith <
|
|
9
|
+
"author": "Alistair Smith <hi@alistair.sh>",
|
|
10
10
|
"license": "MIT",
|
|
11
|
-
"
|
|
12
|
-
"
|
|
13
|
-
"
|
|
14
|
-
"test": "uvu -r ts-node/register tests",
|
|
15
|
-
"prepublishOnly": "yarn test&&yarn build",
|
|
16
|
-
"bundle": "yarn test&&yarn build",
|
|
17
|
-
"build": "tsup src/index.ts --dts --format esm,cjs",
|
|
18
|
-
"lint": "eslint . --fix"
|
|
19
|
-
},
|
|
20
|
-
"main": "dist/index.cjs",
|
|
21
|
-
"module": "dist/index.js",
|
|
22
|
-
"types": "dist/index.d.ts",
|
|
11
|
+
"main": "dist/kaito-http-core.cjs.js",
|
|
12
|
+
"module": "dist/kaito-http-core.esm.js",
|
|
13
|
+
"types": "dist/kaito-http-core.cjs.d.ts",
|
|
23
14
|
"devDependencies": {
|
|
24
|
-
"@types/body-parser": "^1.19.
|
|
25
|
-
"@types/node": "^
|
|
26
|
-
"@types/node-fetch": "^2.
|
|
27
|
-
"
|
|
28
|
-
"
|
|
29
|
-
"eslint": "^7.25.0",
|
|
30
|
-
"lerna": "^4.0.0",
|
|
31
|
-
"node-fetch": "^2.6.1",
|
|
32
|
-
"ts-node": "^9.1.1",
|
|
33
|
-
"tslib": "^2.2.0",
|
|
34
|
-
"tsup": "^4.9.1",
|
|
35
|
-
"typescript": "^4.2.4",
|
|
36
|
-
"uvu": "^0.5.1"
|
|
15
|
+
"@types/body-parser": "^1.19.2",
|
|
16
|
+
"@types/node": "^17.0.24",
|
|
17
|
+
"@types/node-fetch": "^2.6.1",
|
|
18
|
+
"typescript": "4.6",
|
|
19
|
+
"zod": "^3.14.4"
|
|
37
20
|
},
|
|
38
21
|
"files": [
|
|
39
22
|
"package.json",
|
|
@@ -41,15 +24,14 @@
|
|
|
41
24
|
"dist"
|
|
42
25
|
],
|
|
43
26
|
"dependencies": {
|
|
44
|
-
"
|
|
45
|
-
"
|
|
46
|
-
"reflect-metadata": "^0.1.13",
|
|
47
|
-
"trouter": "^3.2.0",
|
|
48
|
-
"tslib": "^2.2.0",
|
|
49
|
-
"zod": "^1.11.13"
|
|
27
|
+
"colorette": "^2.0.16",
|
|
28
|
+
"fastify": "^3.28.0"
|
|
50
29
|
},
|
|
51
30
|
"bugs": {
|
|
52
31
|
"url": "https://github.com/kaito-http/kaito/issues"
|
|
53
32
|
},
|
|
54
|
-
"homepage": "https://github.com/kaito-http/kaito#readme"
|
|
55
|
-
|
|
33
|
+
"homepage": "https://github.com/kaito-http/kaito#readme",
|
|
34
|
+
"peerDependencies": {
|
|
35
|
+
"zod": "*"
|
|
36
|
+
}
|
|
37
|
+
}
|
package/dist/index.cjs
DELETED
|
@@ -1,254 +0,0 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports, "__esModule", {value: true});var __defProp = Object.defineProperty;
|
|
2
|
-
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
3
|
-
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
|
|
4
|
-
var __propIsEnum = Object.prototype.propertyIsEnumerable;
|
|
5
|
-
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, {enumerable: true, configurable: true, writable: true, value}) : obj[key] = value;
|
|
6
|
-
var __objSpread = (a, b) => {
|
|
7
|
-
for (var prop in b || (b = {}))
|
|
8
|
-
if (__hasOwnProp.call(b, prop))
|
|
9
|
-
__defNormalProp(a, prop, b[prop]);
|
|
10
|
-
if (__getOwnPropSymbols)
|
|
11
|
-
for (var prop of __getOwnPropSymbols(b)) {
|
|
12
|
-
if (__propIsEnum.call(b, prop))
|
|
13
|
-
__defNormalProp(a, prop, b[prop]);
|
|
14
|
-
}
|
|
15
|
-
return a;
|
|
16
|
-
};
|
|
17
|
-
|
|
18
|
-
// src/Kaito.ts
|
|
19
|
-
require('reflect-metadata');
|
|
20
|
-
|
|
21
|
-
// src/types.ts
|
|
22
|
-
var MetadataKeys;
|
|
23
|
-
(function(MetadataKeys2) {
|
|
24
|
-
MetadataKeys2["HTTP_METHOD"] = "kaito:http:method";
|
|
25
|
-
MetadataKeys2["SCHEMA"] = "kaito:route:schema";
|
|
26
|
-
MetadataKeys2["QUERY_SCHEMA"] = "kaito:route:schema:query";
|
|
27
|
-
MetadataKeys2["CONTROLLER_PATH"] = "kaito:controller:path";
|
|
28
|
-
MetadataKeys2["AVAILABLE_ROUTE_METHODS"] = "kaito:route:methods";
|
|
29
|
-
MetadataKeys2["ROUTE_PATH"] = "kaito:route:path";
|
|
30
|
-
})(MetadataKeys || (MetadataKeys = exports.MetadataKeys = {}));
|
|
31
|
-
|
|
32
|
-
// src/utils/url.ts
|
|
33
|
-
var FORWARD_SLASH_CHAR_CODE = 47;
|
|
34
|
-
function normalizePath(base, path) {
|
|
35
|
-
return lead(base) + lead(path);
|
|
36
|
-
}
|
|
37
|
-
function lead(path) {
|
|
38
|
-
return path.charCodeAt(0) === FORWARD_SLASH_CHAR_CODE ? path : "/" + path;
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
// src/utils/metadata.ts
|
|
42
|
-
function readControllerMetadata(controller) {
|
|
43
|
-
const base = Reflect.getMetadata(MetadataKeys.CONTROLLER_PATH, controller.constructor);
|
|
44
|
-
const classMethods = Reflect.getMetadata(MetadataKeys.AVAILABLE_ROUTE_METHODS, controller) || [];
|
|
45
|
-
return {
|
|
46
|
-
base,
|
|
47
|
-
routes: classMethods.map((methodKey) => {
|
|
48
|
-
const method2 = Reflect.getMetadata(MetadataKeys.HTTP_METHOD, controller, methodKey);
|
|
49
|
-
const schema = Reflect.getMetadata(MetadataKeys.SCHEMA, controller, methodKey);
|
|
50
|
-
const querySchema = Reflect.getMetadata(MetadataKeys.QUERY_SCHEMA, controller, methodKey);
|
|
51
|
-
const routePath = Reflect.getMetadata(MetadataKeys.ROUTE_PATH, controller, methodKey);
|
|
52
|
-
const path = normalizePath(base, routePath);
|
|
53
|
-
return {
|
|
54
|
-
path,
|
|
55
|
-
schema,
|
|
56
|
-
method: method2,
|
|
57
|
-
routePath,
|
|
58
|
-
querySchema,
|
|
59
|
-
methodName: methodKey
|
|
60
|
-
};
|
|
61
|
-
})
|
|
62
|
-
};
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
// src/Kaito.ts
|
|
66
|
-
var _app = require('@tinyhttp/app');
|
|
67
|
-
|
|
68
|
-
// src/exceptions.ts
|
|
69
|
-
var HttpException = class extends Error {
|
|
70
|
-
constructor(code, message) {
|
|
71
|
-
super(typeof message === "string" ? message : message.join(", "));
|
|
72
|
-
this.code = code;
|
|
73
|
-
}
|
|
74
|
-
};
|
|
75
|
-
var NotFoundException = class extends HttpException {
|
|
76
|
-
constructor() {
|
|
77
|
-
super(404, "That resource was not found");
|
|
78
|
-
}
|
|
79
|
-
};
|
|
80
|
-
|
|
81
|
-
// src/utils/errors.ts
|
|
82
|
-
var _zod = require('zod');
|
|
83
|
-
function defaultErrorHandler(err, ctx) {
|
|
84
|
-
ctx.res.setHeader("Content-Type", "application/json");
|
|
85
|
-
if (err instanceof HttpException) {
|
|
86
|
-
const body = JSON.stringify({
|
|
87
|
-
message: err.message,
|
|
88
|
-
code: err.code,
|
|
89
|
-
error: "HttpException"
|
|
90
|
-
});
|
|
91
|
-
ctx.res.writeHead(err.code, {
|
|
92
|
-
"Content-Type": "application/json"
|
|
93
|
-
});
|
|
94
|
-
ctx.res.end(body);
|
|
95
|
-
} else if (err instanceof _zod.ZodError) {
|
|
96
|
-
const body = JSON.stringify({
|
|
97
|
-
message: err.errors.map((error) => error.message).join(", "),
|
|
98
|
-
code: 422,
|
|
99
|
-
error: "ZodError"
|
|
100
|
-
});
|
|
101
|
-
ctx.res.writeHead(422, {
|
|
102
|
-
"Content-Type": "application/json"
|
|
103
|
-
});
|
|
104
|
-
ctx.res.end(body);
|
|
105
|
-
} else {
|
|
106
|
-
ctx.res.statusCode = 500;
|
|
107
|
-
const body = JSON.stringify({
|
|
108
|
-
message: "Something went wrong on our side",
|
|
109
|
-
error: err.constructor.name,
|
|
110
|
-
code: 500
|
|
111
|
-
});
|
|
112
|
-
ctx.res.end(body);
|
|
113
|
-
}
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
// src/Kaito.ts
|
|
117
|
-
var _colorette = require('colorette');
|
|
118
|
-
var Kaito = class extends _app.App {
|
|
119
|
-
constructor(options) {
|
|
120
|
-
super({
|
|
121
|
-
settings: {xPoweredBy: "kaito.cloud"}
|
|
122
|
-
});
|
|
123
|
-
this.server = null;
|
|
124
|
-
this.addControllers(options.controllers);
|
|
125
|
-
this.kaitoOptions = options;
|
|
126
|
-
this.use = this.use.bind(this);
|
|
127
|
-
}
|
|
128
|
-
async parseBody(req) {
|
|
129
|
-
var _a;
|
|
130
|
-
const get = async () => {
|
|
131
|
-
let chunks = "";
|
|
132
|
-
for await (const chunk of req)
|
|
133
|
-
chunks += chunk;
|
|
134
|
-
return chunks;
|
|
135
|
-
};
|
|
136
|
-
switch ((_a = req.headers["content-type"]) == null ? void 0 : _a.toLowerCase()) {
|
|
137
|
-
case "application/json": {
|
|
138
|
-
return JSON.parse(await get());
|
|
139
|
-
}
|
|
140
|
-
default:
|
|
141
|
-
return null;
|
|
142
|
-
}
|
|
143
|
-
}
|
|
144
|
-
listen(port) {
|
|
145
|
-
const parsed = (typeof port === "string" ? parseInt(port) : port) || process.env.PORT && parseInt(process.env.PORT) || void 0;
|
|
146
|
-
this.server = super.listen(parsed, () => this.log(`starting on ${parsed}`));
|
|
147
|
-
return this.server;
|
|
148
|
-
}
|
|
149
|
-
log(...args) {
|
|
150
|
-
if (this.kaitoOptions.logging) {
|
|
151
|
-
console.log(_colorette.blue.call(void 0, _colorette.bold.call(void 0, "[kaito/core]")), ...args);
|
|
152
|
-
}
|
|
153
|
-
}
|
|
154
|
-
close(cb) {
|
|
155
|
-
this.log("shutting down");
|
|
156
|
-
if (!this.server) {
|
|
157
|
-
this.log("trying to close a server that was never started");
|
|
158
|
-
cb == null ? void 0 : cb(new Error("Could not close a server that was never started"));
|
|
159
|
-
return;
|
|
160
|
-
}
|
|
161
|
-
try {
|
|
162
|
-
this.server.removeAllListeners();
|
|
163
|
-
this.server.close(cb);
|
|
164
|
-
this.server = null;
|
|
165
|
-
cb == null ? void 0 : cb();
|
|
166
|
-
} catch (e) {
|
|
167
|
-
cb == null ? void 0 : cb(e);
|
|
168
|
-
}
|
|
169
|
-
}
|
|
170
|
-
addControllers(controllers) {
|
|
171
|
-
for (const controller of controllers) {
|
|
172
|
-
const {routes} = readControllerMetadata(controller);
|
|
173
|
-
for (const route of routes) {
|
|
174
|
-
const {method: method2, schema, path, methodName, querySchema} = route;
|
|
175
|
-
if (method2 === "get" && schema) {
|
|
176
|
-
throw new Error(`Method ${methodName} (${path}) cannot have a schema as it is a GET only route.`);
|
|
177
|
-
}
|
|
178
|
-
const handler = controller[methodName];
|
|
179
|
-
this[method2](path, async (req, res) => {
|
|
180
|
-
var _a, _b;
|
|
181
|
-
const ip = req.headers["x-forwarded-for"] || req.connection.remoteAddress || req.ip;
|
|
182
|
-
const ctx = {
|
|
183
|
-
body: await this.parseBody(req),
|
|
184
|
-
params: req.params,
|
|
185
|
-
path: req.path,
|
|
186
|
-
query: req.query,
|
|
187
|
-
url: req.url,
|
|
188
|
-
req,
|
|
189
|
-
res,
|
|
190
|
-
ip
|
|
191
|
-
};
|
|
192
|
-
try {
|
|
193
|
-
if (querySchema) {
|
|
194
|
-
ctx.query = await querySchema.parseAsync(ctx.query);
|
|
195
|
-
}
|
|
196
|
-
if (schema) {
|
|
197
|
-
ctx.body = await schema.parseAsync(ctx.body);
|
|
198
|
-
}
|
|
199
|
-
const result = await handler(ctx);
|
|
200
|
-
res.writeHead((_a = result == null ? void 0 : result.status) != null ? _a : 200, __objSpread({"Content-Type": "application/json"}, result == null ? void 0 : result.headers)).end(JSON.stringify((_b = result == null ? void 0 : result.body) != null ? _b : "OK"));
|
|
201
|
-
} catch (e) {
|
|
202
|
-
if (this.kaitoOptions.onError) {
|
|
203
|
-
this.kaitoOptions.onError(e, ctx);
|
|
204
|
-
} else {
|
|
205
|
-
defaultErrorHandler(e, ctx);
|
|
206
|
-
}
|
|
207
|
-
}
|
|
208
|
-
});
|
|
209
|
-
}
|
|
210
|
-
}
|
|
211
|
-
}
|
|
212
|
-
};
|
|
213
|
-
|
|
214
|
-
// src/decorators.ts
|
|
215
|
-
var method = (method2) => (path = "/") => (target, property) => {
|
|
216
|
-
Reflect.defineMetadata(MetadataKeys.HTTP_METHOD, method2, target, property);
|
|
217
|
-
Reflect.defineMetadata(MetadataKeys.ROUTE_PATH, path, target, property);
|
|
218
|
-
const existing = Reflect.getMetadata(MetadataKeys.AVAILABLE_ROUTE_METHODS, target) || [];
|
|
219
|
-
Reflect.defineMetadata(MetadataKeys.AVAILABLE_ROUTE_METHODS, [...existing, property], target);
|
|
220
|
-
};
|
|
221
|
-
var Schema = (schema) => (target, property) => {
|
|
222
|
-
Reflect.defineMetadata(MetadataKeys.SCHEMA, schema, target, property);
|
|
223
|
-
};
|
|
224
|
-
var QuerySchema = (schema) => (target, property) => {
|
|
225
|
-
Reflect.defineMetadata(MetadataKeys.QUERY_SCHEMA, schema, target, property);
|
|
226
|
-
};
|
|
227
|
-
var Controller = (path = "/") => (target) => {
|
|
228
|
-
if (!path.startsWith("/")) {
|
|
229
|
-
throw new Error(`Path must start with / for ${target}`);
|
|
230
|
-
}
|
|
231
|
-
Reflect.defineMetadata(MetadataKeys.CONTROLLER_PATH, path, target);
|
|
232
|
-
};
|
|
233
|
-
var Get = method("get");
|
|
234
|
-
var Post = method("post");
|
|
235
|
-
var Patch = method("patch");
|
|
236
|
-
var Put = method("put");
|
|
237
|
-
var Delete = method("delete");
|
|
238
|
-
var Method = (m) => method(m);
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
exports.Controller = Controller; exports.Delete = Delete; exports.Get = Get; exports.HttpException = HttpException; exports.Kaito = Kaito; exports.MetadataKeys = MetadataKeys; exports.Method = Method; exports.NotFoundException = NotFoundException; exports.Patch = Patch; exports.Post = Post; exports.Put = Put; exports.QuerySchema = QuerySchema; exports.Schema = Schema; exports.method = method;
|
package/dist/index.d.ts
DELETED
|
@@ -1,115 +0,0 @@
|
|
|
1
|
-
import { IncomingMessage, ServerResponse, OutgoingHttpHeaders, Server } from 'http';
|
|
2
|
-
import * as querystring from 'querystring';
|
|
3
|
-
import * as zod from 'zod';
|
|
4
|
-
import { infer, ZodSchema } from 'zod';
|
|
5
|
-
import { App } from '@tinyhttp/app';
|
|
6
|
-
import { IncomingMessage as IncomingMessage$1 } from 'node:http';
|
|
7
|
-
|
|
8
|
-
declare type HTTPMethod = "get" | "post" | "put" | "delete" | "patch";
|
|
9
|
-
interface ServerConstructorOptions {
|
|
10
|
-
controllers: object[];
|
|
11
|
-
logging?: boolean;
|
|
12
|
-
/**
|
|
13
|
-
* An error handler that
|
|
14
|
-
* @param error The error that was thrown
|
|
15
|
-
* @param ctx The context for this request
|
|
16
|
-
*/
|
|
17
|
-
onError?(error: Error, ctx: KaitoContext): unknown;
|
|
18
|
-
}
|
|
19
|
-
declare const enum MetadataKeys {
|
|
20
|
-
"HTTP_METHOD" = "kaito:http:method",
|
|
21
|
-
"SCHEMA" = "kaito:route:schema",
|
|
22
|
-
"QUERY_SCHEMA" = "kaito:route:schema:query",
|
|
23
|
-
"CONTROLLER_PATH" = "kaito:controller:path",
|
|
24
|
-
"AVAILABLE_ROUTE_METHODS" = "kaito:route:methods",
|
|
25
|
-
"ROUTE_PATH" = "kaito:route:path"
|
|
26
|
-
}
|
|
27
|
-
interface KaitoContext<Body = unknown, Query = querystring.ParsedUrlQuery, Params = Record<string, string | string[]>> {
|
|
28
|
-
req: IncomingMessage;
|
|
29
|
-
res: ServerResponse;
|
|
30
|
-
url: string;
|
|
31
|
-
path: string;
|
|
32
|
-
query: Query;
|
|
33
|
-
params: Params;
|
|
34
|
-
body: Body;
|
|
35
|
-
ip: string;
|
|
36
|
-
}
|
|
37
|
-
declare type KaitoDefaultContextConfig<B = unknown, Q = querystring.ParsedUrlQuery, P = Record<string, string | string[]>> = {
|
|
38
|
-
body?: B;
|
|
39
|
-
query?: Q;
|
|
40
|
-
params?: P;
|
|
41
|
-
};
|
|
42
|
-
declare type TypedSchema = {
|
|
43
|
-
_type: any;
|
|
44
|
-
};
|
|
45
|
-
/**
|
|
46
|
-
* Shorter Alias for KaitoRequest
|
|
47
|
-
*
|
|
48
|
-
* https://github.com/microsoft/TypeScript/issues/29188
|
|
49
|
-
*/
|
|
50
|
-
declare type KTX<Config extends KaitoDefaultContextConfig | TypedSchema> = Config extends TypedSchema ? KaitoContext<infer<Config>> : Config extends KaitoDefaultContextConfig ? KaitoContext<Config["body"], Config["query"], Config["params"]> : never;
|
|
51
|
-
declare type KaitoReturnType<Body> = {
|
|
52
|
-
body: NonNullable<Body>;
|
|
53
|
-
status?: number;
|
|
54
|
-
headers?: OutgoingHttpHeaders;
|
|
55
|
-
};
|
|
56
|
-
declare type KRTInner<B> = KaitoReturnType<B> | undefined;
|
|
57
|
-
/**
|
|
58
|
-
* The return type for a kaito request handler
|
|
59
|
-
*/
|
|
60
|
-
declare type KRT<B> = Promise<KRTInner<B>>;
|
|
61
|
-
declare type RequestHandler = <Body>(ctx: KaitoContext) => KRT<Body>;
|
|
62
|
-
|
|
63
|
-
declare class Kaito extends App {
|
|
64
|
-
readonly kaitoOptions: ServerConstructorOptions;
|
|
65
|
-
readonly server: Server | null;
|
|
66
|
-
constructor(options: ServerConstructorOptions);
|
|
67
|
-
parseBody<T>(req: IncomingMessage$1): Promise<T | null>;
|
|
68
|
-
/**
|
|
69
|
-
* Listen on the specified port. If no port is specified, it will try to use the environment variable PORT
|
|
70
|
-
* @param port
|
|
71
|
-
*/
|
|
72
|
-
listen(port?: string | number): Server;
|
|
73
|
-
/**
|
|
74
|
-
* Prints something to the terminal if logging is enabled
|
|
75
|
-
* @param args Anything to be logged
|
|
76
|
-
*/
|
|
77
|
-
protected log(...args: unknown[]): void;
|
|
78
|
-
/**
|
|
79
|
-
* Close and stop the server (useful for tests)
|
|
80
|
-
* @param cb Callback
|
|
81
|
-
* @returns
|
|
82
|
-
*/
|
|
83
|
-
close(cb?: (err?: Error) => unknown): void;
|
|
84
|
-
/**
|
|
85
|
-
* Add controllers and mount them to tinyhttp
|
|
86
|
-
* @param controllers An array of controllers
|
|
87
|
-
*/
|
|
88
|
-
private addControllers;
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
declare const method: (method: HTTPMethod) => (path?: `/${string}`) => MethodDecorator;
|
|
92
|
-
declare const Schema: <T>(schema: ZodSchema<T, zod.ZodTypeDef>) => MethodDecorator;
|
|
93
|
-
declare const QuerySchema: <T extends Record<string, string | string[]>>(schema: ZodSchema<T, zod.ZodTypeDef>) => MethodDecorator;
|
|
94
|
-
declare const Controller: (path?: `/${string}`) => ClassDecorator;
|
|
95
|
-
declare const Get: (path?: `/${string}`) => MethodDecorator;
|
|
96
|
-
declare const Post: (path?: `/${string}`) => MethodDecorator;
|
|
97
|
-
declare const Patch: (path?: `/${string}`) => MethodDecorator;
|
|
98
|
-
declare const Put: (path?: `/${string}`) => MethodDecorator;
|
|
99
|
-
declare const Delete: (path?: `/${string}`) => MethodDecorator;
|
|
100
|
-
declare const Method: (m: HTTPMethod) => (path?: `/${string}`) => MethodDecorator;
|
|
101
|
-
|
|
102
|
-
declare class HttpException extends Error {
|
|
103
|
-
readonly code: number;
|
|
104
|
-
/**
|
|
105
|
-
* Construct an HTTP Exception
|
|
106
|
-
* @param code
|
|
107
|
-
* @param message Can be multiple strings in an array, or a single message
|
|
108
|
-
*/
|
|
109
|
-
constructor(code: number, message: string | string[]);
|
|
110
|
-
}
|
|
111
|
-
declare class NotFoundException extends HttpException {
|
|
112
|
-
constructor();
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
export { Controller, Delete, Get, HTTPMethod, HttpException, KRT, KRTInner, KTX, Kaito, KaitoContext, KaitoReturnType, MetadataKeys, Method, NotFoundException, Patch, Post, Put, QuerySchema, RequestHandler, Schema, ServerConstructorOptions, method };
|