-
-
Notifications
You must be signed in to change notification settings - Fork 47
/
spa-builder.ts
37 lines (30 loc) · 1.37 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
37
import { MiddlewareTarget } from '../models/middleware-target.ts';
import { StaticFilesConfig } from '../models/static-config.ts';
import { send } from '../static/send.ts';
import { getStaticFile } from '../utils/get-static-file.ts';
import { Context } from '../models/context.ts';
export class SpaBuilder<TState> implements MiddlewareTarget<TState> {
constructor(private staticConfig: StaticFilesConfig) {}
onPreRequest(context: Context<TState>): Promise<void> {
return new Promise(async (resolve, reject) => {
if (await getStaticFile(context, this.staticConfig)) {
context.response.setImmediately();
}
resolve();
});
}
onPostRequest(context: Context<TState>): Promise<void> {
return new Promise(async (resolve, reject) => {
if (context.response.result === undefined && this.staticConfig.index && !hasUrlExtension(context.request.url)) {
if (await send({ request: context.request.serverRequest, response: context.response }, this.staticConfig.index, this.staticConfig)) {
context.response.setImmediately();
}
}
resolve();
});
}
}
function hasUrlExtension(url: string): boolean {
const fragments = url.split('/');
return fragments[fragments.length - 1].includes('.');
}