This repository has been archived by the owner on Oct 6, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.ts
111 lines (93 loc) · 2.28 KB
/
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
import {
Request,
Response,
State,
} from "https://deno.land/x/oak@v11.1.0/mod.ts";
import {
InvalidBody,
InvalidHeader,
InvalidProperty,
LimitExceeded,
MissingBody,
UberdenoError,
} from "./errors.ts";
export async function postHandler(
{ request }: {
request: Request;
},
next: () => Promise<unknown>,
): Promise<void> {
if (request.method === "POST" || request.method === "PUT") {
if (!request.hasBody) {
throw new MissingBody();
}
// We'll transfer every header key to lowercase for easier comparison
request.headers.forEach((_value, key) => {
key = key.toLowerCase();
});
if (request.headers.get("content-type") !== "application/json") {
throw new InvalidHeader();
}
const body = request.body({ type: "json" });
await body.value.catch(() => {
throw new InvalidBody();
});
}
await next();
return;
}
export async function errorHandler(
{ response }: {
response: Response;
},
next: () => Promise<unknown>,
): Promise<void> {
await next().catch(
(error: UberdenoError) => {
if (
error.statusError === 500 || typeof error.statusError === "undefined"
) {
response.body = "Internal Server Error";
response.status = 500;
console.log(error.message);
console.log(error.stack);
return;
}
response.status = error.statusError;
response.body = {
message: error.message,
};
},
);
}
export async function limitHandler(
{ request, state }: {
request: Request;
state: State;
},
next: () => Promise<unknown>,
): Promise<void> {
if (request.method === "GET") {
let limit = request.url.searchParams.get(`limit`)
? request.url.searchParams.get(`limit`)
: 5;
let offset = request.url.searchParams.get(`offset`)
? request.url.searchParams.get(`offset`)
: 0;
if (isNaN(+limit!) || Number(limit) < 0) {
throw new InvalidProperty("limit", "number");
}
if (isNaN(+offset!) || Number(offset) < 0) {
throw new InvalidProperty("offset", "number");
}
limit = Number(limit);
offset = Number(offset);
if (limit > 99) {
throw new LimitExceeded();
}
state.limit = limit;
state.offset = offset;
}
await next();
return;
}