diff --git a/lib/backend/api/index.js b/lib/backend/api/index.js index edb4aa4..093cdb2 100755 --- a/lib/backend/api/index.js +++ b/lib/backend/api/index.js @@ -6,6 +6,29 @@ const auth = require('@screeps/backend/lib/game/api/auth') const authlib = require('@screeps/backend/lib/authlib') const _ = require('lodash') +/** + * Like legacy `q-json-response`, envelopes success as `{ ok: 1, ...data }`. + * Unlike it, does NOT call next() after responding: our routes shadow vanilla + * backend routes at the same paths, and falling through would execute the + * vanilla handler on an already-answered request (double side effects, and + * ERR_HTTP_HEADERS_SENT crashes in its tokenAuth). + */ +function jsonResponse (fn) { + return function (request, response) { + Promise.resolve() + .then(() => fn(request, response)) + .then((data) => { + response.json(_.extend({ ok: 1 }, data)) + }) + .catch((error) => { + if (error.stack) console.error(error.stack) + if (!response.headersSent) { + response.json({ error: String(error) }) + } + }) + } +} + module.exports = function (config) { const { common } = config const { db, env, pubsub } = common.storage