Skip to content

Instantly share code, notes, and snippets.

@gomezcabo
Created July 7, 2021 15:13
Show Gist options
  • Save gomezcabo/e7b1edbf34591086b8d2d18cec070aee to your computer and use it in GitHub Desktop.
Save gomezcabo/e7b1edbf34591086b8d2d18cec070aee to your computer and use it in GitHub Desktop.
type Method = "GET" | "POST" | "PUT" | "DELETE";
type RouteCallback = (request?: MockRequest) => unknown;
interface Route {
method: Method;
url: string;
callback: RouteCallback;
}
type MockRequest = {
params?: Record<string, string>;
method?: Method;
body?: any;
};
interface MockAPIConfig {
delay?: number;
routes: Array<Route>;
}
type FetchFunction = (url: string, request?: MockRequest) => Promise<unknown>;
const methodFunction =
(method: Method) =>
(url: string, callback: RouteCallback): Route => ({
method: method,
url,
callback,
});
const rest = {
get: methodFunction("GET"),
post: methodFunction("POST"),
};
function createMockAPI(config: MockAPIConfig): FetchFunction {
return async function (url: string, request?: MockRequest) {
await new Promise(r => setTimeout(r, config?.delay ?? 1000));
const method = request?.method || "GET";
const route = config.routes.find(
route => route.url === url && route.method === method,
);
return route?.callback(request);
};
}
const DATA = {
items: [
{ id: 1, name: "Item 1" },
{ id: 2, name: "Item 2" },
],
};
let newId = 3;
const mockFetch = createMockAPI({
delay: 500,
routes: [
rest.get("/items", () => DATA.items),
rest.get("/items/:id", request => {
const itemId = request?.params?.id;
const item = DATA.items.find(item => item.id === Number(itemId));
return item;
}),
rest.post("/items", request => {
const newItem = {
...request!.body,
id: newId++,
};
DATA.items = [...DATA.items, newItem];
}),
],
});
const doTheJob = async () => {
const a = await mockFetch("/items");
console.log(a);
const b = await mockFetch("/items/:id", { params: { id: '1' } });
console.log(b);
await mockFetch("/items", { method: "POST", body: { name: "Item X" } });
const c = await mockFetch("/items");
console.log(c);
};
doTheJob();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment