-
-
Notifications
You must be signed in to change notification settings - Fork 48
/
cors-builder.ts
89 lines (75 loc) · 2.5 KB
/
cors-builder.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
import { MiddlewareTarget } from '../models/middleware-target.ts';
import { Context } from '../models/context.ts';
export class CorsBuilder<T> implements MiddlewareTarget<T> {
private headers: Map<string, string>;
private allowAnyOrigin: boolean;
private allowAnyMethod: boolean;
private allowAnyHeader: boolean;
constructor() {
this.headers = new Map();
this.allowAnyOrigin = false;
this.allowAnyMethod = false;
this.allowAnyHeader = false;
}
onPreRequest(context: Context<T>): Promise<void> {
return new Promise((resolve, reject) => {
if (this.allowAnyOrigin) {
this.headers.set('Access-Control-Allow-Origin', context.request.headers.get('Origin') || '');
}
if (this.allowAnyMethod) {
this.headers.set(
'Access-Control-Allow-Methods',
context.request.headers.get('Access-Control-Request-Method') || '',
);
}
if (this.allowAnyHeader) {
this.headers.set(
'Access-Control-Allow-Headers',
context.request.headers.get('Access-Control-Request-Headers') || '',
);
}
if (context.request.method == 'OPTIONS') {
this.onPostRequest(context);
context.response.status = 200;
context.response.setImmediately();
}
resolve();
});
}
onPostRequest(context: Context<T>): Promise<void> {
return new Promise((resolve, rej) => {
this.headers.forEach((el, key) => {
context.response.headers.set(key, el);
});
resolve();
});
}
WithOrigins(origins: string) {
this.headers.set('Access-Control-Allow-Origin', origins);
return this;
}
WithMethods(methods: string) {
this.headers.set('Access-Control-Allow-Methods', methods);
return this;
}
WithHeaders(headers: string) {
this.headers.set('Access-Control-Allow-Headers', headers);
return this;
}
AllowAnyOrigin() {
this.allowAnyOrigin = true;
return this;
}
AllowAnyMethod() {
this.allowAnyMethod = true;
return this;
}
AllowAnyHeader() {
this.allowAnyHeader = true;
return this;
}
AllowCredentials() {
this.headers.set('Access-Control-Allow-Credentials', 'true');
return this;
}
}