-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserville.js
1 lines (1 loc) · 1.62 KB
/
serville.js
1
const http=require('http'),url=require('url'),querystring=require('querystring');class Serville{constructor(){this.bindings=[],this.server=http.createServer((a,b)=>{let c=url.parse(a.url,!0),d=decodeURIComponent(c.pathname);for(var e of this.bindings){let g=d.match(e.at);if(null!==g&&(!e.types||-1<e.types.indexOf(a.method))){let d={};for(var f in e.keys)d[e.keys[f]]=g[parseInt(f)+1];let h='';return a.on('data',(a)=>h+=a),void a.on('end',()=>{try{let f=e.cb({params:d,headers:a.headers,query:Object.assign(c.query,querystring.parse(h)),match:g});f instanceof Promise?f.then((a)=>{b.end(JSON.stringify(a))}).catch((a)=>{this._handleBindingError(a,b)}):b.end(JSON.stringify(f))}catch(a){this._handleBindingError(a,b)}})}}b.statusCode=404,b.end('{ "status": "404", "message": "Endpoint Not Found" }')})}_handleBindingError(a,b){b.statusCode=500,b.end(JSON.stringify({status:'Server Error',error:a.message||a})),console.log(a),console.log('Fatal binding error, aborting app. Your server should handle automatic restarting.'),process.exit(1)}at(a,b,c){let d=!1;if(!(a instanceof RegExp)){let b=/\/\:([a-zA-Z0-9_]+?)(?=\/|$)/g,c=a.match(b)||[];d=a.replace(/[\-\[\]\/\{\}\(\)\*\+\.\\\^\$\|]/g,'\\$&');for(let a of c)d=d.replace(a,'/(.+?)')}return this.bindings.push({at:d?new RegExp('^'+d+'$','i'):a,keys:[].map((a)=>a.substring(2)),cb:b,types:c}),this}get(a,b){this.at(a,b,['GET'])}post(a,b){this.at(a,b,['POST'])}put(a,b){this.at(a,b,['PUT'])}delete(a,b){this.at(a,b,['DELETE'])}on(a,b){return this.server.on(a,(a,c)=>b(a,c)),this}catch(a){return this.on('clientError',a),this}listen(a,b){return this.server.listen(a,b),this}}module.exports=()=>new Serville;