npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@laigma/mock-db

v1.2.5

Published

In-memory database for functional tests

Readme

🗄️ MockDB

Lightweight in-memory database + API mocker for testing

npm version License: ISC TypeScript


📋 Overview

@laigma/mock-db is a modular toolkit for mocking data in tests. It ships two independent pieces:

| Export | Purpose | |---|---| | MockDb | Loads JSON files into an in-memory store. Core of the library. | | createApiMocker | Axios interceptor plugin. Intercepts requests and returns mock data from a MockDb instance. Requires axios and a @laigma/logger BackendLogger. |


🚀 Installation

npm install @laigma/mock-db

If you use the createApiMocker plugin, also install:

npm install axios @laigma/logger

📖 MockDb

Setup

Create a directory with one JSON file per collection. The filename (without .json) becomes the key in the database.

mocks/
  users.json
  products.json

Initialization

import MockDb from "@laigma/mock-db";
import path from "path";

const db = new MockDb();
db.init(path.resolve(__dirname, "./mocks"));        // silent
db.init(path.resolve(__dirname, "./mocks"), true);  // with colored ANSI log

Passing true as the second argument prints a visual summary to the terminal:

════════════════════════════════════════════════════════════
  🗄️  MockDB - In-Memory Database
════════════════════════════════════════════════════════════
  ✓ Status: READY
  📊 Loaded Collections: 2
  Available Collections:
     1. users
     2. products
════════════════════════════════════════════════════════════

API

init(jsonDirectory: string, enableLogging?: boolean): void

Reads every .json file in jsonDirectory and stores the parsed content using the filename (without extension) as the key. Throws if the directory does not exist.

getDb(): Record<string, unknown>

Returns a shallow copy of the entire in-memory store.

const snapshot = db.getDb();

getData(key: string): unknown

Returns the value stored under key, or undefined if not found.

const users = db.getData("users");

setData(key: string, value: unknown): void

Inserts or overwrites a key in the store.

db.setData("session", { token: "abc123" });

🔌 createApiMocker plugin

An Axios interceptor that short-circuits outgoing requests and returns mock data instead of hitting the network.

How it works

  1. The request interceptor checks whether the request URL contains any registered key.
  2. Match — resolves with a synthetic 200 response containing the mock data.
  3. No match — calls logger.logError (when debug is active) and rejects with an Error.

Usage

import axios from "axios";
import MockDb, { createApiMocker } from "@laigma/mock-db";
import { createBackendLogger } from "@laigma/logger";
import path from "path";

const db = new MockDb();
db.init(path.resolve(__dirname, "./mocks"));

const logger = createBackendLogger({
  envMode: process.env.NODE_ENV,
  appName: "my-app",
  appVersion: "1.0.0",
});

const axiosInstance = axios.create({ baseURL: "https://api.example.com" });

createApiMocker({
  responses: {
    "/api/users":    db.getData("users"),
    "/api/products": db.getData("products"),
  },
  logger,
  envMode: process.env.NODE_ENV,  // "production" throws immediately
}).attachTo(axiosInstance);

ApiMockerOptions

| Property | Type | Required | Description | |---|---|---|---| | responses | Record<string, unknown> | ✅ | Map of URL fragment → mock data. Values are typically obtained via db.getData(key). | | logger | IBackendLogger | ✅ | Instance of BackendLogger from @laigma/logger. | | envMode | string | — | Application environment (e.g. "development", "test"). Passing "production" throws immediately — mocking in production is forbidden. Also controls the debug default when not set explicitly. | | debug | boolean | — | Enable/disable logger output. When omitted, defaults to false if envMode === "test", true otherwise. Passing debug: false suppresses all logger calls without disabling the interceptors. |

debug / envMode behaviour matrix

| envMode | debug | Logger calls | |---|---|---| | "production" | any | throws at construction | | "test" | (unset) | silent | | "development" | (unset) | active | | (unset) | (unset) | active | | any | true | active | | any | false | silent |

Even when debug: false, an unmatched route still rejects with an Error.

IBackendLogger (structural interface)

The plugin accepts any object that satisfies this shape — no hard dependency on @laigma/logger at the type level:

interface IBackendLogger {
  logError(message: string, errorObj: unknown, metadata?: LogMetadata, stopProcess?: boolean): void;
  logSuccess(message: string, detailObj?: unknown, metadata?: LogMetadata): void;
}

💡 Full example

import MockDb, { createApiMocker } from "@laigma/mock-db";
import { createBackendLogger } from "@laigma/logger";
import axios from "axios";
import path from "path";

const db = new MockDb();
db.init(path.resolve(__dirname, "./mocks"), true);

const logger = createBackendLogger({
  envMode: process.env.NODE_ENV,
  appName: "my-app",
  appVersion: "1.0.0",
});

createApiMocker({
  responses: {
    "/users": db.getData("users"),
    "/posts": db.getData("posts"),
  },
  logger,
  envMode: process.env.NODE_ENV, // throws if NODE_ENV === "production"
  // debug: false                // override logging regardless of envMode
}).attachTo(axios.create({ baseURL: "https://api.example.com" }));

🛠️ Development

npm install

# Run tests
npm test

# Watch mode
npm run test:watch

# Coverage
npm run test:coverage

# Human-readable demo (no tests)
npm run demo

# Build
npm run build

Project structure

src/
  core/
    MockDb.ts          ← in-memory store
  plugins/
    apiMocker.ts       ← createApiMocker plugin
  index.ts             ← public entry point
tests/
  MockDb.test.ts
  MockDb.logging.test.ts
  apiMocker.test.ts
  fixtures/            ← JSON test data
demo/
  index.ts             ← standalone human-debug script
  mocks/               ← demo JSON fixtures

🤝 Contributions

Contributions are welcome! Please feel free to submit a Pull Request or open an Issue.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

📄 License

This project is licensed under the ISC License. See the LICENSE file for more details.


Made with ❤️ by laigma