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 🙏

© 2024 – Pkg Stats / Ryan Hefner

fake-api-middleware

v0.1.8

Published

Express/Connect middleware for dummy responses

Downloads

37

Readme

Fake-Api-Middleware

This is an Express+Connect middleware for mocking API responses. It can be used with Vite, Webpack DevServer, CreateReactApp, and many other frameworks that are based on the NodeJS Connect/Express server.

  • 🔩 Compatible with Express+Connect
  • 🛠️ Write dummy responses with JavaScript/TypeScript
  • 🔥 Hot reloading of dummy responses

Install

npm install fake-api-middleware

Usage

Create a file for storing response dummies. The file can be either in JavaScript or TypeScript.

./apiDummies/index.ts:

import { delay } from 'fake-api-middleware';
import type { ResponseFunctionParams } from 'fake-api-middleware';

export default {
  // The response can be in the form of a normal JavaScript object, which will be returned as JSON with a status code of 200
  'POST /test': {
    foo: 'bar'
  },
  
  // The response can be an object, array, string, number or null
  'GET /api/users': [
    {id: 1, name: 'Bob'},
    {id: 2, name: 'Jack'},
    {id: 3, name: 'Mike'},
  ],
  
  // The response can also be a function that returns a JavaScript object, which will be returned as a JSON response with a status code of 200
  'POST /api/createUser': ({ body, query, headers, params, req, res }: ResponseFunctionParams) => {
    return {
      message: `User ${body.name} created`
    };
  },
  
  // It is possible to change the response status code using the `res` object
  'GET /api/unknown': ({ body, query, headers, params, req, res }: ResponseFunctionParams) => {
    res.statusCode = 404;
    return {
      message: `Route does not exist`
    };
  },
  
  // The API path can contain special regular expression syntax. 
  // For more information, please see https://www.npmjs.com/package/path-to-regexp
  'GET /api/users/:id': ({ body, query, headers, params, req, res }: ResponseFunctionParams) => {
    return {
      message: `User with id ${params.id} is here`
    };
  },
  
  // It is possible to use asynchronous response functions
  'GET /api/async': async ({ body, query, headers, params, req, res }: ResponseFunctionParams) => {
    await delay(1000);
    return {
      message: `Hello!`
    };
  },
  
  // Alternatively, the response can be a function that manually prepares an HTTP response. 
  // For more information, please see https://nodejs.org/api/http.html#class-httpserverresponse
  'POST /api/processData': ({ body, query, headers, params, req, res }: ResponseFunctionParams) => {
    res.statusCode = 200;
    res.setHeader('Content-Type', 'application/json');
    return res.end(
      JSON.stringify({
        additional: {
          body,
          query,
          headers,
          params
        },
        message: 'It is response made with ServerResponse',
      }),
    );
  },
};

Set up the middleware for the HTTP server with the path to the file containing the response dummies. The following example demonstrates using the Connect server, but please check the setup examples below for more options.

./server.js:

var connect = require('connect');
var http = require('http');
const { middleware: fakeApiMiddleware } = require('fake-api-middleware');
 
var app = connect();

app.use(
  fakeApiMiddleware({
    responsesFile: './apiDummies/index.ts',
    watchFiles: ['./apiDummies/**/*'],
    responseDelay: 250,
    enable: true,
  }),
);

http.createServer(app).listen(3000);

API

Options for the middleware:

  • responsesFile: string - Path to the API dummies file.
  • responses: Record<string, any> - Pre-defined dummies object (default: {}).
  • watchFiles: string|string[] - Folders/files to watch for updates to reload dummies file (by default, it only watches the single responsesFile).
  • responseDelay: number - Delay in milliseconds for each dummy response (default: 0).
  • enable: boolean - Enable/disable middleware (default: true).

Options for the dummy response function:

  • body: Record<string, any> - Object with parsed body from request.
  • query: Record<string, any> - Object with parsed query parameters of the requested URL.
  • headers: Record<string, any> - Object with request headers.
  • params: Record<string, any> - Object with URL regular expression values.
  • req: IncomingMessage - Raw Node.js HTTP IncomingMessage object.
  • res: ServerResponse - Raw Node.js HTTP ServerResponse object.

Examples of how to set up the middleware

Express

const express = require('express');
const { middleware: fakeApiMiddleware } = require('fake-api-middleware');

const app = express();

app.use(
  fakeApiMiddleware({
    responsesFile: './apiDummies/index.js',
  }),
);

app.listen(8080);

Vite

Use the built-in plugin for vite in the vite.config.js file:

import { defineConfig } from 'vite';
import { vitePlugin as fakeApiVitePlugin } from 'fake-api-middleware';

export default defineConfig({
  plugins: [
    fakeApiVitePlugin({
      responsesFile: './apiDummies/index.ts',
    }),
  ],
});

Create React App

Create setupProxy.js file in the src folder with the following content (note that the apiDummies folder should be in the root of the project):

const { middleware: fakeApiMiddleware } = require('fake-api-middleware');

module.exports = function (app) {
  app.use(
    fakeApiMiddleware({
      responsesFile: './apiDummies/index.js',
    }),
  );
};

Webpack

To set up the middleware in a webpack configuration, create or modify the devServer section and add a before rule:

const { middleware: fakeApiMiddleware } = require('fake-api-middleware');

module.exports = {
  // ...
  devServer: {
    // ...
    before(app) {
      app.use(
        fakeApiMiddleware({
          responsesFile: './apiDummies/index.js',
        }),
      );
    },
  },
  // ...
};