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

mqk-mock-server

v1.3.0

Published

simple mock server supporting scenario based mock data

Downloads

11

Readme

Just a simple mock server!

Install

npm i --save mqk-mock-server

Set up mock_home

Create a folder as mock_home. mock_home folder should be in following structure:

mock_home
|
|--data
|  |
|  |--[api-controller-folder-name]
|     |
|     |--_default.js | _default.ts
|     |--[api-scenario-file-name]
|
|--preset
|     |
|     |--[preset-file-name]
|
|--routing
|     |
|     |--[route-file-name]
|
|--msconfig.json

(Optional) Use mqk cli to create mock server

For mqk cli usage see mqk-cli

# install cli tool
npm i -g mqk-cli
# install mock server template
npm i -g mqk-template-mock-server@latest
# create mock server instance
mqk g
# select mock-server
# created!

Route file

A route file should export an array of Route settings.

interface Route {
  path: string | string[];
  methods: HTTP_METHOD[];
  controller: string;
}

For example

export default [{
  path: '/user',
  methods: ['GET'],
  controller: 'user-list',
}, {
  path: '/user/:id',
  methods: ['GET'],
  controller: 'user',
}, {
  path: ['/user', '/user-create'],
  methods: ['POST'],
  controller: 'user-create'
}];

Default Scenario Setting

Make sure there is a [_default.js | _default.ts] file under each [api-controller-folder-name] folder. It simply export the default scenario name/names of API Scenario File.

For example

export default 'success';

If an array of scenarios is used, mock server will respond with senario data in sequence.

export default ['success', 'failed'];

API Scenario File

An API Scenario File should return meta data for an API (regard as API Setting). API Scenario File can be in one of following format:

Plain Object (Declarative)

Export API Setting in plain object directly.

export default {
  delay: 1000,
  data: {
    brand: 'auto'
  }
};

Async function (Programmatic)

Export an async function that returns a Promise which resolves / rejects with API Setting.

For example

async function resolver(ctx: RouterContext) {
  let result = await Promise.resolve({
    delay: 1000,
    data: {
      name: 'Peter Pan',
      address: '101 Bluestreet, NewYork'
    }
  });

  if (ctx.params.id) {
    const id = parseInt(ctx.params.id, 10);
    if (id > 5) {
      result = await Promise.reject({
        status: 404,
        data: {
          message: 'not found'
        }
      });
    }
  }
  return result;
}

export default resolver;

API Setting

API Setting support following features.

Response data, status, delay,

export default {
  delay: 1000,
  data: {
    brand: 'auto'
  },
  status: 200 // 200 by default
};

Proxy to remote API endpoint

export default {
  proxy: true,
  host: 'localhost',
  protocal: 'http',
  port: '3001',
  path: '/fake-user-service/:id'
};

Set scenario for related APIs

Declarative

export default {
  delay: 1000,
  useScenario: [{
    api: 'progress',
    scenario: ['90-percent', '100-percent']
  }]
};

Programmatic

async function resolver(ctx, next, server) {
  const result = await Promise.resolve({
    data: {
      percent: 70
    }
  });
  server.useScenario('progress', '80-percent');
  return result;
}

(Optional) Use mqk cli to create API Scenario File

For mqk cli usage see mqk-cli

# install cli tool
npm i -g mqk-cli
# install mock server template
npm i -g mqk-template-mock-server-data@latest
# cd to mock_home/data folder
mqk g
# select mock-server-data
# input the data path
# input default scenario name
# choose whether to include proxy scenario

Validate request headers and data

export default {
  data: {
    name: 'Peter Pan',
    address: '101 Bluestreet, NewYork'
  },
  validators: [{
    rule: {
      headers: {
        'Content-Type': 'application/json',
        'x-csrf-token': /.+/,
        'x-extra-info': 'key-abc'
      },
      body: {
        type: 'json',
        schema: {
          type: 'object',
          properties: {
            name: {
              type: 'string',
            },
            address: {
              '$ref': '/Address'
            }
          },
          required: ['name']
        },
        refs: [{
          'id': '/Address',
          'type': 'object',
          'properties': {
            'street': {
              'type': 'string'
            },
            'city': {
              'type': 'string'
            }
          }
        }]
      }
    },
    status: 400
  }]
};

Validate http header

rule.headers[key] can be string or RegExp

Validate http body

rule.body.type can be one of json, form, text

For json, following options are available:

  • rule.body.schema: JSON schema
  • rule.body.refs: JSON schema definitoin to be referenced in schema

For form, following options are available:

  • rule.body.schema: JSON schema

For text, following options are available:

  • rule.body.pattern: string or RegExp

Globa configuration file

The global configuration file msconfig.json can be provided under mock_home folder. Global configurations are overridden by API specific configurations. Following is an example configuration file:

{
  "delay": 100 // or range {"min": 100, "max": 150}
}

Start The Mock Server

Export your mock_home path as process.env.MOCK_HOME or pass it to the constructor of mock server.

For example

import { MockServer } from 'mqk-mock-server';
mockServer = new MockServer({
  mockHome: path.resolve(__dirname, '../mock_home')
});
// Listen certain port
mockServer.listen(3000);

Enable HTTPS

import { MockServer } from 'mqk-mock-server';
mockServer = new MockServer({
  mockHome: path.resolve(__dirname, '../mock_home'),
  https: true,
  httpsOptions: {
    key: fs.readFileSync('path to key file'), 'utf8'),
    cert: fs.readFileSync('path to cert file'), 'utf8')
  }
});
// Listen certain port
mockServer.listen(9443);

Stop The Mock Server

mockServer.close();

CLI

install

npm i -g mqk-mock-server

Start mock server

cd to MOCK_HOME. Make sure files under MOCK_HOME is compiled otherwise you should use the programmatic way, see [Start The Mock Server](Start The Mock Server)

ms start

Change API scenario

cd to MOCK_HOME.

ms use <api> <scenario>

# or use cmd alias

ms u <api> <scenario>

# or use the default scenario

ms u <api>

Show current API scenario

cd to MOCK_HOME.

ms state <api>

# or use cmd alias

ms c <api>

Load API scenario preset

cd to MOCK_HOME.

ms load <preset>

# or use cmd alias

ms l <preset>

Save all used API scenarios and loaded API scenario presets as local preset file

cd to MOCK_HOME.

ms save <preset>

# or use cmd alias

ms p <preset>

Public API

HTTP API used to control the mock server

Change API scenario

Change scenario for certain api dynamically.

_api/use-scenario

Method:

POST

Params:

  • api: string (the name of controller)
  • scenario: string (the name of scenario)

Change log

  • v1.3.0
    • add _api/api-list for UI integration
  • v1.2.4
    • ms save command
    • auto save changed scenarios to preset/.tmp.ts preset file
  • v1.2.3 fix proxy body param
  • v1.2
    • Request validator
  • v1.1
    • Global delay configuration (support max, min settings).
    • Fix form-data/multipart file upload
  • v1.0 initial release