-
-
Notifications
You must be signed in to change notification settings - Fork 47
/
spa-builder.ts
36 lines (30 loc) · 1.33 KB
/
spa-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
import { MiddlwareTarget } from '../models/middlware-target.ts';
import { ServerResponse, ServerRequest } from '../mod.ts';
import { StaticFilesConfig } from '../models/static-config.ts';
import { send } from '../static/send.ts';
import { getStaticFile } from '../utils/get-static-file.ts';
export class SpaBuilder implements MiddlwareTarget {
constructor(private staticConfig: StaticFilesConfig) {}
onPreRequest(request: ServerRequest, response: ServerResponse): Promise<void> {
return new Promise(async (resolve, reject) => {
if (await getStaticFile(request, response, this.staticConfig)) {
response.immediately = true;
}
resolve();
});
}
onPostRequest(request: ServerRequest, response: ServerResponse, actionResult?: any): Promise<void> {
return new Promise(async (resolve, reject) => {
if (actionResult === undefined && this.staticConfig.index && !hasUrlExtension(request.url)) {
if (await send({ request, response }, this.staticConfig.index, this.staticConfig)) {
response.immediately = true;
}
}
resolve();
});
}
}
function hasUrlExtension(url: string): boolean {
const fragments = url.split('/');
return fragments[fragments.length - 1].includes('.');
}