@kaito-http/core 2.2.7 → 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
  }
@@ -238,142 +262,34 @@ class KaitoResponse {
238
262
 
239
263
  }
240
264
 
241
- function createGetContext(getContext) {
242
- return getContext;
243
- }
244
265
  class Router {
245
- static patternize(path) {
246
- var normalized = normalizePath(path);
247
- return new RegExp("^".concat(normalized, "/?$"), 'i');
266
+ static create() {
267
+ return new Router({});
248
268
  }
249
269
 
250
- constructor(procs) {
251
- _defineProperty(this, "create", method => (path, proc) => {
252
- var pattern = Router.patternize(path);
253
-
254
- var merged = _objectSpread2(_objectSpread2({}, this.procs), {}, {
255
- [path]: _objectSpread2(_objectSpread2({}, proc), {}, {
256
- method,
257
- path,
258
- pattern
259
- })
260
- });
261
-
262
- return new Router(merged);
263
- });
264
-
265
- _defineProperty(this, "merge", (prefix, router) => {
266
- var newProcs = Object.entries(router.getProcs()).reduce((all, entry) => {
267
- var [path, proc] = entry;
268
- var newPath = "".concat(prefix).concat(path);
269
- return _objectSpread2(_objectSpread2({}, all), {}, {
270
- ["".concat(prefix).concat(path)]: _objectSpread2(_objectSpread2({}, proc), {}, {
271
- path: newPath,
272
- pattern: Router.patternize(newPath)
273
- })
274
- });
275
- }, {});
276
-
277
- var mergedProcs = _objectSpread2(_objectSpread2({}, this.procs), newProcs);
278
-
279
- return new Router(mergedProcs);
280
- });
281
-
282
- _defineProperty(this, "get", this.create('GET'));
283
-
284
- _defineProperty(this, "post", this.create('POST'));
285
-
286
- _defineProperty(this, "put", this.create('PUT'));
287
-
288
- _defineProperty(this, "patch", this.create('PATCH'));
289
-
290
- _defineProperty(this, "delete", this.create('DELETE'));
291
-
292
- _defineProperty(this, "head", this.create('HEAD'));
293
-
294
- _defineProperty(this, "options", this.create('OPTIONS'));
295
-
296
- _defineProperty(this, "connect", this.create('CONNECT'));
297
-
298
- _defineProperty(this, "trace", this.create('TRACE'));
299
-
300
- _defineProperty(this, "acl", this.create('ACL'));
301
-
302
- _defineProperty(this, "bind", this.create('BIND'));
303
-
304
- this.procs = procs;
305
- this._procsArray = Object.values(procs);
306
- }
307
-
308
- getProcs() {
309
- return this.procs;
310
- }
311
-
312
- find(method, url) {
313
- for (var proc of this._procsArray) {
314
- if (proc.method !== method) {
315
- continue;
316
- }
317
-
318
- if (proc.pattern.test(url)) {
319
- return proc;
320
- }
321
- }
322
-
323
- return null;
324
- }
325
-
326
- }
327
- class KaitoError extends Error {
328
- constructor(status, message, cause) {
329
- super(message);
330
- this.status = status;
331
- this.cause = cause;
332
- }
333
-
334
- }
335
- function createRouter() {
336
- return new Router({});
337
- }
338
- function createServer(config) {
339
- var log = message => {
340
- if (config.log === undefined) {
341
- console.log(message);
342
- } else if (config.log) {
343
- config.log(message);
344
- }
345
- };
346
-
347
- return http.createServer( /*#__PURE__*/function () {
348
- var _ref = _asyncToGenerator(function* (incomingMessage, serverResponse) {
349
- var start = Date.now();
350
- var req = new KaitoRequest(incomingMessage);
351
- var res = new KaitoResponse(serverResponse);
352
-
270
+ static handle(server, options) {
271
+ return _asyncToGenerator(function* () {
353
272
  try {
354
- var _handler$input, _yield$getInput;
355
-
356
- var handler = config.router.find(req.method, req.raw.url);
273
+ var _options$route$input$, _options$route$input;
357
274
 
358
- if (!handler) {
359
- throw new KaitoError(404, "Cannot ".concat(req.method, " this route."));
360
- }
361
-
362
- 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);
363
- var context = yield config.getContext(req, res);
364
- 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({
365
279
  ctx: context,
366
280
  input,
367
- params: {}
281
+ params: options.params
368
282
  });
369
- res.json({
283
+ options.res.status(200).json({
370
284
  success: true,
371
- data,
285
+ data: result,
372
286
  message: 'OK'
373
287
  });
374
- } catch (error) {
288
+ } catch (e) {
289
+ var error = WrappedError.maybe(e);
290
+
375
291
  if (error instanceof KaitoError) {
376
- res.status(error.status).json({
292
+ options.res.status(error.status).json({
377
293
  success: false,
378
294
  data: null,
379
295
  message: error.message
@@ -382,31 +298,108 @@ function createServer(config) {
382
298
  }
383
299
 
384
300
  var {
385
- status: _status,
386
- message: _message
387
- } = yield config.onError({
388
- error: WrappedError.maybe(error),
389
- req,
390
- res
301
+ status,
302
+ message
303
+ } = yield server.onError({
304
+ error,
305
+ req: options.req,
306
+ res: options.res
391
307
  }).catch(() => ({
392
308
  status: 500,
393
- message: 'Something went wrong'
309
+ message: 'Internal Server Error'
394
310
  }));
395
- res.status(_status).json({
311
+ options.res.status(status).json({
396
312
  success: false,
397
313
  data: null,
398
- message: _message
314
+ message
399
315
  });
400
- } finally {
401
- var finish = Date.now();
402
- log("".concat(req.method, " ").concat(req.fullURL, " ").concat(res.raw.statusCode, " ").concat(finish - start, "ms"));
403
316
  }
404
- });
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;
405
344
 
406
- return function (_x, _x2) {
407
- 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
+ }));
408
395
  };
409
- }());
396
+ }
397
+
410
398
  }
399
+ /**
400
+ * @deprecated Please use Router#create instead
401
+ */
402
+
403
+ var createRouter = Router.create;
411
404
 
412
- 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.7",
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
  }