Skip to content

Commit

Permalink
feat: Respect req.accept header. Support application/json and text/pl…
Browse files Browse the repository at this point in the history
…ain.
  • Loading branch information
andreidmt committed Feb 18, 2020
1 parent ec7cd3a commit 0b1494d
Showing 1 changed file with 35 additions and 15 deletions.
50 changes: 35 additions & 15 deletions src/middleware/res-goodbye.js
Original file line number Diff line number Diff line change
@@ -1,26 +1,46 @@
const debug = require("debug")("Blocks:GoodbyeMiddleware")

import { forEach, is } from "@mutantlove/m"
import { get, isEmpty } from "@mutantlove/m"
import accepts from "accepts"

const toNowInMs = start => {
const end = process.hrtime(start)

return end[0] * 1000 + end[1] / 1000000
}

const bodyByAccept = ({ accept, res }) => {
const payload = get(["ctx", "payload"])(res)

switch (accept.type(["json", "text"])) {
case "json":
res.setHeader("Content-Type", "application/json")

return JSON.stringify(isEmpty(payload) ? {} : payload)
default:
// the fallback is text/plain, so no need to specify it above
res.setHeader("Content-Type", "text/plain")

return isEmpty(payload) ? "" : payload
}
}

module.exports = () => (req, res) => {
debug(`${req.method}:${req.url} responding with ${res.ctx.status}`)

const payload = is(res.ctx.payload) ? res.ctx.payload : {}
const isObject = typeof payload === "object"
const endAt = process.hrtime(req.ctx.startAt)
const body = bodyByAccept({
accept: accepts(req),
res,
})
const startAt = get(["ctx", "startAt"])(req)
const status = get(["ctx", "status"])(res)

const body = isObject ? JSON.stringify(payload) : payload
const contentType = isObject
? "application/json; charset=utf-8"
: "text/plain; charset=utf-8"
// time to respond in miliseconds
res.setHeader("X-Response-Time", `${toNowInMs(startAt)} ms`)

forEach(([name, value]) => res.setHeader(name, value))([
// from the first middleware to now
["X-Response-Time", `${endAt[0]}s ${endAt[1] / 1000000}ms`],
["Content-Type", contentType],
["Content-Length", Buffer.byteLength(body, "utf8")],
])
// count the number of octets, not chars
res.setHeader("Content-Length", Buffer.byteLength(body, "utf8"))

res.writeHead(res.ctx.status)
res.writeHead(status)
res.end(body, "utf8")
}

0 comments on commit 0b1494d

Please sign in to comment.