-
-
Notifications
You must be signed in to change notification settings - Fork 47
/
cors-builder.ts
91 lines (77 loc) · 2.65 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
90
91
import { MiddlwareTarget } from '../models/middlware-target.ts';
import { Response, ServerRequest, RenderResult, ServerResponse } from '../mod.ts';
export class CorsBuilder implements MiddlwareTarget {
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(request: ServerRequest, response: ServerResponse): Promise<void> {
return new Promise((resolve, reject) => {
if (this.allowAnyOrigin) {
this.headers.set('Access-Control-Allow-Origin', request.headers.get('Origin') || '');
}
if (this.allowAnyMethod) {
this.headers.set(
'Access-Control-Allow-Methods',
request.headers.get('Access-Control-Request-Method') || '',
);
}
if (this.allowAnyHeader) {
this.headers.set(
'Access-Control-Allow-Headers',
request.headers.get('Access-Control-Request-Headers') || '',
);
}
if (request.method == 'OPTIONS') {
this.onPostRequest(request, response, response as RenderResult);
response.status = 200;
response.immediately = true;
}
resolve();
});
}
onPostRequest(request: ServerRequest, responce: Response, result?: RenderResult): Promise<void> {
return new Promise((resolve, rej) => {
this.headers.forEach((el, key) => {
if (result && result.headers) {
result.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;
}
}