-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
85 lines (73 loc) · 2.06 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
/*!
* koa-better-response-handler
*
* Copyright(c) 2021-2022 Imed Jaberi
* MIT Licensed
*/
'use strict'
/**
* Module dependencies.
*/
const _isJSON = require('koa-is-json')
/**
* Expose `responseHandler()`.
*/
module.exports = responseHandler
/**
* Same response methods like `express`
*
* @api public
*/
function responseHandler (options = {}) {
// customize you json validation function.
const isJSON = options.isJSON || _isJSON
// default func used when we don't find requested method in ctx.
const defaultNotImplMethods = (method, mwModule) => () => {
throw new Error(
`Can not find the ${method} method inside the context. \n` +
`Make sure that you load the '${mwModule}' module first.`
)
}
return (ctx, next) => {
const responseFactoryObject = {
// all header handlers like append, set,
// get, remove are available by default.
// // status handler. (--- inspired from fastify ---)
// code (code) {
// this.status = code
// return this
// },
// status handler.
statusCode (code) {
this.status = code
return this
},
// sendStatus handler.
sendStatus () {
this.body = this.message
},
// send handler.
send (data) {
this.body = data
},
// json handler.
json (data) {
// validate the isJSON method.
if (typeof isJSON !== 'function') throw new Error('`isJSON` option should be a function.')
if (!isJSON(data)) this.throw(500, 'please use a valid json response.')
this.body = data
},
// jsonp handler (integrate with koa-safe-jsonp)..
jsonp: !ctx.render
? defaultNotImplMethods('jsonp', 'koa-safe-jsonp')
: ctx.jsonp,
// render handler (integrate with koa-views).
render: !ctx.render
? defaultNotImplMethods('render', 'koa-views')
: ctx.render
}
// append all response methods to ctx and ctx.response.
Object.assign(ctx, Object.assign(ctx.response, responseFactoryObject))
return next()
}
}