-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
173 lines (159 loc) · 4.12 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
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
const picosUtil = require('picos-util')
const pTime = require('pico-common').export('pico/time')
const pObj = require('pico-common').export('pico/obj')
const pStr = require('pico-common').export('pico/str')
const GROUPING = [['index', 'csv'], ['range', 'gte', 'lte'], ['time', 'start', 'end']]
const dummyNext = () => {}
const router = {}
async function pipeline(middlewares, i, data, next){
const middleware = middlewares[i++]
if (!middleware) return next()
const params = middleware.slice(1).map(key => {
if (!key || !key.charAt) return key
let datakey = data[key]
if (!datakey){
switch(key.charAt(0)){
case ':':
data[key] = datakey = []
break
case '#':
datakey = key.substring(1)
break
default:
data[key] = datakey = {}
break
}
}
return datakey
})
await middleware[0](...params, async (err, route, newdata = data) => {
if (err) {
if (data && data.ctx) return data.ctx.throw(err)
throw err
}
if (route) {
if (router[route]) return await pipeline(router[route], 0, newdata, next)
throw new Error(`Middleware router [${route}] not found`)
}
await pipeline(middlewares, i, data, next)
})
}
async function trigger(ast, middlewares){
setTimeout(trigger, pTime.nearest(...ast) - Date.now(), ast, middlewares)
await pipeline(middlewares, 0, { }, err => {
if (err) throw err
})
}
function mwm(...middlewares){
const key = middlewares[0]
if (!key) return
if (!Array.isArray(key)){
middlewares.shift()
const ast = pTime.parse(key)
if (ast) return setTimeout(trigger, pTime.nearest(...ast) - Date.now(), ast, middlewares)
if (router[key]) throw new Error(`Middleware router [${key}] is already defined`)
return router[key] = middlewares
}
return (ctx, next) => pipeline(middlewares, 0, {ctx}, next)
}
function groupQuery(input, grouping, output = []){
for (let i = 0, keys, val0; (keys = grouping[i]); i++){
val0 = input[keys[0]]
if (!val0) continue
if (Array.isArray(val0)){
for (let j = 0, l = val0.length; j < l; j++){
output.push(keys.reduce((acc, key) => {
acc[key] = input[key][j]
return acc
}, {}))
}
}else{
output.push(keys.reduce((acc, key) => {
acc[key] = input[key]
return acc
}, {}))
}
}
return output
}
mwm.isDefined = key => !!router[key]
mwm.log = (...args) => {
const len = args.length
args.slice(0, len - 1).forEach(a => console.log(a))
return args[len - 1]()
}
mwm.validate = (spec, source = 'body', grouping = GROUPING) => {
return (ctx, output, ...args) => {
let next
let mapper
switch(args.length){
case 1:
next = args[0]
break
case 2:
mapper = args[0]
next = args[1]
}
let obj
let group
switch(source){
case 'body':
obj = ctx.req.body || ctx.request.body
break
case 'params':
obj = ctx.params
break
case 'query':
group = groupQuery(ctx.request.query, grouping)
obj = Object.assign({group}, ctx.request.query)
break
case 'headers':
obj = ctx.request.headers
break
}
const found = pObj.validate(spec, obj, output, mapper)
if (found) return next(`invalid params [${found}]`)
return next()
}
}
mwm.branch = (route, newdata, next = dummyNext) => {
const middlewares = router[route]
if (!middlewares) throw `route[${route}] not found`
return pipeline(middlewares, 0, newdata, next)
}
mwm.dot = (input, params, def, output, next) => {
const ret = pObj.dot(input, params.slice(), def)
if (!ret) return next(`invalid params [${params}]`)
Object.assign(output, ret)
return next()
}
mwm.ajax = (method, path, opt) => {
const domain = pObj.dot(opt, ['domain'], '')
const radix = new pStr.Radix
radix.add(path)
return (params, body, output, next) => {
return new Promise((resolve, reject) => {
const url = radix.build(path, params)
if (!url) {
reject('invalid params')
return next('invalid params')
}
picosUtil.ajax(method, domain + url, body, opt, (err, state, res) => {
if (4 !== state) return
if (err) {
reject(err)
return next(err)
}
try {
Object.assign(output, JSON.parse(res))
resolve()
}catch (exp){
reject(exp)
return next(exp)
}
return next()
})
})
}
}
module.exports = mwm