@kaito-http/core 2.2.5 → 2.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.
@@ -1,42 +1,21 @@
1
- import http from 'http';
1
+ import * as http from 'http';
2
+ import fmw from 'find-my-way';
2
3
  import { TLSSocket } from 'tls';
3
4
  import getRawBody from 'raw-body';
4
5
 
5
- function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
6
- try {
7
- var info = gen[key](arg);
8
- var value = info.value;
9
- } catch (error) {
10
- reject(error);
11
- return;
12
- }
13
-
14
- if (info.done) {
15
- resolve(value);
16
- } else {
17
- Promise.resolve(value).then(_next, _throw);
18
- }
19
- }
20
-
21
- function _asyncToGenerator(fn) {
22
- return function () {
23
- var self = this,
24
- args = arguments;
25
- return new Promise(function (resolve, reject) {
26
- var gen = fn.apply(self, args);
27
-
28
- function _next(value) {
29
- asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
30
- }
31
-
32
- function _throw(err) {
33
- asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
34
- }
35
-
36
- _next(undefined);
37
- });
6
+ function createFMWServer(config) {
7
+ var fmw = config.router.toFindMyWay(config);
8
+ var server = http.createServer((req, res) => {
9
+ fmw.lookup(req, res);
10
+ });
11
+ return {
12
+ server,
13
+ fmw
38
14
  };
39
15
  }
16
+ function createServer(config) {
17
+ return createFMWServer(config).server;
18
+ }
40
19
 
41
20
  function _defineProperty(obj, key, value) {
42
21
  if (key in obj) {
@@ -91,6 +70,42 @@ function _objectSpread2(target) {
91
70
  return target;
92
71
  }
93
72
 
73
+ function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
74
+ try {
75
+ var info = gen[key](arg);
76
+ var value = info.value;
77
+ } catch (error) {
78
+ reject(error);
79
+ return;
80
+ }
81
+
82
+ if (info.done) {
83
+ resolve(value);
84
+ } else {
85
+ Promise.resolve(value).then(_next, _throw);
86
+ }
87
+ }
88
+
89
+ function _asyncToGenerator(fn) {
90
+ return function () {
91
+ var self = this,
92
+ args = arguments;
93
+ return new Promise(function (resolve, reject) {
94
+ var gen = fn.apply(self, args);
95
+
96
+ function _next(value) {
97
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
98
+ }
99
+
100
+ function _throw(err) {
101
+ asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
102
+ }
103
+
104
+ _next(undefined);
105
+ });
106
+ };
107
+ }
108
+
94
109
  class WrappedError extends Error {
95
110
  static maybe(maybeError) {
96
111
  if (maybeError instanceof Error) {
@@ -109,8 +124,18 @@ class WrappedError extends Error {
109
124
  this.data = data;
110
125
  }
111
126
 
127
+ }
128
+ class KaitoError extends Error {
129
+ constructor(status, message) {
130
+ super(message);
131
+ this.status = status;
132
+ }
133
+
112
134
  }
113
135
 
136
+ function createGetContext(callback) {
137
+ return callback;
138
+ }
114
139
  function getLastEntryInMultiHeaderValue(headerValue) {
115
140
  var normalized = Array.isArray(headerValue) ? headerValue.join(',') : headerValue;
116
141
  var lastIndex = normalized.lastIndexOf(',');
@@ -128,8 +153,7 @@ function normalizePath(path) {
128
153
  }
129
154
 
130
155
  return result;
131
- } // Type for import('http').METHODS
132
-
156
+ }
133
157
  function getInput(_x) {
134
158
  return _getInput.apply(this, arguments);
135
159
  }
@@ -165,6 +189,8 @@ function _getInput() {
165
189
 
166
190
  class KaitoRequest {
167
191
  constructor(raw) {
192
+ _defineProperty(this, "_url", null);
193
+
168
194
  this.raw = raw;
169
195
  }
170
196
 
@@ -175,7 +201,12 @@ class KaitoRequest {
175
201
  }
176
202
 
177
203
  get url() {
178
- return new URL(this.fullURL);
204
+ if (this._url) {
205
+ return this._url;
206
+ }
207
+
208
+ this._url = new URL(this.fullURL);
209
+ return this._url;
179
210
  }
180
211
 
181
212
  get method() {
@@ -231,142 +262,34 @@ class KaitoResponse {
231
262
 
232
263
  }
233
264
 
234
- function createGetContext(getContext) {
235
- return getContext;
236
- }
237
265
  class Router {
238
- static patternize(path) {
239
- var normalized = normalizePath(path);
240
- return new RegExp("^".concat(normalized, "/?$"), 'i');
241
- }
242
-
243
- constructor(procs) {
244
- _defineProperty(this, "create", method => (path, proc) => {
245
- var pattern = Router.patternize(path);
246
-
247
- var merged = _objectSpread2(_objectSpread2({}, this.procs), {}, {
248
- [path]: _objectSpread2(_objectSpread2({}, proc), {}, {
249
- method,
250
- path,
251
- pattern
252
- })
253
- });
254
-
255
- return new Router(merged);
256
- });
257
-
258
- _defineProperty(this, "merge", (_prefix, router) => {
259
- var prefix = normalizePath(_prefix);
260
- var newProcs = Object.entries(router.getProcs()).reduce((all, entry) => {
261
- var [path, proc] = entry;
262
- var newPath = "".concat(prefix).concat(normalizePath(path));
263
- return _objectSpread2(_objectSpread2({}, all), {}, {
264
- ["".concat(prefix).concat(path)]: _objectSpread2(_objectSpread2({}, proc), {}, {
265
- path: newPath,
266
- pattern: Router.patternize(newPath)
267
- })
268
- });
269
- }, {});
270
-
271
- var mergedProcs = _objectSpread2(_objectSpread2({}, this.procs), newProcs);
272
-
273
- return new Router(mergedProcs);
274
- });
275
-
276
- _defineProperty(this, "get", this.create('GET'));
277
-
278
- _defineProperty(this, "post", this.create('POST'));
279
-
280
- _defineProperty(this, "put", this.create('PUT'));
281
-
282
- _defineProperty(this, "patch", this.create('PATCH'));
283
-
284
- _defineProperty(this, "delete", this.create('DELETE'));
285
-
286
- _defineProperty(this, "head", this.create('HEAD'));
287
-
288
- _defineProperty(this, "options", this.create('OPTIONS'));
289
-
290
- _defineProperty(this, "connect", this.create('CONNECT'));
291
-
292
- _defineProperty(this, "trace", this.create('TRACE'));
293
-
294
- _defineProperty(this, "acl", this.create('ACL'));
295
-
296
- _defineProperty(this, "bind", this.create('BIND'));
297
-
298
- this.procs = procs;
299
- this._procsArray = Object.values(procs);
300
- }
301
-
302
- getProcs() {
303
- return this.procs;
266
+ static create() {
267
+ return new Router({});
304
268
  }
305
269
 
306
- find(method, url) {
307
- for (var proc of this._procsArray) {
308
- if (proc.method !== method) {
309
- continue;
310
- }
311
-
312
- if (proc.pattern.test(url)) {
313
- return proc;
314
- }
315
- }
316
-
317
- return null;
318
- }
319
-
320
- }
321
- class KaitoError extends Error {
322
- constructor(status, message, cause) {
323
- super(message);
324
- this.status = status;
325
- this.cause = cause;
326
- }
327
-
328
- }
329
- function createRouter() {
330
- return new Router({});
331
- }
332
- function createServer(config) {
333
- var log = message => {
334
- if (config.log === undefined) {
335
- console.log(message);
336
- } else if (config.log) {
337
- config.log(message);
338
- }
339
- };
340
-
341
- return http.createServer( /*#__PURE__*/function () {
342
- var _ref = _asyncToGenerator(function* (incomingMessage, serverResponse) {
343
- var start = Date.now();
344
- var req = new KaitoRequest(incomingMessage);
345
- var res = new KaitoResponse(serverResponse);
346
-
270
+ static handle(server, options) {
271
+ return _asyncToGenerator(function* () {
347
272
  try {
348
- var _handler$input, _yield$getInput;
349
-
350
- var handler = config.router.find(req.method, req.url.pathname);
273
+ var _options$route$input$, _options$route$input;
351
274
 
352
- if (!handler) {
353
- throw new KaitoError(404, "Cannot ".concat(req.method, " this route."));
354
- }
355
-
356
- var input = (_handler$input = handler.input) === null || _handler$input === void 0 ? void 0 : _handler$input.parse((_yield$getInput = yield getInput(req)) !== null && _yield$getInput !== void 0 ? _yield$getInput : undefined);
357
- var context = yield config.getContext(req, res);
358
- var data = yield handler.run({
275
+ var context = yield server.getContext(options.req, options.res);
276
+ var body = yield getInput(options.req);
277
+ var input = (_options$route$input$ = (_options$route$input = options.route.input) === null || _options$route$input === void 0 ? void 0 : _options$route$input.parse(body)) !== null && _options$route$input$ !== void 0 ? _options$route$input$ : undefined;
278
+ var result = yield options.route.run({
359
279
  ctx: context,
360
- input
280
+ input,
281
+ params: options.params
361
282
  });
362
- res.json({
283
+ options.res.status(200).json({
363
284
  success: true,
364
- data,
285
+ data: result,
365
286
  message: 'OK'
366
287
  });
367
- } catch (error) {
288
+ } catch (e) {
289
+ var error = WrappedError.maybe(e);
290
+
368
291
  if (error instanceof KaitoError) {
369
- res.status(error.status).json({
292
+ options.res.status(error.status).json({
370
293
  success: false,
371
294
  data: null,
372
295
  message: error.message
@@ -375,31 +298,108 @@ function createServer(config) {
375
298
  }
376
299
 
377
300
  var {
378
- status: _status,
379
- message: _message
380
- } = yield config.onError({
381
- error: WrappedError.maybe(error),
382
- req,
383
- res
301
+ status,
302
+ message
303
+ } = yield server.onError({
304
+ error,
305
+ req: options.req,
306
+ res: options.res
384
307
  }).catch(() => ({
385
308
  status: 500,
386
- message: 'Something went wrong'
309
+ message: 'Internal Server Error'
387
310
  }));
388
- res.status(_status).json({
311
+ options.res.status(status).json({
389
312
  success: false,
390
313
  data: null,
391
- message: _message
314
+ message
392
315
  });
393
- } finally {
394
- var finish = Date.now();
395
- log("".concat(req.method, " ").concat(req.fullURL, " ").concat(res.raw.statusCode, " ").concat(finish - start, "ms"));
396
316
  }
397
- });
317
+ })();
318
+ }
319
+
320
+ constructor(routes) {
321
+ _defineProperty(this, "get", this.make('GET'));
322
+
323
+ _defineProperty(this, "post", this.make('POST'));
324
+
325
+ _defineProperty(this, "head", this.make('HEAD'));
326
+
327
+ _defineProperty(this, "put", this.make('PUT'));
328
+
329
+ _defineProperty(this, "patch", this.make('PATCH'));
330
+
331
+ this.routes = routes;
332
+ }
333
+
334
+ merge(prefix, router) {
335
+ var newRoutes = Object.fromEntries(Object.entries(router.routes).map(_ref => {
336
+ var [k, v] = _ref;
337
+ return ["".concat(prefix).concat(k), v];
338
+ }));
339
+ return new Router(_objectSpread2(_objectSpread2({}, this.routes), newRoutes));
340
+ }
341
+
342
+ toFindMyWay(server) {
343
+ var _this = this;
398
344
 
399
- return function (_x, _x2) {
400
- return _ref.apply(this, arguments);
345
+ var instance = fmw({
346
+ defaultRoute(req, serverResponse) {
347
+ var _req$url;
348
+
349
+ var res = new KaitoResponse(serverResponse);
350
+ res.status(404).json({
351
+ success: false,
352
+ data: null,
353
+ message: "Cannot ".concat(req.method, " ").concat((_req$url = req.url) !== null && _req$url !== void 0 ? _req$url : '/')
354
+ });
355
+ }
356
+
357
+ }); // eslint-disable-next-line guard-for-in
358
+
359
+ var _loop = function _loop(path) {
360
+ var route = _this.routes[path];
361
+ instance.on(route.method, path, /*#__PURE__*/function () {
362
+ var _ref2 = _asyncToGenerator(function* (incomingMessage, serverResponse, params) {
363
+ var req = new KaitoRequest(incomingMessage);
364
+ var res = new KaitoResponse(serverResponse);
365
+ yield Router.handle(server, {
366
+ route,
367
+ params,
368
+ req,
369
+ res
370
+ });
371
+ });
372
+
373
+ return function (_x, _x2, _x3) {
374
+ return _ref2.apply(this, arguments);
375
+ };
376
+ }());
377
+ };
378
+
379
+ for (var path in this.routes) {
380
+ _loop(path);
381
+ }
382
+
383
+ return instance;
384
+ }
385
+
386
+ make(method) {
387
+ return (path, route) => {
388
+ var mergedRoute = _objectSpread2(_objectSpread2({}, route), {}, {
389
+ method
390
+ });
391
+
392
+ return new Router(_objectSpread2(_objectSpread2({}, this.routes), {}, {
393
+ [path]: mergedRoute
394
+ }));
401
395
  };
402
- }());
396
+ }
397
+
403
398
  }
399
+ /**
400
+ * @deprecated Please use Router#create instead
401
+ */
402
+
403
+ var createRouter = Router.create;
404
404
 
405
- export { KaitoError, Router, createGetContext, createRouter, createServer };
405
+ export { KaitoError, KaitoRequest, KaitoResponse, Router, WrappedError, createFMWServer, createGetContext, createRouter, createServer, getInput, getLastEntryInMultiHeaderValue, normalizePath };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kaito-http/core",
3
- "version": "2.2.5",
3
+ "version": "2.3.0",
4
4
  "description": "Functional HTTP Framework for TypeScript",
5
5
  "repository": "https://github.com/kaito-http/kaito",
6
6
  "author": "Alistair Smith <hi@alistair.sh>",
@@ -32,6 +32,7 @@
32
32
  "framework"
33
33
  ],
34
34
  "dependencies": {
35
+ "find-my-way": "^5.5.0",
35
36
  "raw-body": "^2.5.1"
36
37
  }
37
38
  }