2020-03-09 01:55:02 +01:00
|
|
|
const { promises: fs } = require('fs')
|
2019-12-11 18:26:20 +01:00
|
|
|
const path = require('path')
|
2020-08-18 21:18:25 +02:00
|
|
|
const Koa = require('koa')
|
2019-12-11 18:26:20 +01:00
|
|
|
|
|
|
|
const CURRENT_STATE_KEY = '__CURRENT__'
|
|
|
|
const DEFAULT_STATE_KEY = '__DEFAULT__'
|
|
|
|
|
|
|
|
const FIXTURE_SERVER_HOST = 'localhost'
|
|
|
|
const FIXTURE_SERVER_PORT = 12345
|
|
|
|
|
|
|
|
class FixtureServer {
|
2020-11-03 00:41:28 +01:00
|
|
|
constructor() {
|
2019-12-11 18:26:20 +01:00
|
|
|
this._app = new Koa()
|
2020-11-03 00:41:28 +01:00
|
|
|
this._stateMap = new Map([[DEFAULT_STATE_KEY, Object.create(null)]])
|
2019-12-11 18:26:20 +01:00
|
|
|
this._initialStateCache = new Map()
|
|
|
|
|
|
|
|
this._app.use(async (ctx) => {
|
|
|
|
// Firefox is _super_ strict about needing CORS headers
|
|
|
|
ctx.set('Access-Control-Allow-Origin', '*')
|
|
|
|
if (this._isStateRequest(ctx)) {
|
|
|
|
ctx.body = this._stateMap.get(CURRENT_STATE_KEY)
|
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2020-11-03 00:41:28 +01:00
|
|
|
async start() {
|
2019-12-11 18:26:20 +01:00
|
|
|
const options = {
|
|
|
|
host: FIXTURE_SERVER_HOST,
|
|
|
|
port: FIXTURE_SERVER_PORT,
|
|
|
|
exclusive: true,
|
|
|
|
}
|
|
|
|
|
|
|
|
return new Promise((resolve, reject) => {
|
|
|
|
this._server = this._app.listen(options)
|
|
|
|
this._server.once('error', reject)
|
|
|
|
this._server.once('listening', resolve)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2020-11-03 00:41:28 +01:00
|
|
|
async stop() {
|
2019-12-11 18:26:20 +01:00
|
|
|
if (!this._server) {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2020-08-12 21:06:57 +02:00
|
|
|
await new Promise((resolve, reject) => {
|
2019-12-11 18:26:20 +01:00
|
|
|
this._server.close()
|
|
|
|
this._server.once('error', reject)
|
|
|
|
this._server.once('close', resolve)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2020-11-03 00:41:28 +01:00
|
|
|
async loadState(directory) {
|
2019-12-11 18:26:20 +01:00
|
|
|
const statePath = path.resolve(__dirname, directory, 'state.json')
|
|
|
|
|
|
|
|
let state
|
|
|
|
if (this._initialStateCache.has(statePath)) {
|
|
|
|
state = this._initialStateCache.get(statePath)
|
|
|
|
} else {
|
|
|
|
const data = await fs.readFile(statePath)
|
|
|
|
state = JSON.parse(data.toString('utf-8'))
|
|
|
|
this._initialStateCache.set(statePath, state)
|
|
|
|
}
|
|
|
|
|
|
|
|
this._stateMap.set(CURRENT_STATE_KEY, state)
|
|
|
|
}
|
|
|
|
|
2020-11-03 00:41:28 +01:00
|
|
|
_isStateRequest(ctx) {
|
2019-12-11 18:26:20 +01:00
|
|
|
return ctx.method === 'GET' && ctx.path === '/state.json'
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = FixtureServer
|