-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
38 lines (30 loc) · 1.04 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
'use strict'
const {json, createError} = require('micro')
const {StructError, Struct, validate} = require('superstruct')
const isStruct = x => x instanceof Struct
module.exports = opt => handler => async (request, response, ...restArgs) => {
if (isStruct(opt)) {
opt = {body: opt}
}
if (typeof opt !== 'object') {
throw createError(500, `micro-superstruct: Parameter must be a \`Struct\` or object, not ${typeof opt}`)
}
if (isStruct(opt.body)) {
const body = await json(request)
const [error] = validate(body, opt.body)
if (error instanceof StructError) {
throw createError(400, error.message, error)
}
request.body = body
}
if (isStruct(opt.query)) {
const {search} = new URL(request.url, `http:\\${request.headers.host}`)
const searchParameters = Object.fromEntries(new URLSearchParams(search))
const [error] = validate(searchParameters, opt.query)
if (error instanceof StructError) {
throw createError(400, error.message, error)
}
request.query = searchParameters
}
return handler(request, response, ...restArgs)
}