-
Notifications
You must be signed in to change notification settings - Fork 0
/
genericEventMiddleware.ts
38 lines (32 loc) · 1.43 KB
/
genericEventMiddleware.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
import { RequestContext, ShioriMiddlewareWithState } from "shiorack";
import { handleRequestLazy, RequestCallbackReturnValue } from "shiori-request-helper";
const genericEventMiddleware: <State>(events?: genericEventMiddleware.Events<State>) =>
ShioriMiddlewareWithState<State, genericEventMiddleware.EventsState<State>> =
<State>(events: genericEventMiddleware.Events<State> = {}) =>
({
request: async function genericEventRequestMiddleware(ctx, next) {
const id = ctx.request.headers.ID as string;
const event = ctx.state.events[id];
if (event) {
return handleRequestLazy(ctx.request, async () => {
const response = await event(ctx);
// tslint:disable-next-line strict-type-predicates
return response == undefined ? next() : response; // 返り値がなかったら後続ミドルへ
});
} else {
return handleRequestLazy(ctx.request, next);
}
},
state: { events },
});
namespace genericEventMiddleware {
export type SanaRequestCallback<State> =
(ctx: RequestContext<State & EventsState<State>>) => RequestCallbackReturnValue;
export interface Events<State> {
[name: string]: SanaRequestCallback<State>;
}
export interface EventsState<State> {
events: Events<State>;
}
}
export = genericEventMiddleware;