Skip to content

Commit 1aa71c9

Browse files
committed
feat: implement on
1 parent 54e1d46 commit 1aa71c9

File tree

2 files changed

+27
-14
lines changed

2 files changed

+27
-14
lines changed

src/pico.ts

Lines changed: 16 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import type { Handler } from './types'
22

3-
const METHODS = ['all', 'get', 'post', 'put', 'delete', 'head', 'options', 'patch'] as const
3+
const METHODS = ['all', 'get', 'post', 'put', 'delete', 'head'] as const
44
function defineDynamicClass(): {
55
new (): {
66
[K in typeof METHODS[number]]: (path: string, handler: Handler) => Pico
@@ -18,25 +18,27 @@ class Pico extends defineDynamicClass() {
1818
constructor() {
1919
super()
2020
;[...METHODS].map((method) => {
21-
this[method] = (path: string, handler: Handler) => {
22-
const route = {
23-
pattern: new URLPattern({
24-
pathname: path,
25-
}),
26-
method: method.toUpperCase(),
27-
handler,
28-
}
29-
this.routes.push(route)
30-
return this
31-
}
21+
this[method] = (path: string, handler: Handler) => this.on(method, path, handler)
3222
})
3323
}
3424

25+
on(method: string, path: string, handler: Handler) {
26+
const route = {
27+
pattern: new URLPattern({
28+
pathname: path,
29+
}),
30+
method: method.toLowerCase(),
31+
handler,
32+
}
33+
this.routes.push(route)
34+
return this
35+
}
36+
3537
match(method: string, url: string): { handler: Handler; result: URLPatternURLPatternResult } {
36-
method = method.toUpperCase()
38+
method = method.toLowerCase()
3739
for (const route of this.routes) {
3840
const matched = route.pattern.test(url)
39-
if ((matched && route.method === 'ALL') || (matched && route.method === method)) {
41+
if ((matched && route.method === 'all') || (matched && route.method === method)) {
4042
return { handler: route.handler, result: route.pattern.exec(url) }
4143
}
4244
}

test/pico.test.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,3 +50,14 @@ describe('All', () => {
5050
expect(res.status).toBe(200)
5151
})
5252
})
53+
54+
describe('on', () => {
55+
const app = new Pico()
56+
app.on('PURGE', '/cache', () => 'purged')
57+
58+
it('Should return 200 response with PURGE method', async () => {
59+
const req = new Request('http://localhost/cache', { method: 'PURGE' })
60+
const res = app.fetch(req)
61+
expect(res.status).toBe(200)
62+
})
63+
})

0 commit comments

Comments
 (0)