Browse Source

Flatten send() (#143)

* Flatten send()

* Remove onerror parameter from run()
master
Tim Neutkens 8 years ago
committed by Leo Lamprecht
parent
commit
033f2e3182
  1. 81
      lib/server.js

81
lib/server.js

@ -10,7 +10,7 @@ const DEV = 'development' === process.env.NODE_ENV
const TESTING = 'test' === process.env.NODE_ENV
const serve = fn => server((req, res) => {
run(req, res, fn, sendError)
run(req, res, fn)
})
module.exports = exports = serve
@ -21,7 +21,7 @@ exports.send = send
exports.sendError = sendError
exports.createError = createError
async function run(req, res, fn, onError) {
async function run(req, res, fn) {
try {
const val = await fn(req, res)
@ -35,7 +35,7 @@ async function run(req, res, fn, onError) {
send(res, res.statusCode || 200, val)
}
} catch (err) {
await onError(req, res, err)
await sendError(req, res, err)
}
}
@ -72,47 +72,50 @@ async function json(req, {limit = '1mb'} = {}) {
function send(res, code, obj = null) {
res.statusCode = code
if (null !== obj) {
if (Buffer.isBuffer(obj)) {
if (!res.getHeader('Content-Type')) {
res.setHeader('Content-Type', 'application/octet-stream')
}
if (null === obj) {
res.end()
return
}
if (Buffer.isBuffer(obj)) {
if (!res.getHeader('Content-Type')) {
res.setHeader('Content-Type', 'application/octet-stream')
}
res.setHeader('Content-Length', obj.length)
res.end(obj)
return
}
if (isStream(obj)) {
if (!res.getHeader('Content-Type')) {
res.setHeader('Content-Type', 'application/octet-stream')
}
obj.pipe(res)
return
}
let str = obj
res.setHeader('Content-Length', obj.length)
res.end(obj)
} else if (isStream(obj)) {
if (!res.getHeader('Content-Type')) {
res.setHeader('Content-Type', 'application/octet-stream')
}
if ('object' === typeof obj) {
// we stringify before setting the header
// in case `JSON.stringify` throws and a
// 500 has to be sent instead
obj.pipe(res)
// the `JSON.stringify` call is split into
// two cases as `JSON.stringify` is optimized
// in V8 if called with only one argument
if (DEV) {
str = JSON.stringify(obj, null, 2)
} else {
let str
if ('object' === typeof obj) {
// we stringify before setting the header
// in case `JSON.stringify` throws and a
// 500 has to be sent instead
// the `JSON.stringify` call is split into
// two cases as `JSON.stringify` is optimized
// in V8 if called with only one argument
if (DEV) {
str = JSON.stringify(obj, null, 2)
} else {
str = JSON.stringify(obj)
}
res.setHeader('Content-Type', 'application/json')
} else {
str = obj
}
res.setHeader('Content-Length', Buffer.byteLength(str))
res.end(str)
str = JSON.stringify(obj)
}
} else {
res.end()
res.setHeader('Content-Type', 'application/json')
}
res.setHeader('Content-Length', Buffer.byteLength(str))
res.end(str)
}
function sendError(req, res, {statusCode, message, stack}) {

Loading…
Cancel
Save