-
Notifications
You must be signed in to change notification settings - Fork 348
Expand file tree
/
Copy pathmiddleware-route.ts
More file actions
81 lines (74 loc) · 1.82 KB
/
Copy pathmiddleware-route.ts
File metadata and controls
81 lines (74 loc) · 1.82 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
import type { HTTPMethod } from "../types/h3.ts";
import type { Middleware } from "../types/handler.ts";
import type { H3Plugin, H3 } from "../types/h3.ts";
import type { H3Event } from "../event.ts";
import { defineMiddleware } from "../middleware.ts";
/**
* Middleware route definition options
*/
export interface MiddlewareRouteDefinition {
/**
* Path pattern for the middleware, e.g. '/api/**'
*/
path?: string;
/**
* HTTP methods to apply the middleware to
*/
methods?: HTTPMethod[];
/**
* Middleware handler function
*/
handler: Middleware;
/**
* Additional middleware metadata
*/
meta?: Record<string, unknown>;
}
/**
* Define a middleware route as a plugin that can be registered with app.register()
*
* @example
* ```js
* const authMiddleware = defineMiddlewareRoute({
* path: '/api/**',
* methods: ['GET', 'POST'],
* meta: {
* rateLimit: {
* interval: '1m',
* tokensPerInterval: 10,
* },
* },
* handler: async (event, next) => {
* console.log('Auth middleware running');
* // Check authentication
* if (!event.context.user) {
* return new Response('Unauthorized', { status: 401 });
* }
* return next();
* }
* });
*
* app.register(authMiddleware);
* ```
*/
export function defineMiddlewareRoute(
def: MiddlewareRouteDefinition,
): H3Plugin {
const middleware = defineMiddleware(def.handler);
return (h3: H3) => {
const options = {
...(def.methods && {
match: (event: H3Event) => {
const method = event.req.method.toUpperCase();
return def.methods!.includes(method as HTTPMethod);
},
}),
...(def.meta && { meta: def.meta }),
};
if (def.path) {
h3.use(def.path, middleware, options);
} else {
h3.use(middleware, options);
}
};
}