Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

foundation simulator delay response API #285

Merged
merged 3 commits into from
Sep 13, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changes/foundation-delay.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@simulacrum/foundation-simulator": minor:enhance
---

Add API to configure a delay of all responses with a set interval. Using this in a simulator would enable a feel closer to a real external endpoint.
4 changes: 4 additions & 0 deletions packages/foundation/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import type {
ExtendSimulationSchema,
} from "./store/schema";
import type { RecursivePartial } from "./store/types";
import { delayMiddleware } from "./middleware/delay";

type SimulationHandlerFunctions = (
context: OpenAPIBackendContext,
Expand All @@ -50,12 +51,14 @@ export function createFoundationSimulationServer<
ExtendedSimulationSelectors
>({
port = 9000,
delayResponses,
serveJsonFiles,
openapi,
extendStore,
extendRouter,
}: {
port: number;
delayResponses?: number | { minimum: number; maximum: number };
serveJsonFiles?: string;
openapi?: {
document: Document | (Document | RecursivePartial<Document>)[];
Expand Down Expand Up @@ -93,6 +96,7 @@ export function createFoundationSimulationServer<
let app = express();
app.use(express.json());
let simulationStore = createSimulationStore(extendStore);
app.use(delayMiddleware(delayResponses));

if (serveJsonFiles) {
const jsonFiles = new fdir()
Expand Down
61 changes: 61 additions & 0 deletions packages/foundation/src/middleware/delay.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import type { Request, Response, NextFunction } from "express";

export function delayMiddleware(
delayResponses?: number | { minimum: number; maximum: number }
) {
const delayMin =
typeof delayResponses === "number"
? delayResponses
: delayResponses?.minimum;
const delayMax =
typeof delayResponses === "number" ? undefined : delayResponses?.maximum;

const minFromProcess = process.env.SIM_RESPONSE_DELAY_MIN
? process.env.SIM_RESPONSE_DELAY_MIN
: process.env.SIM_RESPONSE_DELAY;
const min = minFromProcess ? parseInt(minFromProcess, 10) : delayMin;

const maxFromProcess = process.env.SIM_RESPONSE_DELAY_MAX;
const max = maxFromProcess ? parseInt(maxFromProcess, 10) : delayMax;
jbolda marked this conversation as resolved.
Show resolved Hide resolved

return async function delayHandler(
request: Request,
response: Response,
next: NextFunction
) {
if (min || max) {
let timeoutDuration = calculateTimeoutDuration(min, max);
await new Promise<void>((resolve) => {
let timeoutHandle: NodeJS.Timeout | undefined = undefined;

const done = () => {
if (timeoutHandle) {
clearTimeout(timeoutHandle);
}
resolve();
};

timeoutHandle = setTimeout(done, timeoutDuration);
});
}
next();
};
}

function calculateTimeoutDuration(
min: number | undefined,
max: number | undefined
): number {
if (max && !min) {
// sets the timeout at +/- 20% of configured max
return max * 0.8 + max * 0.4 * Math.random();
} else if (min && !max) {
// sets the timeout at +/- 20% of configured max
return min * 0.8 + min * 0.4 * Math.random();
} else if (max && min) {
const timeoutRange = max - min;
return min + timeoutRange * Math.random();
}

return 0;
}
Loading