deno.land / x / duck_web_framework@0.1.1 / middleware.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
import { matchPath, extractParams } from "./utils/URL.ts";import { DuckRequest } from "./request.ts";import { DuckResponse } from "./response.ts";import { HTTPMethods } from "./router.ts";
export type MiddlewareFunction = ( req: DuckRequest, res: DuckResponse, next: Function,) => any;export type ErrorMiddlewareFunction = ( error: any, req: DuckRequest, res: DuckResponse, next: Function,) => any;
export interface Endpoint { path: Function | string; method: HTTPMethods;}
export class Middleware { private endpoint?: Endpoint; handler: MiddlewareFunction | ErrorMiddlewareFunction;
/** * * @param handler - the function that handles request (or error) * @param endpoint - optional endpoint to match (path and method) */ constructor( handler: MiddlewareFunction | ErrorMiddlewareFunction, endpoint?: Endpoint, ) { this.handler = handler; this.endpoint = endpoint; }
/** * Sets request parameters, based on request URL and this endpoint's path * @param {DuckRequest} req - the request */ setParams(req: DuckRequest): void { let params = {}; if (this.endpoint) { const path = this.endpoint.path instanceof Function ? this.endpoint.path() : this.endpoint.path; params = extractParams(req.url, path); }
req.params = params; }
private matches(request: DuckRequest): boolean { if (this.endpoint) { if ( this.endpoint.method === HTTPMethods.ANY || this.endpoint.method === request.method ) { // if path is a function, it returns the actual path - kinda like computed properties // it's for router using another router, ex. router('/api') uses another router2 // so every route in router2 has to be prepended with '/api' const path = this.endpoint.path instanceof Function ? this.endpoint.path() : this.endpoint.path; return matchPath(request.url, path); } return false; } // if no path specified - it is a global middleware and matches all routes return true; }
/** * Returns middlewares from given collection, that match given request (based on path and method) * @param middlewares - middlewares to look through * @param request - request as filter param */ static findMatching( middlewares: Middleware[], request: DuckRequest, ): Middleware[] { return middlewares.filter((middleware) => middleware.matches(request)); }}
duck_web_framework

Version Info

Tagged at
3 years ago