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 🙏

© 2025 – Pkg Stats / Ryan Hefner

custom-api-mock-package

v2.1.2

Published

mockCustomAPI is a lightweight Node.js package that allows developers to quickly set up a mock API for development, unit testing, or integration testing. It supports all CRUD operations and provides validation middleware for API keys and authorization tok

Readme

MockCustomAPI

Overview

mockCustomAPI is a lightweight Node.js package that allows developers to quickly set up a mock API for development, unit testing, or integration testing. It supports all CRUD operations and provides validation middleware for API keys and authorization tokens.

Features

  • Supports the fourth basics HTTP methods: GET, POST, PUT, DELETE.
  • Ability to define custom routes with mock responses.
  • Middleware support for API key and authorization validation.
  • Built-in CRUD functionality for dynamic resources.
  • CORS support for cross-origin requests.
  • Easy-to-use constructor for quick setup.
  • Built-in request logging for debugging.
  • Custom middleware support for advanced request handling.

Installation

npm install mock-custom-api

Usage

Initializing the Mock API Server

import MockAPI from "mock-custom-api";

const mockAPI = new MockAPI("MyMockAPI", 4000, true, true);
  • The first parameter ('MyMockAPI') is the application name.
  • The second parameter (4000) is the port number. if you put undefined, the server will start on a 3000 port.
  • The third parameter (true) enables CORS for all origins. You can also pass an array of allowed origins.
  • The fourth parameter (true) is to allow create some defaults endpoints.

Default Routes

The Mock API includes several default routes for common use cases. These routes are automatically added when the createDefaultRoutes parameter is set to true during initialization.

Default Routes List

  • GET /health - Returns a 200 response with a message indicating the server is running.
  • GET /route-get - Returns a 200 response with a list of items.
  • POST /route-create - Returns a 201 response indicating an item was created.
  • PUT /route-update - Returns a 200 response indicating an item was updated.
  • DELETE /route-delete - Returns a 200 response indicating an item was deleted.
  • GET /secure-route-x-api-key - Returns a 200 response if a valid API key is provided.
  • GET /secure-route-authorization - Returns a 200 response if a valid authorization token is provided.
  • GET /token - Returns a 200 response with a randomly generated token.
  • POST /login-success - Returns a 200 response with a token for successful login.
  • POST /login-error - Returns a 401 response with an error message for failed login.

Example Usage

// Fetch a random token
fetch("http://localhost:3000/token")
  .then((response) => response.json())
  .then((data) => console.log(data));

// Simulate a successful login
fetch("http://localhost:3000/login-success", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ username: "user", password: "pass" }),
})
  .then((response) => response.json())
  .then((data) => console.log(data));

// Simulate a failed login
fetch("http://localhost:3000/login-error", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ username: "user", password: "wrong-pass" }),
})
  .then((response) => response.json())
  .then((data) => console.log(data));

Adding Custom Routes

You can define custom API routes with predefined responses.

mockAPI.addRoute({
  method: "GET",
  path: "/test",
  response: { message: "Test success" },
});

Adding Custom Routes With Authentication Middleware

You can secure routes with API key or token-based authentication.

mockAPI.addRoute({
  method: "GET",
  path: "/protected",
  response: { message: "Protected route" },
  validationType: "apiKey",
  validationValue: "my-secret-key",
});
  • validationType: 'apiKey' ensures that requests must include x-api-key: my-secret-key in the headers.
mockAPI.addRoute({
  method: "GET",
  path: "/secured",
  response: { message: "Protected route" },
  validationType: "authorization",
  validationValue: "secret-token",
});
  • validationType: 'authorization' ensures that requests must include authorization: secret-token in the headers.

Adding CRUD Routes

The addCrudRoutes method allows you to quickly set up CRUD (Create, Read, Update, Delete) endpoints for a specific resource. This is useful for mocking APIs with dynamic resources.

Syntax

mockAPI.addCrudRoutes<T>({
  name: string,
  interface: T,
  randomData: boolean,
});
  • name: The name of the resource (e.g., "users"). This will be used as the base path for the endpoints.
  • interface: The TypeScript interface defining the structure of the resource.
  • randomData: A boolean indicating whether to generate random data for the resource.

Example

interface IUser {
  id: string;
  name: string;
  age: number;
  email: string;
  isActive: boolean;
}

mockAPI.addCrudRoutes<IUser>({
  name: "users",
  interface: {
    id: "",
    name: "",
    age: 0,
    email: "",
    isActive: false,
  },
  randomData: true,
});

This will generate the following endpoints:

  • GET /users - Retrieve a list of users.
  • POST /users - Create a new user.
  • PUT /users - Update an existing user.
  • DELETE /users - Delete a user.

Example API Calls Using Fetch

// Fetch all users
fetch("http://localhost:4000/users")
  .then((response) => response.json())
  .then((data) => console.log(data));

// Create a new user
fetch("http://localhost:4000/users", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({
    id: "1",
    name: "John Doe",
    age: 30,
    email: "[email protected]",
    isActive: true,
  }),
})
  .then((response) => response.json())
  .then((data) => console.log(data));

// Update a user
fetch("http://localhost:4000/users", {
  method: "PUT",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({
    id: "1",
    name: "Jane Doe",
    age: 25,
    email: "[email protected]",
    isActive: false,
  }),
})
  .then((response) => response.json())
  .then((data) => console.log(data));

// Delete a user
fetch("http://localhost:4000/users", {
  method: "DELETE",
})
  .then((response) => response.json())
  .then((data) => console.log(data));

Notes

  • The randomData option generates random data for the resource if set to true. This is useful for testing purposes.
  • The interface parameter ensures that the resource structure adheres to the specified TypeScript interface.

Starting the Mock API Server

mockAPI.start();

Stopping the Mock API Server

mockAPI.stop();

This starts the API server on the specified port.

Example API Calls Using Fetch

fetch("http://localhost:4000/test")
  .then((response) => response.json())
  .then((data) => console.log(data));

fetch("http://localhost:4000/protected", {
  headers: { "x-api-key": "my-secret-key" },
})
  .then((response) => response.json())
  .then((data) => console.log(data));

Running Tests

npm test

License

MIT