forked from koajs/joi-router
-
Notifications
You must be signed in to change notification settings - Fork 0
/
helpers.ts
241 lines (206 loc) · 5.19 KB
/
helpers.ts
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
import {
Spec,
ValidatorBuilder,
IRange,
IValidateObject,
IValidationError,
Validator,
ContextExtension,
} from './types'
import { Middleware } from '@koa/router'
import { Context } from 'koa'
import assert from 'assert'
import * as parse from 'co-body'
import { OutputValidator } from './output-validator'
type InputProp = 'header' | 'query' | 'params' | 'body'
export async function identityValidator<Schema>(
validator: Schema
): Promise<Validator> {
// @ts-ignore
return validator
}
/**
* Handles parser internal errors
* @param {Object} spec
* @param {function} parsePayload
* @return {async function}
* @api private
*/
function wrapError<Meta, Schema>(
spec: Spec<Meta, Schema>,
parsePayload: any
): Middleware {
return async function errorHandler(ctx, next) {
try {
await parsePayload(ctx, next)
} catch (err) {
captureError(ctx, 'type', err)
if (spec.validate?.continueOnError) {
return await next()
} else {
return ctx.throw(err as any)
}
}
}
}
/**
* Creates JSON body parser middleware.
*
* @param {Object} spec
* @return {async function}
* @api private
*/
function makeJSONBodyParser<Meta, Schema>(
spec: Spec<Meta, Schema>
): Middleware {
const opts = spec?.validate?.jsonOptions ?? {}
opts.limit = opts.limit ?? spec?.validate?.maxBody
return async function parseJSONPayload(ctx, next) {
if (!ctx.request.is('json')) {
ctx.throw(400, 'expected json')
return
}
// eslint-disable-next-line require-atomic-updates
// @ts-ignore
ctx.request.body = ctx.request.body ?? (await parse.json(ctx, opts))
await next()
}
}
/**
* Creates body parser middleware.
*
* @param {Object} spec
* @return {async function}
* @api private
*/
export function makeBodyParser<Meta, Schema>(spec: Spec<Meta, Schema>) {
if (!spec.validate) return null
if (!spec.validate.type && spec.validate.body) {
throw new Error(
`Body type is not present in the 'validate' field. Possible values are: 'json'`
)
}
switch (spec.validate.type) {
case 'json':
return wrapError(spec, makeJSONBodyParser(spec))
case 'form':
case 'stream':
case 'multipart':
default:
return null
}
}
export function injectSpec<Meta, Schema>(
spec: Spec<Meta, Schema>
): Middleware<any, ContextExtension<Meta, Schema>> {
return async (ctx, next) => {
ctx.spec = spec
await next()
}
}
/**
* @api private
*/
function captureError(ctx: Context, type: string, err: any) {
// expose Error message to JSON.stringify()
err.msg = err.message
if (!ctx.invalid) ctx.invalid = {}
ctx.invalid[type] = err
}
/**
* Creates validator middleware.
*
* @param {Object} spec
* @return {async function}
* @api private
*/
export function makeValidator<Meta, Schema>(
spec: Spec<Meta, Schema>,
validatorBuilder: ValidatorBuilder<Schema>
): Middleware {
const inputProps = ['header', 'query', 'params', 'body'] as const
const outputValidator = spec.validate?.output
? new OutputValidator(spec.validate?.output)
: null
return async function validator(ctx, next) {
if (!spec.validate) return await next()
let err: IValidationError
for (let prop of inputProps) {
if (spec.validate[prop]) {
err = await validateInput(prop, ctx, spec.validate, validatorBuilder)
if (err) {
captureError(ctx, prop, err)
if (!spec.validate.continueOnError) return ctx.throw(err)
}
}
}
await next()
if (outputValidator) {
err = await outputValidator.validate(ctx, validatorBuilder)
if (err) {
err.status = 500
return ctx.throw(err)
}
}
}
}
/**
* Validates request[prop] data with the defined validation schema.
*
* @param {String} prop
* @param {koa.Request} request
* @param {Object} validate
* @returns {Error|undefined}
* @api private
*/
async function validateInput<Schema>(
prop: InputProp,
ctx: Context,
validate: IValidateObject<Schema>,
validatorBuilder: ValidatorBuilder<Schema>
) {
const validatorSchema = validate[prop]
if (validatorSchema) {
const validatedValue =
prop === 'params' ? ctx.params : (ctx.request as any)[prop]
const validator = await validatorBuilder(validatorSchema)
const result = await validator(validatedValue)
if (result.error) {
result.error.status = validate.failure ?? 400
return result.error
}
// update our request w/ the casted values
switch (prop) {
case 'header': // request.header is getter only, cannot set it
case 'query': // setting request.query directly causes casting back to strings
Object.keys(result.value).forEach((key) => {
ctx.request[prop][key] = result.value[key]
})
break
case 'params':
ctx.params = result.value
break
default:
// @ts-ignore
ctx.request[prop] = result.value
}
}
}
function validateCode(code: string) {
assert(
/^[1-5][0-9]{2}$/.test(code),
'invalid status code: ' + code + ' must be between 100-599'
)
}
export function rangify(rule: string): IRange {
if (rule === '*') {
return { lower: 0, upper: Infinity }
}
const parts = rule.split('-')
assert(parts.length && parts.length < 3, 'invalid status code: ' + rule)
const lower = parts[0]
const upper = parts.length === 2 ? parts[1] : lower
validateCode(lower)
validateCode(upper)
return { lower: parseInt(lower, 10), upper: parseInt(upper, 10) }
}