Skip to content

Instantly share code, notes, and snippets.

@shcyiza
Last active February 17, 2020 09:57
Show Gist options
  • Save shcyiza/fa8f2678d88e41b8ba8cdde725cc85ba to your computer and use it in GitHub Desktop.
Save shcyiza/fa8f2678d88e41b8ba8cdde725cc85ba to your computer and use it in GitHub Desktop.
express api json resposder
'use strict'
/*
* API middleware
*
* Adds shortcut methods for JSON API responses (inspired by KeystoneJS) :
*
* `res.apiResponse(data)`
* `res.apiError(key, err, msg, code)`
* `res.apiNotFound(err, msg)`
* `res.apiNotAllowed(err, msg)`
*/
const winston = require('winston')
const logger = new winston.createLogger({
transports: [
new winston.transports.Console({
timestamp: true,
level: 'debug',
handleExceptions: true,
json: false,
colorize: true
})
],
exitOnError: false
})
logger.stream = {
write: (message) => logger.debug(message.replace(/\n$/, ''))
}
const initAPI = (req, res, next) => {
// Utility methods
res.apiResponse = data => {
if (req.query.callback) {
res.jsonp(data)
} else {
res.json(data)
}
}
res.apiError = (status, err, info) => {
if (err) {
const ip = (req.ip) ? req.ip : 'anonymous'
logger.error(
`user=${ip} - method=${req.method} - url=`
+ `${req.originalUrl} - status=${status} - message=${err.message}`,
{ error: err }
)
}
res.status(status || 500)
res.apiResponse({
success: false,
message: err.message || info
})
}
// Handler for HTTP response codes : errors
res.apiNotFound = (err, info) => {
res.apiError(404, err, info || 'Data not found')
}
res.apiBadRequest = (err, info) => {
res.apiError(400, err, info || 'Bad request')
}
res.apiUnauthorized = (err, info) => {
res.apiError(401, err, info || 'Unauthorized operation')
}
res.apiForbidden = (err, info) => {
res.apiError(403, err, info || 'Request forbidden')
}
res.apiNotAllowedMethod = (err, info) => {
res.apiError(405, err, info || 'Method not allowed')
}
next()
}
module.exports = { initAPI }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment