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

data-mocks-server

v10.0.2

Published

Server version of the popular data-mocks library

Downloads

2,140

Readme

Data Mocks Server

This package was originally a port of https://github.com/ovotech/data-mocks that prefers spinning up an express server instead of mocking out fetch and XHR operations. Thanks goes to grug for his idea and implementation.

Table of contents

Installation

npm install data-mocks-server

Example usage

const { run } = require('data-mocks-server');

run({
  default: [
    {
      url: '/api/test-me',
      method: 'GET',
      response: { data: { blue: 'yoyo' } },
    },
  ],
  scenarios: {
    cheese: [
      {
        url: '/api/test-me',
        method: 'GET',
        response: { data: { blue: 'cheese' } },
      },
    ],
  },
});

Calls to http://localhost:3000/api/test-me will start by returning { blue: 'yoyo' }.

Visiting http://localhost:3000 will allow you to Modify scenarios. The default response will always be included unless a scenario overrides it. In this case enabling cheese will modify /api/test-me so that it returns { blue: 'cheese' }.

API

createExpressApp

Returns the internal express instance

function({ default, scenarios, options })

run

Returns an http server, with an additional kill method

function({ default, scenarios, options })

default

Array<Mock> | { context, mocks } | required

| Property | Type | Default | Description | | -------- | ------------- | ----------- | ------------------------------------- | | context | object | undefined | Used to set up data across API calls. | | mocks | Array<Mock> | required | See Mock for more details. |

scenarios

{ [scenarioName]: Array<Mock> | { group, mocks } }

| Property | Type | Default | Description | | ------------ | ------------- | ----------- | -------------------------------------------------------------------------------------- | | scenarioName | string | required | Name of scenario. | | Mock | Mock | required | See Mock for more details. | | group | string | undefined | Used to group scenarios together so that only one scenario in a group can be selected. | | context | object | undefined | Used to set up data across API calls. | | mocks | Array<Mock> | required | See Mock for more details. |

options

{ port, uiPath, modifyScenariosPath, resetScenariosPath, scenariosPath } | defaults to {}

| Property | Type | Default | Description | | ------------------- | --------- | ------------------- | ------------------------------------------------------------------------------------------ | | port | number | 3000 | Port that the http server runs on. | | uiPath | string | / | Path that the UI will load on. http://localhost:{port}{uiPath} | | modifyScenariosPath | string | /modify-scenarios | API path for modifying scenarios. http://localhost:{port}{modifyScenariosPath} | | resetScenariosPath | string | /reset-scenarios | API path for resetting scenarios. http://localhost:{port}{resetScenariosPath} | | scenariosPath | string | /scenarios | API path for getting scenarios. http://localhost:{port}{scenariosPath} | | cookieMode | boolean | false | Whether or not to store scenario selections in a cookie rather than directly in the server |

Types

Mock

HttpMock | GraphQlMock

See HttpMock and GraphQlMock for more details.

HttpMock

{ url, method, response }

| Property | Type | Default | Description | | -------- | ----------------------------------------------------- | ----------- | --------------------------------------------------------------------- | | url | string / RegExp | required | Path of endpoint. Must start with /. | | method | 'GET' / 'POST' / 'PUT' / 'DELETE' / 'PATCH' | required | HTTP method of endpoint. | | response | undefined / Response / HttpResponseFunction | undefined | Response, HttpResponseFunction. |

Response

{ status, headers, data, delay }

| Property | Type | Default | Description | | -------- | ---------------------------- | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | status | number | 200 | HTTP status code for response. | | headers | object / undefined | See description | Key/value pairs of HTTP headers for response. Defaults to undefined when response is undefined, adds 'Content-Type': 'application/json' when response is not undefined and Content-Type is not supplied. | | data | null / string / object | undefined | Response data | | delay | number | 0 | Number of milliseconds before the response is returned. |

HttpResponseFunction

function({ query, body, params, context, updateContext }): response | Promise<response>

| Property | Type | Default | Description | | ------------- | ------------------------ | ---------------------------------- | ----------------------------------------------------------------------------------------------------------------- | | query | object | {} | query object as defined by express. | | body | object | {} | body object as defined by express. | | params | object | {} | params object as defined by express. | | context | object | {} | Data stored across API calls. | | updateContext | Function | partialContext => updatedContext | Used to update context. partialContext can either be an object or a function (context => partialContext). | | response | undefined / Response | required | Response. |

GraphQlMock

{ url, method, operations }

| Property | Type | Default | Description | | ---------- | ------------------ | ---------- | -------------------------------------------------------------------------------------- | | url | string | required | Path of endpoint. | | method | 'GRAPHQL' | required | Indentifies this mock as a GraphQlMock. | | operations | Array<Operation> | required | List of operations for GraphQL endpoint. See Operation for more details. |

Operation

{ type, name, response }

| Property | Type | Default | Description | | -------- | ----------------------------------------------------------- | ----------- | ----------------------------------------------------------------------------------------- | | type | 'query' / 'mutation' | required | Type of operation. | | name | string | required | Name of operation. | | response | undefined / GraphQlResponse / GraphQlResponseFunction | undefined | GraphQlResponse, GraphQlResponseFunction. |

GraphQlResponse

{ status, headers, data, delay }

| Property | Type | Default | Description | | -------- | ------------------------------------------ | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | status | number | 200 | HTTP status code for response. | | headers | object / undefined | See description | Key/value pairs of HTTP headers for response. Defaults to undefined when response is undefined, adds 'Content-Type': 'application/json' when response is not undefined and Content-Type is not supplied. | | data | { data?: null / object, errors?: array } | undefined | Response data | | delay | number | 0 | Number of milliseconds before the response is returned. |

GraphQlResponseFunction

function({ variables, context, updateContext }): response | Promise<response>

| Property | Type | Default | Description | | ------------- | ------------------------------- | ---------------------------------- | ----------------------------------------------------------------------------------------------------------------- | | variables | object | {} | variables sent by client. | | context | object | {} | Data stored across API calls. | | updateContext | Function | partialContext => updatedContext | Used to update context. partialContext can either be an object or a function (context => partialContext). | | response | undefined / GraphQlResponse | required | GraphQlResponse. |

Allowing for multiple responses

Sometimes you may want an endpoint to respond with different status codes depending on what is sent. It is the recommendation of this package that this can be achieved by using scenarios. However, given response can be a function, it is possible to respond with a different value for the status, headers, data and delay properties:

const mock = {
  url: '/some-url',
  method: 'GET',
  response: ({ body }) => {
    if (body.name === 'error1') {
      return {
        status: 400,
        data: { message: 'something went wrong' },
        delay: 1000,
      };
    }

    if (body.name === 'error2') {
      return {
        status: 500,
        data: { message: 'something else went wrong' },
        delay: 2000,
      };
    }

    if (body.name === 'notFound') {
      return {
        status: 404,
        data: { message: 'no data here' },
      };
    }

    // Default status is 200
    return { data: { message: 'success' } };
  },
};