-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcobain.ts
196 lines (138 loc) · 5.54 KB
/
cobain.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
import { serve, HTTPOptions, ServerRequest } from "https://deno.land/std@0.98.0/http/server.ts"
export const cobain: Cobain = (...middleware) => {
for (const fn of middleware) {
if (typeof fn !== 'function') throw new TypeError('Middleware must be composed of functions!')
}
function createContext(req: ServerRequest): CobainContext {
return {
req,
local: {},
decorators: [],
plugins: [],
}
}
async function respond(ctx: CobainContext): Promise<void> {
// if (ctx.req.)
// ctx.req.
}
// Shoutout the Koa team (https://github.com/koajs/compose)
const compose = (ctx: CobainContext) => {
let index = -1
return dispatch(0)
function dispatch (i: number) {
if (i <= index) return Promise.reject(new Error('handler() called multiple times'))
index = i
let fn = middleware[i]
if (i === middleware.length) fn = dispatch.bind(null, i + 1)
if (!fn) return Promise.resolve()
try {
return Promise.resolve(fn(ctx));
} catch (err) {
return Promise.reject(err)
}
}
}
return (addr) => {
return {
async handleRequest(req: ServerRequest) {
const ctx = createContext(req)
const handleResponse = () => respond(ctx)
try {
await compose(ctx)
handleResponse()
} catch (_err) {
// TODO: catch
}
},
async start() {
if (!addr) throw new Error('No address specified')
const server = serve(addr)
for await (const request of server) {
this.handleRequest(request)
// console.log(request.headers.get('user-agent') || 'unknown')
}
},
}
}
}
const difference = <T>(a: T[], b: T[]) => a.filter(ai => !b.includes(ai))
export const mount = (instance: CobainInstance) =>
(ctx: CobainContext) => instance.handleRequest(ctx.req)
export const router = (route: CobainRouter): CobainRequestHandler => {
const routeHandler: CobainRouteHandler = (path, handler) => {
const getPaths = (decorators: CobainDecorator[]): CobainRoute[] =>
decorators
.filter(method => method !== 'paths')
.map(method => [{ path, method }, handler])
const safeMap: CobainDecoratorMap = prev => {
const entries = prev.map((decorator, idx) => {
const next = prev.slice(0, idx).concat(prev.slice(idx + 1))
if (decorator === 'paths') {
return [decorator, getPaths(difference(cobainDecorators, next))]
}
return [decorator, safeMap(next)]
})
return Object.fromEntries(entries)
}
return safeMap(cobainDecorators)
}
const routes = route(routeHandler)
// execute plugins, act on decorators, etc.
return routes[0].paths[0][1]
}
type CobainRouter = <Decorator extends CobainDecorator = CobainDecorator>(route: CobainRouteHandler) =>
Omit<CobainRouteBuilder<Decorator>, Exclude<CobainDecorator, 'paths'>>[]
export interface CobainInstance {
start: () => Promise<void>
handleRequest: (req: ServerRequest) => Promise<void>
}
export type Cobain = (...middleware: CobainRequestHandler[]) => (addr?: string | HTTPOptions) => CobainInstance
export type CobainAppLocals = Record<string, unknown>
export type CobainContext = {
local: Record<string, unknown>
plugins: unknown[]
decorators: string[]
req: ServerRequest
}
export type CobainRequestHandler = (ctx: CobainContext) => Promise<CobainRequestHandler | void> | CobainRequestHandler | void
export type CobainMiddleware = (handler?: CobainRequestHandler) => CobainRequestHandler
export type CobainRoute = [
def: { path: string, method: string },
handler: CobainRequestHandler
]
export type CobainRouteHandler<Decorator extends CobainDecorator = CobainDecorator> = (path: string, handler: CobainRequestHandler) => CobainRouteBuilder<Decorator>
type CobainRouteBuilder<Decorator extends CobainDecorator = CobainDecorator> = {
[key in CobainDecorator]: key extends 'paths' ? CobainRoute[] : Omit<CobainRouteBuilder<Decorator | key>, Decorator | key>
}
type CobainDecorator = 'get' | 'post' | 'put' | 'patch' | 'delete' | 'paths' | 'all'
const cobainDecorators: CobainDecorator[] = [
'get', 'post', 'put', 'patch', 'delete', 'paths', 'all'
]
type CobainDecoratorMap = (prevDecorators: CobainDecorator[]) => CobainRouteBuilder<typeof prevDecorators[number]>
// const create = <T extends typeof methods[number] = typeof methods[number]>(type: Methods = '', prevTypes: Methods[] = []): Method<T> | Method<Exclude<Methods, typeof type>> => {
/*
const allUsers = (ctx: CobainContext) => {}
const user = (ctx: CobainContext) => {}
const profile = (ctx: CobainContext) => {}
const users = app({
'/': route(auth(allUsers)).get,
'/:id': route(user).get.post(auth).patch(auth),
'/:id': route(user).destroy(auth)
'/:id/profile': route(profile).get
})
export default users
const posts = app()(route => [
route('/', auth(allUsers)).get,
route('/:id', user).get.post(auth).patch(auth),
route('/:id',user).destroy(auth)
route('/:id/profile', profile) // defaults to .get
])
//
const myAppName = cobain()(
auth(
users,
posts
)
)
myAppName.start()
*/