counterfact
Version:
Generate a TypeScript-based mock server from an OpenAPI spec in seconds — with stateful routes, hot reload, and REPL support.
36 lines (35 loc) • 1.29 kB
JavaScript
import { watch } from "chokidar";
import createDebug from "debug";
import { waitForEvent } from "../util/wait-for-event.js";
import { CHOKIDAR_OPTIONS } from "./constants.js";
import { loadOpenApiDocument } from "./load-openapi-document.js";
const debug = createDebug("counterfact:server:openapi-watcher");
export class OpenApiWatcher {
openApiPath;
dispatcher;
watcher;
constructor(openApiPath, dispatcher) {
this.openApiPath = openApiPath;
this.dispatcher = dispatcher;
}
async watch() {
if (this.openApiPath === "_" || this.openApiPath.startsWith("http")) {
return;
}
this.watcher = watch(this.openApiPath, CHOKIDAR_OPTIONS).on("change", () => {
void (async () => {
try {
this.dispatcher.openApiDocument = await loadOpenApiDocument(this.openApiPath);
debug("reloaded OpenAPI document from %s", this.openApiPath);
}
catch (error) {
debug("failed to reload OpenAPI document from %s: %o", this.openApiPath, error);
}
})();
});
await waitForEvent(this.watcher, "ready");
}
async stopWatching() {
await this.watcher?.close();
}
}