UNPKG

@lingua/response-payload

Version:

Node.js module for generating response payloads for server requests to ensure uniform responses

68 lines (55 loc) 1.59 kB
Node.js module for generating response payloads for server requests to ensure uniform responses ```bash $ npm install @lingua/response-payload ``` #### Usage ```javascript const ResponsePayload = require('@lingua/response-payload'); http.createServer((req, res) => { const response = new ResponsePayload(req, res); try { doSomething(); response.setPayload({ message: 'Hi' }); res.writeHead(200, {'content-type': 'application/json'}); } catch (err) { response.addError(err).captureStacktrace(err); res.writeHead(500, {'content-type': 'application/json'}); } res.end(JSON.stringify(response)); }); ``` Example response: ```json { "url": "http://example.com/", "timestamp": "2016-12-29T06:35:55.029Z", "errors": [ "Something went wrong" ], "payload": { "message": "Hi" }, "stacktrace": [ "at repl:1:2", "at realRunInThisContextScript (vm.js:22:35)", "at sigintHandlersWrap (vm.js:98:12)", "at ContextifyScript.Script.runInThisContext (vm.js:24:12)", "at REPLServer.defaultEval (repl.js:346:29)", "at bound (domain.js:280:14)", "at REPLServer.runBound [as eval] (domain.js:293:12)", "at REPLServer.onLine (repl.js:545:10)", "at emitOne (events.js:101:20)", "at REPLServer.emit (events.js:188:7)" ] } ``` Config: ```javascript ResponsePayload.config = { // Should a stacktrace be included in the response includeStacktrace: false, // Should included stacktraces be parsed out (requires the @lingua/debug-stack optional dependency) parseStacktrace: false }; ```