-
-
Notifications
You must be signed in to change notification settings - Fork 798
Expand file tree
/
Copy pathhooks.ts
More file actions
214 lines (170 loc) · 5.46 KB
/
Copy pathhooks.ts
File metadata and controls
214 lines (170 loc) · 5.46 KB
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
import {
getManager,
HookContextData,
HookManager,
HookMap as BaseHookMap,
hooks,
Middleware,
collect
} from '@feathersjs/hooks'
import {
Service,
ServiceOptions,
HookContext,
FeathersService,
HookMap,
AroundHookFunction,
HookFunction,
HookType
} from './declarations'
import { defaultServiceArguments, getHookMethods } from './service'
type ConvertedMap = { [type in HookType]: ReturnType<typeof convertHookData> }
type HookStore = {
around: { [method: string]: AroundHookFunction[] }
before: { [method: string]: HookFunction[] }
after: { [method: string]: HookFunction[] }
error: { [method: string]: HookFunction[] }
collected: { [method: string]: AroundHookFunction[] }
}
type HookEnabled = { __hooks: HookStore }
const types: HookType[] = ['before', 'after', 'error', 'around']
const isType = (value: any): value is HookType => types.includes(value)
// Converts different hook registration formats into the
// same internal format
export function convertHookData(input: any) {
const result: { [method: string]: HookFunction[] | AroundHookFunction[] } = {}
if (Array.isArray(input)) {
result.all = input
} else if (typeof input !== 'object') {
result.all = [input]
} else {
for (const key of Object.keys(input)) {
const value = input[key]
result[key] = Array.isArray(value) ? value : [value]
}
}
return result
}
export function collectHooks(target: HookEnabled, method: string) {
const { collected, around } = target.__hooks
return [
...(around.all || []),
...(around[method] || []),
...(collected.all || []),
...(collected[method] || [])
] as AroundHookFunction[]
}
// Add `.hooks` functionality to an object
export function enableHooks(object: any) {
const store: HookStore = {
around: {},
before: {},
after: {},
error: {},
collected: {}
}
Object.defineProperty(object, '__hooks', {
configurable: true,
value: store,
writable: true
})
return function registerHooks(this: HookEnabled, input: HookMap<any, any>) {
const store = this.__hooks
const map = Object.keys(input).reduce((map, type) => {
if (!isType(type)) {
throw new Error(`'${type}' is not a valid hook type`)
}
map[type] = convertHookData(input[type])
return map
}, {} as ConvertedMap)
const types = Object.keys(map) as HookType[]
types.forEach((type) =>
Object.keys(map[type]).forEach((method) => {
const mapHooks = map[type][method]
const storeHooks: any[] = (store[type][method] ||= [])
storeHooks.push(...mapHooks)
if (store.before[method] || store.after[method] || store.error[method]) {
const collected = collect({
before: store.before[method] || [],
after: store.after[method] || [],
error: store.error[method] || []
})
store.collected[method] = [collected]
}
})
)
return this
}
}
export function createContext(service: Service, method: string, data: HookContextData = {}) {
const createContext = (service as any)[method].createContext
if (typeof createContext !== 'function') {
throw new Error(`Can not create context for method ${method}`)
}
return createContext(data) as HookContext
}
export class FeathersHookManager<A> extends HookManager {
constructor(public app: A, public method: string) {
super()
this._middleware = []
}
collectMiddleware(self: any, args: any[]): Middleware[] {
const appHooks = collectHooks(this.app as any as HookEnabled, this.method)
const middleware = super.collectMiddleware(self, args)
const methodHooks = collectHooks(self, this.method)
return [...appHooks, ...middleware, ...methodHooks]
}
initializeContext(self: any, args: any[], context: HookContext) {
const ctx = super.initializeContext(self, args, context)
ctx.params = ctx.params || {}
return ctx
}
middleware(mw: Middleware[]) {
this._middleware.push(...mw)
return this
}
}
export function hookMixin<A>(this: A, service: FeathersService<A>, path: string, options: ServiceOptions) {
if (typeof service.hooks === 'function') {
return service
}
const hookMethods = getHookMethods(service, options)
const serviceMethodHooks = hookMethods.reduce((res, method) => {
const params = (defaultServiceArguments as any)[method] || ['data', 'params']
res[method] = new FeathersHookManager<A>(this, method).params(...params).props({
app: this,
path,
method,
service,
event: null,
type: 'around',
get statusCode() {
return this.http?.status
},
set statusCode(value: number) {
this.http = this.http || {}
this.http.status = value
}
})
return res
}, {} as BaseHookMap)
const registerHooks = enableHooks(service)
hooks(service, serviceMethodHooks)
service.hooks = function (this: any, hookOptions: any) {
if (hookOptions.before || hookOptions.after || hookOptions.error || hookOptions.around) {
return registerHooks.call(this, hookOptions)
}
if (Array.isArray(hookOptions)) {
return hooks(this, hookOptions)
}
Object.keys(hookOptions).forEach((method) => {
const manager = getManager(this[method])
if (!(manager instanceof FeathersHookManager)) {
throw new Error(`Method ${method} is not a Feathers hooks enabled service method`)
}
manager.middleware(hookOptions[method])
})
return this
}
return service
}