smart-api-mocking-layer
v0.1.0
Published
Wrapper around fetch/axios: auto-mock in development, real APIs in production, scenario-based errors/latency/partial data
Downloads
14
Maintainers
Readme
smart-api-mocking-layer
A small wrapper around fetch and axios that registers URL-based mocks for local development, forwards to real APIs when mocking is off (typically production), and supports scenario presets: success, error, latency, and partial (trim fields from JSON).
Install
npm install smart-api-mocking-layerFor the axios adapter, install axios (optional peer):
npm install axiosRequires Node 18+ (uses global fetch / Request).
Demo (React + DummyJSON)
The repo includes a small Vite + React app under demo/ that loads DummyJSON products through smartFetch. You can toggle mocks, prod-like mode, and scenarios (success, latency, partial, error) to see the layer next to the live API.
From the package root:
npm run build
npm install --prefix demo
npm run dev --prefix demoOr in one step (builds the library, installs demo deps, starts Vite):
npm run demoThen open the URL Vite prints (usually http://localhost:5173). With mocks enabled and prod-like mode off, the app serves a small fake product list; turn off mocks or enable prod-like mode to hit the real DummyJSON response. The partial scenario strips total, skip, and limit from the mocked JSON so you can compare payloads in the collapsible raw JSON panel.
Behavior
- Mocking on when not in production:
NODE_ENV !== "production"andVERCEL_ENV !== "production", unless you override (see below). - Mocking off in production: requests use the real
fetch/ default axios adapter. - Override order:
mockEnabledoption →SMART_API_MOCKenv (1/true/onor0/false/off) → production heuristic.
Usage
fetch
import { createSmartLayer } from "smart-api-mocking-layer";
const api = createSmartLayer({
partialOmitPaths: ["user.email"], // used when scenario is `partial`
});
api.registerMock({
id: "users",
url: "/api/users", // substring of full URL
method: "GET",
handler: () => ({ users: [{ id: "1", name: "Ada" }] }),
});
// Same shape as fetch; add mockScenario per call if needed
const res = await api.smartFetch("/api/users");
const data = await res.json();Scenarios
api.setScenario("latency"); // adds defaultLatencyMs (800) before a successful mock
api.setScenario("error"); // fetch: 503 + JSON; axios: rejected AxiosError
api.setScenario("partial"); // drops partialOmitPaths from JSON mocks
api.setScenario("success");
await api.smartFetch("/api/users", { mockScenario: "error" }); // one-off overrideaxios
import axios from "axios";
import { createSmartLayer } from "smart-api-mocking-layer";
const layer = createSmartLayer();
layer.registerMock({
url: "https://api.example.com/v1/me",
handler: () => ({ id: "me" }),
});
const client = axios.create({ adapter: layer.axiosAdapter });
type MockReq = import("axios").AxiosRequestConfig & {
mockScenario?: "success" | "error" | "latency" | "partial";
};
await client.get("https://api.example.com/v1/me", {
mockScenario: "latency",
} as MockReq);Forcing prod-like behavior locally
createSmartLayer({ mockEnabled: false });
// or
createSmartLayer({ isProduction: true });Forcing mocks in production (e.g. demos)
Set SMART_API_MOCK=1 or mockEnabled: true.
API
createSmartLayer(options?)→SmartLayerSmartLayer.registerMock(rule),unregisterMock,clearMocksSmartLayer.setScenario/getScenarioSmartLayer.smartFetch— drop-infetchreplacement when a rule matches and mocking is activeSmartLayer.axiosAdapter— pass toaxios.create({ adapter })detectProduction(),resolveMockEnabled()— helpers for custom wiring
License
MIT
