Comparing version
@@ -8,2 +8,15 @@ # Nodecaf Changelog | ||
## [v0.11.4] - 2021-01-21 | ||
### Added | ||
- `pre()` and `pos()` hooks functionality | ||
### Fixed | ||
- memory leak during cors | ||
- assertion responding with text 'undefined' when no message is set | ||
### Removed | ||
- automatic gzip for payloads of over 4kb | ||
- a lot of dead-weight from useless dependencies | ||
## [v0.11.3] - 2020-12-14 | ||
@@ -87,2 +100,12 @@ | ||
## [v0.9.5] (hotfix) - 2021-01-13 | ||
### Fixed | ||
- body request being logged to console every time | ||
## [v0.9.4] (hotfix) - 2020-11-09 | ||
### Fixed | ||
- Add missing cookies support to WS handlers | ||
## [v0.9.3] - 2020-08-07 | ||
@@ -459,1 +482,2 @@ | ||
[v0.11.3]: https://gitlab.com/GCSBOSS/nodecaf/-/tags/v0.11.3 | ||
[v0.11.4]: https://gitlab.com/GCSBOSS/nodecaf/-/tags/v0.11.4 |
@@ -1,1 +0,1 @@ | ||
[{"categories":["Complexity"],"check_name":"method_complexity","content":{"body":"# Cognitive Complexity\nCognitive Complexity is a measure of how difficult a unit of code is to intuitively understand. Unlike Cyclomatic Complexity, which determines how difficult your code will be to test, Cognitive Complexity tells you how difficult your code will be to read and comprehend.\n\n### A method's cognitive complexity is based on a few simple rules:\n* Code is not considered more complex when it uses shorthand that the language provides for collapsing multiple statements into one\n* Code is considered more complex for each \"break in the linear flow of the code\"\n* Code is considered more complex when \"flow breaking structures are nested\"\n\n### Further reading\n* [Cognitive Complexity docs](https://docs.codeclimate.com/v1.0/docs/cognitive-complexity)\n* [Cognitive Complexity: A new way of measuring understandability](https://www.sonarsource.com/docs/CognitiveComplexity.pdf)\n"},"description":"Function `matchRoute` has a Cognitive Complexity of 7 (exceeds 5 allowed). Consider refactoring.","fingerprint":"f1ec05382472876a629e10fabf52d32b","location":{"path":"lib/api.js","lines":{"begin":32,"end":48}},"other_locations":[],"remediation_points":350000,"severity":"minor","type":"issue","engine_name":"structure"},{"categories":["Complexity"],"check_name":"method_complexity","content":{"body":"# Cognitive Complexity\nCognitive Complexity is a measure of how difficult a unit of code is to intuitively understand. Unlike Cyclomatic Complexity, which determines how difficult your code will be to test, Cognitive Complexity tells you how difficult your code will be to read and comprehend.\n\n### A method's cognitive complexity is based on a few simple rules:\n* Code is not considered more complex when it uses shorthand that the language provides for collapsing multiple statements into one\n* Code is considered more complex for each \"break in the linear flow of the code\"\n* Code is considered more complex when \"flow breaking structures are nested\"\n\n### Further reading\n* [Cognitive Complexity docs](https://docs.codeclimate.com/v1.0/docs/cognitive-complexity)\n* [Cognitive Complexity: A new way of measuring understandability](https://www.sonarsource.com/docs/CognitiveComplexity.pdf)\n"},"description":"Function `parseSignedCookies` has a Cognitive Complexity of 6 (exceeds 5 allowed). Consider refactoring.","fingerprint":"1a232bcf8abb180d7d962d700b545e32","location":{"path":"lib/api.js","lines":{"begin":89,"end":99}},"other_locations":[],"remediation_points":250000,"severity":"minor","type":"issue","engine_name":"structure"},{"categories":["Complexity"],"check_name":"method_complexity","content":{"body":"# Cognitive Complexity\nCognitive Complexity is a measure of how difficult a unit of code is to intuitively understand. Unlike Cyclomatic Complexity, which determines how difficult your code will be to test, Cognitive Complexity tells you how difficult your code will be to read and comprehend.\n\n### A method's cognitive complexity is based on a few simple rules:\n* Code is not considered more complex when it uses shorthand that the language provides for collapsing multiple statements into one\n* Code is considered more complex for each \"break in the linear flow of the code\"\n* Code is considered more complex when \"flow breaking structures are nested\"\n\n### Further reading\n* [Cognitive Complexity docs](https://docs.codeclimate.com/v1.0/docs/cognitive-complexity)\n* [Cognitive Complexity: A new way of measuring understandability](https://www.sonarsource.com/docs/CognitiveComplexity.pdf)\n"},"description":"Function `parseBody` has a Cognitive Complexity of 6 (exceeds 5 allowed). Consider refactoring.","fingerprint":"0a4d135aa1342b4a3c74ca38b609ff04","location":{"path":"lib/parser.js","lines":{"begin":26,"end":52}},"other_locations":[],"remediation_points":250000,"severity":"minor","type":"issue","engine_name":"structure"},{"categories":["Complexity"],"check_name":"return_statements","content":{"body":""},"description":"Avoid too many `return` statements within this function.","location":{"path":"lib/parser.js","lines":{"begin":47,"end":47}},"other_locations":[],"remediation_points":300000,"severity":"major","type":"issue","engine_name":"structure","fingerprint":"3e5e98cdcba8196f5b12dfdad720bf15"},{"categories":["Complexity"],"check_name":"return_statements","content":{"body":""},"description":"Avoid too many `return` statements within this function.","location":{"path":"lib/error.js","lines":{"begin":20,"end":20}},"other_locations":[],"remediation_points":300000,"severity":"major","type":"issue","engine_name":"structure","fingerprint":"4817974afd7e0907cec853ce7a62130c"}] | ||
[{"categories":["Complexity"],"check_name":"method_complexity","content":{"body":"# Cognitive Complexity\nCognitive Complexity is a measure of how difficult a unit of code is to intuitively understand. Unlike Cyclomatic Complexity, which determines how difficult your code will be to test, Cognitive Complexity tells you how difficult your code will be to read and comprehend.\n\n### A method's cognitive complexity is based on a few simple rules:\n* Code is not considered more complex when it uses shorthand that the language provides for collapsing multiple statements into one\n* Code is considered more complex for each \"break in the linear flow of the code\"\n* Code is considered more complex when \"flow breaking structures are nested\"\n\n### Further reading\n* [Cognitive Complexity docs](https://docs.codeclimate.com/v1.0/docs/cognitive-complexity)\n* [Cognitive Complexity: A new way of measuring understandability](https://www.sonarsource.com/docs/CognitiveComplexity.pdf)\n"},"description":"Function `error` has a Cognitive Complexity of 6 (exceeds 5 allowed). Consider refactoring.","fingerprint":"88994aa80c77bbca72328cfc03a840dc","location":{"path":"lib/response.js","lines":{"begin":69,"end":96}},"other_locations":[],"remediation_points":250000,"severity":"minor","type":"issue","engine_name":"structure"},{"categories":["Complexity"],"check_name":"method_complexity","content":{"body":"# Cognitive Complexity\nCognitive Complexity is a measure of how difficult a unit of code is to intuitively understand. Unlike Cyclomatic Complexity, which determines how difficult your code will be to test, Cognitive Complexity tells you how difficult your code will be to read and comprehend.\n\n### A method's cognitive complexity is based on a few simple rules:\n* Code is not considered more complex when it uses shorthand that the language provides for collapsing multiple statements into one\n* Code is considered more complex for each \"break in the linear flow of the code\"\n* Code is considered more complex when \"flow breaking structures are nested\"\n\n### Further reading\n* [Cognitive Complexity docs](https://docs.codeclimate.com/v1.0/docs/cognitive-complexity)\n* [Cognitive Complexity: A new way of measuring understandability](https://www.sonarsource.com/docs/CognitiveComplexity.pdf)\n"},"description":"Function `matchRoute` has a Cognitive Complexity of 7 (exceeds 5 allowed). Consider refactoring.","fingerprint":"f1ec05382472876a629e10fabf52d32b","location":{"path":"lib/api.js","lines":{"begin":56,"end":73}},"other_locations":[],"remediation_points":350000,"severity":"minor","type":"issue","engine_name":"structure"},{"categories":["Complexity"],"check_name":"method_complexity","content":{"body":"# Cognitive Complexity\nCognitive Complexity is a measure of how difficult a unit of code is to intuitively understand. Unlike Cyclomatic Complexity, which determines how difficult your code will be to test, Cognitive Complexity tells you how difficult your code will be to read and comprehend.\n\n### A method's cognitive complexity is based on a few simple rules:\n* Code is not considered more complex when it uses shorthand that the language provides for collapsing multiple statements into one\n* Code is considered more complex for each \"break in the linear flow of the code\"\n* Code is considered more complex when \"flow breaking structures are nested\"\n\n### Further reading\n* [Cognitive Complexity docs](https://docs.codeclimate.com/v1.0/docs/cognitive-complexity)\n* [Cognitive Complexity: A new way of measuring understandability](https://www.sonarsource.com/docs/CognitiveComplexity.pdf)\n"},"description":"Function `parseSignedCookies` has a Cognitive Complexity of 6 (exceeds 5 allowed). Consider refactoring.","fingerprint":"1a232bcf8abb180d7d962d700b545e32","location":{"path":"lib/api.js","lines":{"begin":120,"end":130}},"other_locations":[],"remediation_points":250000,"severity":"minor","type":"issue","engine_name":"structure"},{"categories":["Complexity"],"check_name":"method_lines","content":{"body":""},"description":"Function `trigger` has 29 lines of code (exceeds 25 allowed). Consider refactoring.","fingerprint":"93febd1983b6007b540d743a3a9dac87","location":{"path":"lib/api.js","lines":{"begin":196,"end":238}},"other_locations":[],"remediation_points":696000,"severity":"minor","type":"issue","engine_name":"structure"},{"categories":["Complexity"],"check_name":"method_complexity","content":{"body":"# Cognitive Complexity\nCognitive Complexity is a measure of how difficult a unit of code is to intuitively understand. Unlike Cyclomatic Complexity, which determines how difficult your code will be to test, Cognitive Complexity tells you how difficult your code will be to read and comprehend.\n\n### A method's cognitive complexity is based on a few simple rules:\n* Code is not considered more complex when it uses shorthand that the language provides for collapsing multiple statements into one\n* Code is considered more complex for each \"break in the linear flow of the code\"\n* Code is considered more complex when \"flow breaking structures are nested\"\n\n### Further reading\n* [Cognitive Complexity docs](https://docs.codeclimate.com/v1.0/docs/cognitive-complexity)\n* [Cognitive Complexity: A new way of measuring understandability](https://www.sonarsource.com/docs/CognitiveComplexity.pdf)\n"},"description":"Function `parseBody` has a Cognitive Complexity of 6 (exceeds 5 allowed). Consider refactoring.","fingerprint":"0a4d135aa1342b4a3c74ca38b609ff04","location":{"path":"lib/parser.js","lines":{"begin":26,"end":52}},"other_locations":[],"remediation_points":250000,"severity":"minor","type":"issue","engine_name":"structure"},{"categories":["Complexity"],"check_name":"return_statements","content":{"body":""},"description":"Avoid too many `return` statements within this function.","location":{"path":"lib/parser.js","lines":{"begin":47,"end":47}},"other_locations":[],"remediation_points":300000,"severity":"major","type":"issue","engine_name":"structure","fingerprint":"3e5e98cdcba8196f5b12dfdad720bf15"},{"categories":["Complexity"],"check_name":"return_statements","content":{"body":""},"description":"Avoid too many `return` statements within this function.","location":{"path":"lib/error.js","lines":{"begin":20,"end":20}},"other_locations":[],"remediation_points":300000,"severity":"major","type":"issue","engine_name":"structure","fingerprint":"4817974afd7e0907cec853ce7a62130c"},{"type":"issue","check_name":"similar-code","description":"Similar blocks of code found in 2 locations. Consider refactoring.","categories":["Duplication"],"location":{"path":"lib/api.js","lines":{"begin":158,"end":162}},"remediation_points":750000,"other_locations":[{"path":"lib/api.js","lines":{"begin":164,"end":168}}],"content":{"body":"## Duplicated Code\n\nDuplicated code can lead to software that is hard to understand and difficult to change. The Don't Repeat Yourself (DRY) principle states:\n\n> Every piece of knowledge must have a single, unambiguous, authoritative representation within a system.\n\nWhen you violate DRY, bugs and maintenance problems are sure to follow. Duplicated code has a tendency to both continue to replicate and also to diverge (leaving bugs as two similar implementations differ in subtle ways).\n\n## Tuning\n\n**This issue has a mass of 75**.\n\nWe set useful threshold defaults for the languages we support but you may want to adjust these settings based on your project guidelines.\n\nThe threshold configuration represents the minimum [mass](https://docs.codeclimate.com/docs/duplication#mass) a code block must have to be analyzed for duplication. The lower the threshold, the more fine-grained the comparison.\n\nIf the engine is too easily reporting duplication, try raising the threshold. If you suspect that the engine isn't catching enough duplication, try lowering the threshold. The best setting tends to differ from language to language.\n\nSee [`codeclimate-duplication`'s documentation](https://docs.codeclimate.com/docs/duplication) for more information about tuning the mass threshold in your `.codeclimate.yml`.\n\n## Refactorings\n\n* [Extract Method](http://sourcemaking.com/refactoring/extract-method)\n* [Extract Class](http://sourcemaking.com/refactoring/extract-class)\n* [Form Template Method](http://sourcemaking.com/refactoring/form-template-method)\n* [Introduce Null Object](http://sourcemaking.com/refactoring/introduce-null-object)\n* [Pull Up Method](http://sourcemaking.com/refactoring/pull-up-method)\n* [Pull Up Field](http://sourcemaking.com/refactoring/pull-up-field)\n* [Substitute Algorithm](http://sourcemaking.com/refactoring/substitute-algorithm)\n\n## Further Reading\n\n* [Don't Repeat Yourself](http://c2.com/cgi/wiki?DontRepeatYourself) on the C2 Wiki\n* [Duplicated Code](http://sourcemaking.com/refactoring/duplicated-code) on SourceMaking\n* [Refactoring: Improving the Design of Existing Code](http://www.amazon.com/Refactoring-Improving-Design-Existing-Code/dp/0201485672) by Martin Fowler. _Duplicated Code_, p76\n"},"fingerprint":"18a4365e60b432a9f2fc2fd4f1d679e6","severity":"major","engine_name":"duplication"},{"type":"issue","check_name":"similar-code","description":"Similar blocks of code found in 2 locations. Consider refactoring.","categories":["Duplication"],"location":{"path":"lib/api.js","lines":{"begin":164,"end":168}},"remediation_points":750000,"other_locations":[{"path":"lib/api.js","lines":{"begin":158,"end":162}}],"content":{"body":"## Duplicated Code\n\nDuplicated code can lead to software that is hard to understand and difficult to change. The Don't Repeat Yourself (DRY) principle states:\n\n> Every piece of knowledge must have a single, unambiguous, authoritative representation within a system.\n\nWhen you violate DRY, bugs and maintenance problems are sure to follow. Duplicated code has a tendency to both continue to replicate and also to diverge (leaving bugs as two similar implementations differ in subtle ways).\n\n## Tuning\n\n**This issue has a mass of 75**.\n\nWe set useful threshold defaults for the languages we support but you may want to adjust these settings based on your project guidelines.\n\nThe threshold configuration represents the minimum [mass](https://docs.codeclimate.com/docs/duplication#mass) a code block must have to be analyzed for duplication. The lower the threshold, the more fine-grained the comparison.\n\nIf the engine is too easily reporting duplication, try raising the threshold. If you suspect that the engine isn't catching enough duplication, try lowering the threshold. The best setting tends to differ from language to language.\n\nSee [`codeclimate-duplication`'s documentation](https://docs.codeclimate.com/docs/duplication) for more information about tuning the mass threshold in your `.codeclimate.yml`.\n\n## Refactorings\n\n* [Extract Method](http://sourcemaking.com/refactoring/extract-method)\n* [Extract Class](http://sourcemaking.com/refactoring/extract-class)\n* [Form Template Method](http://sourcemaking.com/refactoring/form-template-method)\n* [Introduce Null Object](http://sourcemaking.com/refactoring/introduce-null-object)\n* [Pull Up Method](http://sourcemaking.com/refactoring/pull-up-method)\n* [Pull Up Field](http://sourcemaking.com/refactoring/pull-up-field)\n* [Substitute Algorithm](http://sourcemaking.com/refactoring/substitute-algorithm)\n\n## Further Reading\n\n* [Don't Repeat Yourself](http://c2.com/cgi/wiki?DontRepeatYourself) on the C2 Wiki\n* [Duplicated Code](http://sourcemaking.com/refactoring/duplicated-code) on SourceMaking\n* [Refactoring: Improving the Design of Existing Code](http://www.amazon.com/Refactoring-Improving-Design-Existing-Code/dp/0201485672) by Martin Fowler. _Duplicated Code_, p76\n"},"fingerprint":"18a4365e60b432a9f2fc2fd4f1d679e6","severity":"major","engine_name":"duplication"}] |
124
lib/api.js
const assert = require('assert'); | ||
const { METHODS } = require('http'); | ||
const { pathToRegexp } = require('path-to-regexp'); | ||
const cookieSignature = require('cookie-signature'); | ||
@@ -9,4 +8,29 @@ | ||
const PRG_OPTS = { sensitive: true, strict: true }; | ||
function pathToRegexp(path){ | ||
let r = { params: [] }; | ||
let regexp = ''; | ||
path.split('/').forEach(seg => { | ||
if(!seg) | ||
return; | ||
if(seg[0] == ':'){ | ||
r.params.push(seg.substr(1)); | ||
regexp += '\\/([\\w\\d\\-\\._~]+)'; | ||
return; | ||
} | ||
if(seg[0] == '('){ | ||
regexp += seg; | ||
r.params.push('path'); | ||
return; | ||
} | ||
regexp += '\\/' + seg; | ||
}); | ||
r.regexp = new RegExp(regexp); | ||
return r; | ||
} | ||
function normalizeHandler(func){ | ||
@@ -35,2 +59,3 @@ if(func.constructor.name === 'AsyncFunction') | ||
// this => API | ||
let route = method + ' ' + path; | ||
@@ -44,3 +69,3 @@ if(route in this.static) | ||
if(match){ | ||
r.params.forEach( (p, i) => params[p.name] = match[i + 1]); | ||
r.params.forEach( (p, i) => params[p] = match[i + 1]); | ||
return r.handler; | ||
@@ -53,3 +78,3 @@ } | ||
function runHandler(input, handler){ | ||
function runHandler(input, handler, done){ | ||
@@ -60,4 +85,4 @@ if(input.res.stackAborted) | ||
input.next = handler.next | ||
? () => runHandler(input, handler.next) | ||
: () => input.log.warn({ type: 'route' }, 'next() called after stack already came to an end'); | ||
? () => runHandler(input, handler.next, done) | ||
: () => done(); | ||
@@ -67,7 +92,7 @@ handler(input).catch(err => handleError(err, input)); | ||
function generateResponseObject(method, url){ | ||
function generateResponseObject(method, url, req){ | ||
return { | ||
headers: {}, | ||
req: { url, method }, | ||
req, | ||
statusCode: 200, | ||
@@ -95,2 +120,8 @@ end(body){ | ||
function generateRequestObject(method, path, input){ | ||
let obj = { method, path }; | ||
input.headers && Object.assign(obj, input.headers); | ||
return obj; | ||
} | ||
function parseSignedCookies(cconf, input){ | ||
@@ -116,8 +147,2 @@ for(let key in input.cookies) | ||
function moveAllPathParam({ params, next }){ | ||
params.path = params['0']; | ||
delete params['0']; | ||
next(); | ||
} | ||
module.exports = class API { | ||
@@ -139,5 +164,17 @@ | ||
proxy.all = (...chain) => METHODS.forEach(m => | ||
this.addEndpoint(m.toLowerCase(), '(.*)', moveAllPathParam, ...chain)); | ||
this.addEndpoint(m.toLowerCase(), '(.*)', ...chain)); | ||
spec.apply(context, [ proxy ]); | ||
proxy.pre = (...chain) => { | ||
let stack = buildStack(this.context, chain); | ||
this.preHook = stack[0]; | ||
stack.slice(-1)[0].tail = true; | ||
}; | ||
proxy.pos = (...chain) => { | ||
let stack = buildStack(this.context, chain); | ||
this.posHook = stack[0]; | ||
stack.slice(-1)[0].tail = true; | ||
}; | ||
spec.call(context, proxy); | ||
} | ||
@@ -160,15 +197,11 @@ | ||
if(!/[:?+*]/.test(path)) | ||
if(path.indexOf('/:') < 0 && path.indexOf('*') < 0) | ||
return this.static[route] = stack[0]; | ||
let params = []; | ||
this.dynamic[m] = this.dynamic[m] || []; | ||
this.dynamic[m].push({ | ||
regexp: pathToRegexp(path, params, PRG_OPTS), | ||
handler: stack[0], | ||
params | ||
}); | ||
let { regexp, params } = pathToRegexp(path); | ||
this.dynamic[m].push({ regexp, handler: stack[0], params }); | ||
} | ||
trigger(method, path, input){ | ||
async trigger(method, path, input = {}){ | ||
method = method.toUpperCase(); | ||
@@ -178,33 +211,38 @@ let params = {}; | ||
let app = this.context; | ||
app.log.debug({ type: 'request' }, 'Received %s request for %s', method, path); | ||
let handler = matchRoute.apply(this, [ method, path, params ]); | ||
let res = generateResponseObject(method, path); | ||
input = { | ||
...app.global, conf: app.conf, res, flash: {}, cookies: {}, | ||
headers: {}, query: {}, ...input, params, log: app.log | ||
...app.global, conf: app.conf, flash: {}, cookies: {}, headers: {}, | ||
query: {}, ...input, params, log: app.log, signedCookies: {} | ||
}; | ||
input.fork = fork.bind(app, input); | ||
Object.assign(input.res, resMethods); | ||
let req = input.req = input.req || generateRequestObject(method, path, input); | ||
let res = input.res = input.res || generateResponseObject(method, path, req); | ||
res.req = req; | ||
res.input = input; | ||
Object.assign(res, resMethods); | ||
input.res.input = input; | ||
app.log.debug({ req }); | ||
let handler = matchRoute.call(this, method, path, params); | ||
if(app.conf.cookie) | ||
input.res.cookieSecret = app.conf.cookie.secret; | ||
input.signedCookies = {}; | ||
res.cookieSecret = app.conf.cookie.secret; | ||
parseSignedCookies(app.conf.cookie, input); | ||
let masterPromise = new Promise(resolve => { | ||
input.res.routeEnded = resolve; | ||
}); | ||
let masterPromise = new Promise(done => { res.routeEnded = done }); | ||
if(!handler) | ||
input.res.status(404).end(); | ||
else | ||
runHandler(input, handler); | ||
if(!handler){ | ||
res.status(404).end(); | ||
return masterPromise; | ||
} | ||
this.preHook && await new Promise(done => runHandler(input, this.preHook, done)); | ||
let warn = () => app.log.warn({ type: 'route' }, | ||
'next() was called when the chain is finished'); | ||
runHandler(input, handler, this.posHook | ||
? () => runHandler(input, this.posHook, warn) : warn); | ||
return masterPromise; | ||
@@ -211,0 +249,0 @@ } |
@@ -1,2 +0,1 @@ | ||
const { URL } = require('url'); | ||
const cookie = require('cookie'); | ||
@@ -9,49 +8,21 @@ const querystring = require('querystring'); | ||
function forMiddleware(mw, req, res){ | ||
return new Promise((done, error) => { | ||
try{ | ||
mw(req, res, done); | ||
} | ||
catch(e){ | ||
/* istanbul ignore next */ | ||
error(e); | ||
} | ||
}); | ||
} | ||
async function handleRequest(req, res){ | ||
// this => app | ||
function handleCORS(app, req, res){ | ||
return forMiddleware(app._cors, req, res); | ||
} | ||
if(req.method == 'OPTIONS') | ||
return this._cors(req, res); | ||
else if(this.conf.cors) | ||
await new Promise(done => this._cors(req, res, done)); | ||
async function prepareHandling(app, req, res){ | ||
req.hasBody = Boolean(req.headers['content-length']); | ||
if(app._shouldParseBody && req.hasBody) | ||
req.body = await parseBody.apply(app, [req]); | ||
await forMiddleware(app._compress, req, res); | ||
let [ path, query ] = req.url.split('?'); | ||
req.path = normalizePath(path); | ||
req.cookies = cookie.parse(req.headers.cookie || ''); | ||
req.query = querystring.parse(query); | ||
if(app.conf.cors) | ||
await handleCORS(app, req, res); | ||
} | ||
req.hasBody = Boolean(req.headers['content-length']); | ||
if(this._shouldParseBody && req.hasBody) | ||
req.body = await parseBody.call(this, req); | ||
async function handleRequest(req, res){ | ||
// this => app | ||
let url = new URL(req.url, 'http://0.0.0.0'); | ||
req.path = normalizePath(url.pathname); | ||
req.params = {}; | ||
res.req = req; | ||
res.on('finish', () => this.log.debug({ res })); | ||
if(req.method == 'OPTIONS') | ||
return handleCORS(this, req, res); | ||
await prepareHandling(this, req, res); | ||
req.flash = {}; | ||
req.query = querystring.parse(url.search.slice(1)); | ||
await this._api.trigger(req.method, req.path, { | ||
@@ -58,0 +29,0 @@ query: req.query, req, res, headers: req.headers, body: req.body, |
@@ -6,4 +6,3 @@ const | ||
assert = require('assert'), | ||
Confort = require('confort'), | ||
compression = require('compression'); | ||
confort = require('confort'); | ||
@@ -61,11 +60,10 @@ const { startServer } = require('./http'); | ||
constructor(opts = {}){ | ||
validateOpts.apply(this, [ opts ]); | ||
validateOpts.call(this, opts); | ||
// TODO sha1 of host+time+name to identify app | ||
this._confort = new Confort(); | ||
this._shouldParseBody = opts.shouldParseBody || typeof opts.shouldParseBody == 'undefined'; | ||
this._alwaysRebuildAPI = opts.alwaysRebuildAPI || false; | ||
this.conf = this._confort.object; | ||
this.conf = confort({}); | ||
this.running = false; | ||
@@ -81,7 +79,4 @@ this.stopped = Promise.resolve(true); | ||
setup(objectOrPath){ | ||
this._confort.addLayer(objectOrPath || {}); | ||
this.conf = this._confort.object; | ||
this.conf = confort(this.conf, objectOrPath || {}); | ||
this._cors = cors(this.conf.cors); | ||
this._compress = compression(); | ||
@@ -125,3 +120,3 @@ if(this.conf.log) | ||
if(this.conf.port) | ||
await startServer.apply(this); | ||
await startServer.call(this); | ||
else | ||
@@ -128,0 +123,0 @@ this.log.info({ type: 'app' }, '%s v%s has started', this._name, this._version); |
@@ -86,6 +86,9 @@ const { sign } = require('cookie-signature'); | ||
} | ||
else if(message == null) | ||
type = null; | ||
else | ||
message = String(message); | ||
this.type(type).end(message); | ||
type && this.type(type); | ||
this.end(message); | ||
@@ -128,3 +131,3 @@ this.stackAborted = true; | ||
module.exports[name] = function(...args){ | ||
assert.apply(this, [ ASSERTS[name], ...args ]); | ||
assert.call(this, ASSERTS[name], ...args); | ||
} | ||
@@ -131,0 +134,0 @@ |
{ | ||
"name": "nodecaf", | ||
"version": "0.11.3", | ||
"version": "0.11.4", | ||
"description": "Nodecaf is a light framework for developing RESTful Apps in a quick and convenient manner.", | ||
@@ -19,4 +19,2 @@ "main": "lib/main.js", | ||
"config", | ||
"ssl", | ||
"https", | ||
"promises", | ||
@@ -41,4 +39,3 @@ "async", | ||
"busboy": "^0.3.1", | ||
"compression": "^1.7.4", | ||
"confort": "^0.1.4", | ||
"confort": "^0.2.0", | ||
"content-type": "^1.0.4", | ||
@@ -48,6 +45,4 @@ "cookie": "^0.4.1", | ||
"cors": "^2.8.5", | ||
"golog": "^0.3.1", | ||
"path-to-regexp": "^6.1.0", | ||
"raw-body": "^2.4.1", | ||
"stdout-stream": "^1.4.1" | ||
"golog": "^0.4.0", | ||
"raw-body": "^2.4.1" | ||
}, | ||
@@ -54,0 +49,0 @@ "devDependencies": { |
@@ -202,5 +202,8 @@ const assert = require('assert'); | ||
it('Should load form file when path is sent', () => { | ||
const fs = require('fs'); | ||
fs.writeFileSync(__dirname + '/a.toml', 'key = "value"', 'utf-8'); | ||
let app = new Nodecaf({ conf: { key: 'valueOld' } }); | ||
app.setup('test/res/conf.toml'); | ||
app.setup(__dirname + '/a.toml'); | ||
assert.strictEqual(app.conf.key, 'value'); | ||
fs.unlink(__dirname + '/a.toml', Function.prototype); | ||
}); | ||
@@ -245,3 +248,3 @@ | ||
assert.strictEqual(r.status, 200); | ||
let res = await app.trigger('post', '/foo'); | ||
let res = await app.trigger('post', '/foo', { headers: { host: 'what.com' } }); | ||
assert.strictEqual(res.headers['X-Test'], 'Foo'); | ||
@@ -252,2 +255,48 @@ await app.stop(); | ||
}); | ||
describe('#pre', () => { | ||
it('Should run hook before any routes', async () => { | ||
let c = 0; | ||
let app = new Nodecaf({ | ||
api({ post, pre }){ | ||
pre( | ||
({ next }) => { c++; next() }, | ||
({ next }) => { c++; next() } | ||
); | ||
post('/foo', ({ res }) => res.end()); | ||
post('/bar', ({ res }) => res.end()); | ||
} | ||
}); | ||
await app.start(); | ||
await app.trigger('post', '/foo'); | ||
assert.strictEqual(c, 2); | ||
await app.trigger('post', '/bar'); | ||
assert.strictEqual(c, 4); | ||
await app.stop(); | ||
}); | ||
}); | ||
describe('#pos', () => { | ||
it('Should run hook before any routes', async () => { | ||
let c = {}; | ||
let app = new Nodecaf({ | ||
api({ post, pos }){ | ||
pos( | ||
({ next }) => { c++; next() }, | ||
({ res }) => { c++; res.end() } | ||
); | ||
post('/foo', ({ next }) => { c = 0; next() }); | ||
} | ||
}); | ||
await app.start(); | ||
await app.trigger('post', '/foo'); | ||
assert.strictEqual(c, 2); | ||
await app.stop(); | ||
}); | ||
}); | ||
}); | ||
@@ -541,7 +590,9 @@ | ||
fs.writeFileSync(__dirname + '/file.txt', 'filefoobar\r\n', 'utf-8'); | ||
let form = new FormData(); | ||
form.append('foo', 'bar'); | ||
form.append('foobar', fs.createReadStream('./test/res/file.txt')); | ||
form.append('foobar', fs.createReadStream(__dirname + '/file.txt')); | ||
await new Promise(done => form.submit(LOCAL_HOST + '/bar/', (err, res) => { | ||
assert(res.headers['x-test'] == 'file.txt'); | ||
fs.unlink(__dirname + '/file.txt', Function.prototype); | ||
done(); | ||
@@ -760,3 +811,3 @@ })); | ||
fs.readdir('.', function(){ | ||
res.error(404, 'errfoobar'); | ||
res.error(404, true); | ||
}); | ||
@@ -856,2 +907,18 @@ }); | ||
it('Should NOT send reponse body when assertion has no message', async () => { | ||
let app = new Nodecaf({ | ||
conf: { port: 80 }, | ||
api({ get }){ | ||
get('/foo', function({ res }){ | ||
res.unauthorized(true); | ||
}); | ||
} | ||
}); | ||
await app.start(); | ||
let { headers, body } = await base.get('foo'); | ||
assert(!headers['content-type']); | ||
assert.strictEqual(body.length, 0); | ||
await app.stop(); | ||
}); | ||
}); | ||
@@ -877,2 +944,16 @@ | ||
it('Should not send CORS headers when setup so [cors]', async () => { | ||
let app = new Nodecaf({ | ||
conf: { port: 80 }, | ||
api({ get }){ | ||
get('/foobar', ({ res }) => res.end() ); | ||
} | ||
}); | ||
await app.start(); | ||
const { assert } = await base.get('foobar', { 'Origin': 'http://outsider.com' }); | ||
assert.status.is(200); | ||
assert.headers.match('access-control-allow-origin', undefined); | ||
await app.stop(); | ||
}); | ||
it('Should store data to be accessible to all handlers [app.global]', async () => { | ||
@@ -879,0 +960,0 @@ let app = new Nodecaf({ |
Sorry, the diff of this file is not supported yet
104096
8.26%8
-27.27%1530
7.22%18
-21.74%6
20%+ Added
+ Added
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
- Removed
Updated
Updated