@onlinx/core
Advanced tools
Comparing version 0.1.1 to 0.1.2
@@ -21,6 +21,4 @@ /// <reference types="node" /> | ||
private request; | ||
body?: string | Buffer | UnknownObject; | ||
headers: Headers; | ||
continued: boolean; | ||
continue(): void; | ||
data: UnknownObject; | ||
constructor(request: ContextRequest); | ||
@@ -27,0 +25,0 @@ status(status: number): Context; |
@@ -77,3 +77,3 @@ 'use strict'; | ||
this.continued = false; // Makes sure that the defaultResponse is not mutated | ||
this.data = {}; // Makes sure that the defaultResponse is not mutated | ||
@@ -94,6 +94,2 @@ this.response = _extends({}, defaultResponse); | ||
_proto["continue"] = function _continue() { | ||
this.continued = true; | ||
}; | ||
_proto.status = function status(_status) { | ||
@@ -367,37 +363,11 @@ this.response.status = _status; | ||
var _temp6 = function () { | ||
var _temp3 = function () { | ||
var _request$method; | ||
if (method === ((_request$method = request.method) === null || _request$method === void 0 ? void 0 : _request$method.toLowerCase())) { | ||
var _temp7 = function () { | ||
var _temp4 = function () { | ||
if (handler instanceof Array) { | ||
var _interrupt2 = false; | ||
var _temp8 = _forOf(handler, function (h) { | ||
return Promise.resolve(h(routeContext)).then(function (res) { | ||
var _temp2 = function () { | ||
if (res === undefined || res === true) {} else { | ||
var _temp9 = function () { | ||
if (res === false) { | ||
_interrupt2 = true; | ||
} else { | ||
return Promise.resolve(createResponse(res, response, routeContext)).then(function () { | ||
_interrupt2 = true; | ||
}); | ||
} | ||
}(); | ||
if (_temp9 && _temp9.then) return _temp9.then(function () {}); | ||
} | ||
}(); | ||
if (_temp2 && _temp2.then) return _temp2.then(function () {}); | ||
}); | ||
}, function () { | ||
return _interrupt2; | ||
}); | ||
if (_temp8 && _temp8.then) return _temp8.then(function () {}); | ||
return Promise.resolve(handleHandlerArray(handler, routeContext, response)).then(function () {}); | ||
} else { | ||
var _temp10 = function () { | ||
var _temp5 = function () { | ||
if (handler != undefined) { | ||
@@ -410,13 +380,11 @@ return Promise.resolve(handler(routeContext)).then(function (res) { | ||
if (_temp10 && _temp10.then) return _temp10.then(function () {}); | ||
if (_temp5 && _temp5.then) return _temp5.then(function () {}); | ||
} | ||
}(); | ||
if (_temp7 && _temp7.then) return _temp7.then(function () {}); | ||
if (_temp4 && _temp4.then) return _temp4.then(function () {}); | ||
} | ||
}(); | ||
if (_temp6 && _temp6.then) return _temp6.then(function () {}); | ||
}, function () { | ||
return _interrupt2; | ||
if (_temp3 && _temp3.then) return _temp3.then(function () {}); | ||
})); | ||
@@ -441,2 +409,36 @@ } catch (e) { | ||
var handleHandlerArray = function handleHandlerArray(handler, context, response) { | ||
try { | ||
var _interrupt2 = false; | ||
var _temp9 = _forOf(handler, function (h) { | ||
return Promise.resolve(h(context)).then(function (res) { | ||
var _temp7 = function () { | ||
if (res === undefined || res === true) {} else { | ||
var _temp10 = function () { | ||
if (res === false) { | ||
_interrupt2 = true; | ||
} else { | ||
return Promise.resolve(createResponse(res, response, context)).then(function () { | ||
_interrupt2 = true; | ||
}); | ||
} | ||
}(); | ||
if (_temp10 && _temp10.then) return _temp10.then(function () {}); | ||
} | ||
}(); | ||
if (_temp7 && _temp7.then) return _temp7.then(function () {}); | ||
}); | ||
}, function () { | ||
return _interrupt2; | ||
}); | ||
return Promise.resolve(_temp9 && _temp9.then ? _temp9.then(function () {}) : void 0); | ||
} catch (e) { | ||
return Promise.reject(e); | ||
} | ||
}; | ||
var Server = /*#__PURE__*/function () { | ||
@@ -443,0 +445,0 @@ function Server(controller) { |
@@ -1,2 +0,2 @@ | ||
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var t=require("url"),n=require("http");function r(){return(r=Object.assign||function(t){for(var n=1;n<arguments.length;n++){var r=arguments[n];for(var e in r)Object.prototype.hasOwnProperty.call(r,e)&&(t[e]=r[e])}return t}).apply(this,arguments)}function e(t,n){(null==n||n>t.length)&&(n=t.length);for(var r=0,e=new Array(n);r<n;r++)e[r]=t[r];return e}var o={type:"text/plain",status:404,headers:{}},i=function(){function t(t){var n=this;this.continued=!1,this.response=r({},o),this.request=t,this.headers={get:function(t){return n.request.headers[t.toLowerCase()]},set:function(t,r){n.response.headers[t]=r}}}var n=t.prototype;return n.continue=function(){this.continued=!0},n.status=function(t){return this.response.status=t,this},t}();const u=function(){function t(){}return t.prototype.then=function(n,r){const e=new t,o=this.s;if(o){const t=1&o?n:r;if(t){try{s(e,1,t(this.v))}catch(t){s(e,2,t)}return e}return this}return this.o=function(t){try{const o=t.v;1&t.s?s(e,1,n?n(o):o):r?s(e,1,r(o)):s(e,2,o)}catch(t){s(e,2,t)}},e},t}();function s(t,n,r){if(!t.s){if(r instanceof u){if(!r.s)return void(r.o=s.bind(null,t,n));1&n&&(n=r.s),r=r.v}if(r&&r.then)return void r.then(s.bind(null,t,n),s.bind(null,t,2));t.s=n,t.v=r;const e=t.o;e&&e(t)}}function c(t){return t instanceof u&&1&t.s}const a="undefined"!=typeof Symbol?Symbol.iterator||(Symbol.iterator=Symbol("Symbol.iterator")):"@@iterator";function f(t,n,r){if("function"==typeof t[a]){var e,o,i,f=t[a]();if(function t(a){try{for(;!((e=f.next()).done||r&&r());)if((a=n(e.value))&&a.then){if(!c(a))return void a.then(t,i||(i=s.bind(null,o=new u,2)));a=a.v}o?s(o,1,a):o=a}catch(t){s(o||(o=new u),2,t)}}(),f.return){var h=function(t){try{e.done||f.return()}catch(t){}return t};if(o&&o.then)return o.then(h,(function(t){throw h(t)}));h()}return o}if(!("length"in t))throw new TypeError("Object is not iterable");for(var l=[],v=0;v<t.length;v++)l.push(t[v]);return function(t,n,r){var e,o,i=-1;return function a(f){try{for(;++i<t.length&&(!r||!r());)if((f=n(i))&&f.then){if(!c(f))return void f.then(a,o||(o=s.bind(null,e=new u,2)));f=f.v}e?s(e,1,f):e=f}catch(t){s(e||(e=new u),2,t)}}(),e}(l,(function(t){return n(l[t])}),r)}"undefined"!=typeof Symbol&&(Symbol.asyncIterator||(Symbol.asyncIterator=Symbol("Symbol.asyncIterator")));var h=function(){function n(){this.routes=[]}var r=n.prototype;return r.route=function(t,n){this.routes.push({path:t,routes:n})},r.mount=function(){var n=this;return function(r,o){try{var i=(u=t.parse(r.url||"/").pathname||"",s={path:"*",routes:{all:function(t){try{return t.status(404),Promise.resolve("404 Not Found")}catch(t){return Promise.reject(t)}}}},function(t){for(var n,r=[],o=function(t,n){var r;if("undefined"==typeof Symbol||null==t[Symbol.iterator]){if(Array.isArray(t)||(r=function(t,n){if(t){if("string"==typeof t)return e(t,void 0);var r=Object.prototype.toString.call(t).slice(8,-1);return"Object"===r&&t.constructor&&(r=t.constructor.name),"Map"===r||"Set"===r?Array.from(t):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?e(t,void 0):void 0}}(t))){r&&(t=r);var o=0;return function(){return o>=t.length?{done:!0}:{done:!1,value:t[o++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}return(r=t[Symbol.iterator]()).next.bind(r)}(t);!(n=o()).done;){var i=n.value;"*"===i.path?r.unshift(i):i.path.startsWith("/")&&r.push(i)}return r}(n.routes).some((function(t){return("*"===t.path||t.path===u)&&(s=t,!0)})),s);return Promise.resolve(l(i,r,o)).then((function(){}))}catch(t){return Promise.reject(t)}var u,s}},n}(),l=function(t,n,r){try{var e=function(t){return{headers:t.headers}}(n),o=new i(e);return Promise.resolve(f(Object.entries(t.routes),(function(t){var e=t[0],i=t[1],u=function(){var t;if(e===(null===(t=n.method)||void 0===t?void 0:t.toLowerCase())){var u=function(){if(i instanceof Array){var t=!1,n=f(i,(function(n){return Promise.resolve(n(o)).then((function(n){var e=function(){if(void 0===n||!0===n);else{var e=function(){if(!1!==n)return Promise.resolve(v(n,r,o)).then((function(){t=!0}));t=!0}();if(e&&e.then)return e.then((function(){}))}}();if(e&&e.then)return e.then((function(){}))}))}),(function(){return t}));if(n&&n.then)return n.then((function(){}))}else{var e=function(){if(null!=i)return Promise.resolve(i(o)).then((function(t){return Promise.resolve(v(t,r,o)).then((function(){}))}))}();if(e&&e.then)return e.then((function(){}))}}();if(u&&u.then)return u.then((function(){}))}}();if(u&&u.then)return u.then((function(){}))}),(function(){return _interrupt2})))}catch(t){return Promise.reject(t)}},v=function(t,n,e){var o={};"object"==typeof t&&(o["Content-Type"]="application/json"),o=r({},o,e.response.headers),n.writeHead(e.response.status,o),n.write(t),n.end()},p=function(){function t(t){this.controller=t,this.server=n.createServer(this.controller.router.mount())}return t.prototype.mount=function(t,n){this.server.listen(t,n)},t}();exports.Context=i,exports.Controller=function(t){this.router=t},exports.Router=h,exports.Server=p; | ||
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var t=require("url"),n=require("http");function r(){return(r=Object.assign||function(t){for(var n=1;n<arguments.length;n++){var r=arguments[n];for(var e in r)Object.prototype.hasOwnProperty.call(r,e)&&(t[e]=r[e])}return t}).apply(this,arguments)}function e(t,n){(null==n||n>t.length)&&(n=t.length);for(var r=0,e=new Array(n);r<n;r++)e[r]=t[r];return e}var o={type:"text/plain",status:404,headers:{}},i=function(){function t(t){var n=this;this.data={},this.response=r({},o),this.request=t,this.headers={get:function(t){return n.request.headers[t.toLowerCase()]},set:function(t,r){n.response.headers[t]=r}}}return t.prototype.status=function(t){return this.response.status=t,this},t}();const u=function(){function t(){}return t.prototype.then=function(n,r){const e=new t,o=this.s;if(o){const t=1&o?n:r;if(t){try{s(e,1,t(this.v))}catch(t){s(e,2,t)}return e}return this}return this.o=function(t){try{const o=t.v;1&t.s?s(e,1,n?n(o):o):r?s(e,1,r(o)):s(e,2,o)}catch(t){s(e,2,t)}},e},t}();function s(t,n,r){if(!t.s){if(r instanceof u){if(!r.s)return void(r.o=s.bind(null,t,n));1&n&&(n=r.s),r=r.v}if(r&&r.then)return void r.then(s.bind(null,t,n),s.bind(null,t,2));t.s=n,t.v=r;const e=t.o;e&&e(t)}}function c(t){return t instanceof u&&1&t.s}const a="undefined"!=typeof Symbol?Symbol.iterator||(Symbol.iterator=Symbol("Symbol.iterator")):"@@iterator";function f(t,n,r){if("function"==typeof t[a]){var e,o,i,f=t[a]();if(function t(a){try{for(;!((e=f.next()).done||r&&r());)if((a=n(e.value))&&a.then){if(!c(a))return void a.then(t,i||(i=s.bind(null,o=new u,2)));a=a.v}o?s(o,1,a):o=a}catch(t){s(o||(o=new u),2,t)}}(),f.return){var h=function(t){try{e.done||f.return()}catch(t){}return t};if(o&&o.then)return o.then(h,(function(t){throw h(t)}));h()}return o}if(!("length"in t))throw new TypeError("Object is not iterable");for(var l=[],v=0;v<t.length;v++)l.push(t[v]);return function(t,n,r){var e,o,i=-1;return function a(f){try{for(;++i<t.length&&(!r||!r());)if((f=n(i))&&f.then){if(!c(f))return void f.then(a,o||(o=s.bind(null,e=new u,2)));f=f.v}e?s(e,1,f):e=f}catch(t){s(e||(e=new u),2,t)}}(),e}(l,(function(t){return n(l[t])}),r)}"undefined"!=typeof Symbol&&(Symbol.asyncIterator||(Symbol.asyncIterator=Symbol("Symbol.asyncIterator")));var h=function(){function n(){this.routes=[]}var r=n.prototype;return r.route=function(t,n){this.routes.push({path:t,routes:n})},r.mount=function(){var n=this;return function(r,o){try{var i=(u=t.parse(r.url||"/").pathname||"",s={path:"*",routes:{all:function(t){try{return t.status(404),Promise.resolve("404 Not Found")}catch(t){return Promise.reject(t)}}}},function(t){for(var n,r=[],o=function(t,n){var r;if("undefined"==typeof Symbol||null==t[Symbol.iterator]){if(Array.isArray(t)||(r=function(t,n){if(t){if("string"==typeof t)return e(t,void 0);var r=Object.prototype.toString.call(t).slice(8,-1);return"Object"===r&&t.constructor&&(r=t.constructor.name),"Map"===r||"Set"===r?Array.from(t):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?e(t,void 0):void 0}}(t))){r&&(t=r);var o=0;return function(){return o>=t.length?{done:!0}:{done:!1,value:t[o++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}return(r=t[Symbol.iterator]()).next.bind(r)}(t);!(n=o()).done;){var i=n.value;"*"===i.path?r.unshift(i):i.path.startsWith("/")&&r.push(i)}return r}(n.routes).some((function(t){return("*"===t.path||t.path===u)&&(s=t,!0)})),s);return Promise.resolve(l(i,r,o)).then((function(){}))}catch(t){return Promise.reject(t)}var u,s}},n}(),l=function(t,n,r){try{var e=function(t){return{headers:t.headers}}(n),o=new i(e);return Promise.resolve(f(Object.entries(t.routes),(function(t){var e=t[0],i=t[1],u=function(){var t;if(e===(null===(t=n.method)||void 0===t?void 0:t.toLowerCase())){var u=function(){if(i instanceof Array)return Promise.resolve(p(i,o,r)).then((function(){}));var t=function(){if(null!=i)return Promise.resolve(i(o)).then((function(t){return Promise.resolve(v(t,r,o)).then((function(){}))}))}();return t&&t.then?t.then((function(){})):void 0}();if(u&&u.then)return u.then((function(){}))}}();if(u&&u.then)return u.then((function(){}))})))}catch(t){return Promise.reject(t)}},v=function(t,n,e){var o={};"object"==typeof t&&(o["Content-Type"]="application/json"),o=r({},o,e.response.headers),n.writeHead(e.response.status,o),n.write(t),n.end()},p=function(t,n,r){try{var e=!1,o=f(t,(function(t){return Promise.resolve(t(n)).then((function(t){var o=function(){if(void 0===t||!0===t);else{var o=function(){if(!1!==t)return Promise.resolve(v(t,r,n)).then((function(){e=!0}));e=!0}();if(o&&o.then)return o.then((function(){}))}}();if(o&&o.then)return o.then((function(){}))}))}),(function(){return e}));return Promise.resolve(o&&o.then?o.then((function(){})):void 0)}catch(t){return Promise.reject(t)}},y=function(){function t(t){this.controller=t,this.server=n.createServer(this.controller.router.mount())}return t.prototype.mount=function(t,n){this.server.listen(t,n)},t}();exports.Context=i,exports.Controller=function(t){this.router=t},exports.Router=h,exports.Server=y; | ||
//# sourceMappingURL=core.cjs.production.min.js.map |
@@ -73,3 +73,3 @@ import { parse } from 'url'; | ||
this.continued = false; // Makes sure that the defaultResponse is not mutated | ||
this.data = {}; // Makes sure that the defaultResponse is not mutated | ||
@@ -90,6 +90,2 @@ this.response = _extends({}, defaultResponse); | ||
_proto["continue"] = function _continue() { | ||
this.continued = true; | ||
}; | ||
_proto.status = function status(_status) { | ||
@@ -363,37 +359,11 @@ this.response.status = _status; | ||
var _temp6 = function () { | ||
var _temp3 = function () { | ||
var _request$method; | ||
if (method === ((_request$method = request.method) === null || _request$method === void 0 ? void 0 : _request$method.toLowerCase())) { | ||
var _temp7 = function () { | ||
var _temp4 = function () { | ||
if (handler instanceof Array) { | ||
var _interrupt2 = false; | ||
var _temp8 = _forOf(handler, function (h) { | ||
return Promise.resolve(h(routeContext)).then(function (res) { | ||
var _temp2 = function () { | ||
if (res === undefined || res === true) {} else { | ||
var _temp9 = function () { | ||
if (res === false) { | ||
_interrupt2 = true; | ||
} else { | ||
return Promise.resolve(createResponse(res, response, routeContext)).then(function () { | ||
_interrupt2 = true; | ||
}); | ||
} | ||
}(); | ||
if (_temp9 && _temp9.then) return _temp9.then(function () {}); | ||
} | ||
}(); | ||
if (_temp2 && _temp2.then) return _temp2.then(function () {}); | ||
}); | ||
}, function () { | ||
return _interrupt2; | ||
}); | ||
if (_temp8 && _temp8.then) return _temp8.then(function () {}); | ||
return Promise.resolve(handleHandlerArray(handler, routeContext, response)).then(function () {}); | ||
} else { | ||
var _temp10 = function () { | ||
var _temp5 = function () { | ||
if (handler != undefined) { | ||
@@ -406,13 +376,11 @@ return Promise.resolve(handler(routeContext)).then(function (res) { | ||
if (_temp10 && _temp10.then) return _temp10.then(function () {}); | ||
if (_temp5 && _temp5.then) return _temp5.then(function () {}); | ||
} | ||
}(); | ||
if (_temp7 && _temp7.then) return _temp7.then(function () {}); | ||
if (_temp4 && _temp4.then) return _temp4.then(function () {}); | ||
} | ||
}(); | ||
if (_temp6 && _temp6.then) return _temp6.then(function () {}); | ||
}, function () { | ||
return _interrupt2; | ||
if (_temp3 && _temp3.then) return _temp3.then(function () {}); | ||
})); | ||
@@ -437,2 +405,36 @@ } catch (e) { | ||
var handleHandlerArray = function handleHandlerArray(handler, context, response) { | ||
try { | ||
var _interrupt2 = false; | ||
var _temp9 = _forOf(handler, function (h) { | ||
return Promise.resolve(h(context)).then(function (res) { | ||
var _temp7 = function () { | ||
if (res === undefined || res === true) {} else { | ||
var _temp10 = function () { | ||
if (res === false) { | ||
_interrupt2 = true; | ||
} else { | ||
return Promise.resolve(createResponse(res, response, context)).then(function () { | ||
_interrupt2 = true; | ||
}); | ||
} | ||
}(); | ||
if (_temp10 && _temp10.then) return _temp10.then(function () {}); | ||
} | ||
}(); | ||
if (_temp7 && _temp7.then) return _temp7.then(function () {}); | ||
}); | ||
}, function () { | ||
return _interrupt2; | ||
}); | ||
return Promise.resolve(_temp9 && _temp9.then ? _temp9.then(function () {}) : void 0); | ||
} catch (e) { | ||
return Promise.reject(e); | ||
} | ||
}; | ||
var Server = /*#__PURE__*/function () { | ||
@@ -439,0 +441,0 @@ function Server(controller) { |
@@ -1,6 +0,6 @@ | ||
import * as http from 'http'; | ||
import { Route } from '../router'; | ||
import { ContextRequest } from '../context'; | ||
import type { ContextRequest } from '../context'; | ||
import type { IncomingMessage } from 'http'; | ||
import type { Route } from '../router'; | ||
export declare const getRoute: (path: string, routes: Route[]) => Route; | ||
export declare const sortRoutes: (routes: Route[]) => Route[]; | ||
export declare const createContextRequest: (request: http.IncomingMessage) => ContextRequest; | ||
export declare const createContextRequest: (request: IncomingMessage) => ContextRequest; |
{ | ||
"version": "0.1.1", | ||
"version": "0.1.2", | ||
"license": "MIT", | ||
@@ -4,0 +4,0 @@ "main": "dist/index.js", |
@@ -14,3 +14,3 @@ # Onlinx | ||
```ts | ||
import { Controller, Router, Server } from 'onlinx'; | ||
import { Controller, Router, Server } from '@onlinx/core'; | ||
@@ -35,4 +35,26 @@ const router = new Router(); | ||
Usage with node is coming soon. We need to configure some config options to get it to work with both Typescript and Node | ||
Run `npm install @onlinx/core` | ||
Here's the hello world example in Node | ||
```ts | ||
const { Controller, Router, Server } = require('@onlinx/core'); | ||
const router = new Router(); | ||
router.route('/', { | ||
get() { | ||
return 'hello world' | ||
} | ||
}) | ||
const controller = new Controller(router); | ||
const app = new Server(controller); | ||
app.mount(3000, () => console.log('running...')); | ||
``` | ||
The server will be running on port 3000 | ||
As you can tell, it's not very different from the typescript verson. From now on, all examples are in Typescript | ||
## API Documentation | ||
@@ -61,2 +83,22 @@ | ||
#### `data` | ||
The `data` object allows middlewares to pass data to the next handler. For example, a body parser could pass the contents of the body to the rest of the middlewares | ||
Note that type assertions are neccessary at the moment due to the way it is set up | ||
Example (only the important parts): | ||
```ts | ||
const body = (ctx: Context) => { | ||
ctx.data.body = 'hello'; | ||
return true | ||
} | ||
router.route('/', { | ||
get: [body, (ctx: Context) => { | ||
return ctx.data.body as string; | ||
}] | ||
}) | ||
``` | ||
## Common questions | ||
@@ -100,4 +142,4 @@ | ||
```typescript | ||
import { Controller, Router, Server } from './node_modules/onlinx'; | ||
```ts | ||
import { Controller, Router, Server } from '@onlinx/core'; | ||
@@ -120,3 +162,3 @@ const router = new Router(); | ||
```typescript | ||
```ts | ||
import { Controller, Router, Server, Context } from './node_modules/onlinx'; | ||
@@ -123,0 +165,0 @@ |
@@ -30,12 +30,6 @@ import { IncomingHttpHeaders } from 'http'; | ||
body?: string | Buffer | UnknownObject | ||
headers: Headers | ||
continued: boolean = false | ||
continue() { | ||
this.continued = true; | ||
} | ||
data: UnknownObject | ||
constructor(request: ContextRequest) { | ||
this.data = {}; | ||
// Makes sure that the defaultResponse is not mutated | ||
@@ -42,0 +36,0 @@ this.response = { |
import * as http from 'http'; | ||
import * as url from 'url'; | ||
import { Context, HeadersObject } from './context'; | ||
import { HandlerCallback } from './handler'; | ||
import { getRoute, createContextRequest } from './utils/helpers'; | ||
import { Context, HeadersObject } from './context'; | ||
import { createContextRequest, getRoute } from './utils/helpers'; | ||
@@ -19,3 +19,3 @@ type AcceptedHandler = HandlerCallback | HandlerCallback[] | undefined; | ||
[key: string]: AcceptedHandler | ||
}; | ||
} | ||
@@ -55,4 +55,4 @@ export interface Route { | ||
// }); | ||
const correctRoute = getRoute(path || '', this.routes) | ||
await handleRoute(correctRoute, request, response) | ||
const correctRoute = getRoute(path || '', this.routes); | ||
await handleRoute(correctRoute, request, response); | ||
}; | ||
@@ -63,6 +63,6 @@ } | ||
const handleRoute = async (route: Route, request: http.IncomingMessage, response: http.ServerResponse) => { | ||
const contextRequest = createContextRequest(request) | ||
const routeContext = new Context(contextRequest) | ||
const contextRequest = createContextRequest(request); | ||
const routeContext = new Context(contextRequest); | ||
for(let [method, handler] of Object.entries(route.routes)) { | ||
for(const [ method, handler ] of Object.entries(route.routes)) { | ||
// if(method === 'all') { | ||
@@ -73,24 +73,14 @@ // continue; | ||
if(handler instanceof Array) { | ||
for(const h of handler) { | ||
const res = await h(routeContext) | ||
if(res === undefined ||res === true) { | ||
continue | ||
} else if(res === false ) { | ||
break | ||
} else { | ||
await createResponse<typeof res>(res, response, routeContext) | ||
break | ||
} | ||
} | ||
await handleHandlerArray(handler, routeContext, response); | ||
} else if(handler != undefined) { | ||
const res = await handler(routeContext) | ||
await createResponse<typeof res>(res, response, routeContext) | ||
} | ||
const res = await handler(routeContext); | ||
await createResponse<typeof res>(res, response, routeContext); | ||
} | ||
} | ||
} | ||
} | ||
}; | ||
const createResponse = <T>(handlerResponse: T, response: http.ServerResponse, context: Context) => { | ||
let headers: HeadersObject = {} | ||
let headers: HeadersObject = {}; | ||
if(typeof handlerResponse === 'object') { | ||
headers['Content-Type'] = 'application/json' | ||
headers['Content-Type'] = 'application/json'; | ||
} | ||
@@ -100,6 +90,20 @@ headers = { | ||
...context.response.headers | ||
}; | ||
response.writeHead(context.response.status, headers); | ||
response.write(handlerResponse); | ||
response.end(); | ||
}; | ||
const handleHandlerArray = async (handler: HandlerCallback[], context: Context, response: http.ServerResponse) => { | ||
for(const h of handler) { | ||
const res = await h(context); | ||
if(res === undefined ||res === true) { | ||
continue; | ||
} else if(res === false ) { | ||
break; | ||
} else { | ||
await createResponse<typeof res>(res, response, context); | ||
break; | ||
} | ||
} | ||
response.writeHead(context.response.status, headers) | ||
response.write(handlerResponse) | ||
response.end() | ||
} | ||
}; |
@@ -1,4 +0,5 @@ | ||
import * as http from 'http'; | ||
import { Route } from '../router' | ||
import { Context, ContextRequest } from '../context'; | ||
import type { Context, ContextRequest } from '../context'; | ||
import type { IncomingMessage } from 'http'; | ||
import type { Route } from '../router'; | ||
// All the routing logic, as to not clog handler.ts and router.ts | ||
@@ -10,31 +11,31 @@ export const getRoute = (path: string, routes: Route[]): Route => { | ||
all: async (ctx: Context) => { | ||
ctx.status(404) | ||
return '404 Not Found' | ||
ctx.status(404); | ||
return '404 Not Found'; | ||
} | ||
} | ||
} | ||
const sorted = sortRoutes(routes) | ||
}; | ||
const sorted = sortRoutes(routes); | ||
sorted.some(route => { | ||
if(route.path === '*' || route.path === path) { | ||
validRoute = route | ||
return true | ||
validRoute = route; | ||
return true; | ||
} | ||
return false | ||
}) | ||
return validRoute | ||
} | ||
return false; | ||
}); | ||
return validRoute; | ||
}; | ||
export const sortRoutes = (routes: Route[]): Route[] => { | ||
let sorted = [] | ||
for(let route of routes) { | ||
if(route.path === '*') sorted.unshift(route) | ||
else if(route.path.startsWith('/')) sorted.push(route) | ||
const sorted = []; | ||
for(const route of routes) { | ||
if(route.path === '*') sorted.unshift(route); | ||
else if(route.path.startsWith('/')) sorted.push(route); | ||
} | ||
return sorted | ||
} | ||
return sorted; | ||
}; | ||
// Context related functions | ||
export const createContextRequest = (request: http.IncomingMessage): ContextRequest => { | ||
export const createContextRequest = (request: IncomingMessage): ContextRequest => { | ||
return { | ||
headers: request.headers | ||
} | ||
} | ||
}; | ||
}; |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
159976
1134
181