-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: Respect req.accept header. Support application/json and text/pl…
…ain.
- Loading branch information
Showing
1 changed file
with
35 additions
and
15 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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") | ||
} |