2021-09-10 00:22:43 +08:00
|
|
|
import net from 'net';
|
2021-09-09 23:47:04 +08:00
|
|
|
|
|
|
|
import Koa from 'koa';
|
|
|
|
import files from 'koa-files';
|
|
|
|
|
|
|
|
import {ServerAddress} from './types.js';
|
|
|
|
|
|
|
|
export class FixturesServer {
|
|
|
|
private readonly koa: Koa;
|
|
|
|
|
2022-02-16 18:50:37 +08:00
|
|
|
private server?: net.Server;
|
2021-09-09 23:47:04 +08:00
|
|
|
|
2021-09-30 11:18:33 +08:00
|
|
|
constructor(path: string) {
|
2021-09-09 23:47:04 +08:00
|
|
|
this.koa = new Koa();
|
2021-09-30 11:18:33 +08:00
|
|
|
this.koa.use(files(path));
|
2021-09-09 23:47:04 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
async start(): Promise<ServerAddress> {
|
|
|
|
return new Promise((resolve, reject) => {
|
|
|
|
this.server = this.koa.listen(0, 'localhost', () => {
|
|
|
|
const addr = this.server?.address();
|
|
|
|
if (typeof addr === 'string' || !addr) {
|
|
|
|
reject(new Error('invalid address'));
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
resolve({
|
|
|
|
address: addr.address,
|
|
|
|
port: addr.port,
|
|
|
|
base: `http://localhost:${addr.port}`,
|
|
|
|
});
|
|
|
|
});
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
async stop(): Promise<void> {
|
|
|
|
return new Promise((resolve) => {
|
|
|
|
this.server?.close(() => {
|
|
|
|
resolve();
|
|
|
|
});
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|