Skip to content

Instantly share code, notes, and snippets.

@jackinf
Created September 12, 2018 09:31
Show Gist options
  • Save jackinf/26498316c7f5a9c94f38485746d270d6 to your computer and use it in GitHub Desktop.
Save jackinf/26498316c7f5a9c94f38485746d270d6 to your computer and use it in GitHub Desktop.
Json-Server helper files
'use strict'
module.exports = (req, res, next) => {
const _send = res.send
res.send = function (body) {
if (require('url').parse(req.originalUrl, true).query['singular']) {
try {
const json = JSON.parse(body)
if (Array.isArray(json)) {
if (json.length === 1) {
return _send.call(this, JSON.stringify(json[0]))
} else if (json.length === 0) {
return _send.call(this, '{}', 404)
}
}
} catch (e) {}
}
return _send.call(this, body)
}
next()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment