Responser
Simplify, standardize and format HTTP Status Code responses in JSON with express
No need to remember which is the code for each HTTP status anymore!
Responser provides a simple way to return standardized responses for each available HTTP status. It overwrites the express interface, making all methods accessible through your response
or res
variable.
Simple Usage
Install
Add responser with your favorite package manager:
yarn add responser
Typescript
Express response without the use of responser
:
import express, { Request, Response } from 'express'
const app = express()
const router = express.Router()
app.use(router)
router.get('/hello', (req: Request, res: Response) => {
res.status(400).json({
status: 'BAD_REQUEST',
code: 400,
message: 'Request is wrong!',
success: false
})
})
Now same code using responser
:
import responser from 'responser'
import express, { Request, Response } from 'express'
const app = express()
const router = express.Router()
app.use(responser)
app.use(router)
router.get('/hello', (req: Request, res: Response) => {
res.send_badRequest('Request is wrong!')
})
As you can see from the example above, using responser
makes code a bit cleaner and less error-prone.
Require (CommonJS) version:
const responser = require("responser").default
const express = require("express")
const app = express()
const router = express.Router()
app.use(responser)
app.use(router)
router.get('/hello', (req, res) => {
res.send_badRequest('Request is wrong!')
})
Input Parameters
All respose.send_*
methods accept two parameters:
(message: string, content?: any) => void
parameter | description | type | required |
---|
message | Human-readable message | string | yes |
content | Anything you would like to return | any | no |
Output Properties
property | description | type | e.g.1 | e.g.2 |
---|
code | HTTP Status Code | number | 200 | 400 |
status | HTTP Status Name | string | OK | BAD_REQUEST |
success | Success Flag | boolean | true | false |
data | content if success=true | any | { items: [] } | - |
errors | content if success=false | any | - | [{ err: "err1 text"}] |
Details
For each responser method,
When code
is < 300 (✅ successful):
- Property
success
will be true
content
given will be accessible as property data
When code
is >= 300 (❌ unsuccessful):
- Property
success
will be false
content
given will be accessible as property errors
List of Methods (method, code and status):
send_continue 100
send_switchingProtocols 101
send_processing 102
send_ok 200
send_created 201
send_accepted 202
send_nonAuthoritativeInformation 203
send_noContent 204
send_resetContent 205
send_partialContent 206
send_multiStatus 207
send_multipleChoices 300
send_movedPermanently 301
send_movedTemporarily 302
send_seeOther 303
send_notModified 304
send_useProxy 305
send_temporaryRedirect 307
send_permanentRedirect 308
send_badRequest 400
send_unauthorized 401
send_paymentRequired 402
send_forbidden 403
send_notFound 404
send_methodNotAllowed 405
send_notAcceptable 406
send_proxyAuthenticationRequired 407
send_requestTimeout 408
send_conflict 409
send_gone 410
send_lengthRequired 411
send_preconditionFailed 412
send_requestTooLong 413
send_requestUriTooLong 414
send_unsupportedMediaType 415
send_requestedRangeNotSatisfiable 416
send_expectationFailed 417
send_imATeapot 418
send_insufficientSpaceOnResource 419
send_methodFailure 420
send_unprocessableEntity 422
send_locked 423
send_failedDependency 424
send_preconditionRequired 428
send_tooManyRequests 429
send_requestHeaderFieldsTooLarge 431
send_unavailableForLegalReasons 451
send_internalServerError 500
send_notImplemented 501
send_badGateway 502
send_serviceUnavailable 503
send_gatewayTimeout 504
send_httpVersionNotSupported 505
send_insufficientStorage 507
send_networkAuthenticationRequired 511
Full example: Successful response
const express = require('express')
const responser = require('responser').default
const app = express()
const router = express.Router()
app.use(responser)
app.use(router)
router.get('/planets', (request, response, next) => {
const planets = ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune']
response.send_ok('Planets were found successfully', {
planets,
planetsCount: planets.length
})
})
app.listen(3000, () => console.log('Server running on port 3000'))
The route /planets
generates the following response to a GET request:
HTTP/1.1 200 OK
X-Powered-By: Express
Content-Type: application/json; charset=utf-8
{
"status": "OK",
"code": 200,
"success": true,
"message": "Planets were found successfully",
"data": {
"planets": [
"Mercury",
"Venus",
"Earth",
"Mars",
"Jupiter",
"Saturn",
"Uranus",
"Neptune"
],
"planetsCount": 8
}
}
Full example: Unsuccessful response
const express = require('express')
const responser = require('responser').default
const app = express()
const router = express.Router()
app.use(responser)
app.use(router)
router.post('/planets', (request, response, next) => {
const planetName = request.body?.name
let myErrors = []
if(!planetName) myErrors.push({
name: 'planetName',
message: 'Planet name was not given!'
})
if(myErrors.length) return response.send_badRequest(
'The request contains one or more errors!', myErrors
)
})
app.listen(3000, () => console.log('Server running on port 3000'))
Example response if planetName is not given on a POST request body.
HTTP/1.1 400 BAD REQUEST
X-Powered-By: Express
Content-Type: application/json; charset=utf-8
{
"status": "BAD_REQUEST",
"code": 400,
"success": false,
"message": "The request contains one or more errors!",
"errors": [
{
"name": "planetName",
"message": "Planet name was not given!"
}
]
}
Tip: if you would like a way to check all request variables automatically, consider using request-check. It will return an array of error messages for each field.
Testing
Run the test suit with yarn test
.
Contributing
If you want to contribute in any of theses ways:
- Give your ideas or feedback
- Question something
- Point out a problem or issue
- Enhance the code or its documentation
- Help in any other way
You can (and should) open an issue or even a pull request!
Thanks for your interest in contributing to this repo!
Author
Luiz Felipe Zarco (felipezarco@hotmail.com)
License
This code is licensed under the MIT License. See the LICENSE.md file for more info.