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

koa-mock-response

v1.0.0

Published

Mock a Rest API or any backend service.

Downloads

9,005

Readme

view on npm npm module downloads Build Status Dependency Status js-standard-style

koa-mock-response

Mocks give you full control over the response headers and body returned to the client. They can be used to return anything from a simple html string to a resourceful REST API. Typically, they're used to mock services but can be used for anything.

In the config, define an array called mocks. Each mock definition maps a route to a response. A simple home page:

{
  "mocks": [
    {
      "route": "/",
      "response": {
        "body": "<h1>Welcome to the Mock Responses example</h1>"
      }
    }
  ]
}

Under the hood, the property values from the response object are written onto the underlying koa response object. You can set any valid koa response properies, for example type:

{
  "mocks": [
    {
      "route": "/",
      "response": {
        "type": "text/plain",
        "body": "<h1>Welcome to the Mock Responses example</h1>"
      }
    }
  ]
}

Conditional Response

To define a conditional response, set a request object on the mock definition. The request value acts as a query - the response defined will only be returned if each property of the request query matches. For example, return an XML response only if the request headers include accept: application/xml, else return 404 Not Found.

{
  "mocks": [
    {
      "route": "/two",
      "request": { "accepts": "xml" },
      "response": {
        "body": "<result id='2' name='whatever' />"
      }
    }
  ]
}

Multiple Potential Responses

To specify multiple potential responses, set an array of mock definitions to the responses property. The first response with a matching request query will be sent. In this example, the client will get one of two responses depending on the request method:

{
  "mocks": [
    {
      "route": "/three",
      "responses": [
        {
          "request": { "method": "GET" },
          "response": {
            "body": "<h1>Mock response for 'GET' request on /three</h1>"
          }
        },
        {
          "request": { "method": "POST" },
          "response": {
            "status": 400,
            "body": { "message": "That method is not allowed." }
          }
        }
      ]
    }
  ]
}

Dynamic Response

The examples above all returned static data. To define a dynamic response, create a mock module. Specify its path in the module property:

{
  "mocks": [
    {
      "route": "/four",
      "module": "/mocks/stream-self.js"
    }
  ]
}

Here's what the stream-self module looks like. The module should export a mock definition (an object, or array of objects, each with a response and optional request). In this example, the module simply streams itself to the response but you could set body to any valid value.

const fs = require('fs')

module.exports = {
  response: {
    body: fs.createReadStream(__filename)
  }
}

Response function

For more power, define the response as a function. It will receive the koa context as its first argument. Now you have full programmatic control over the response returned.

module.exports = {
  response: function (ctx) {
    ctx.body = '<h1>I can do anything i want.</h1>'
  }
}

If the route contains tokens, their values are passed to the response. For example, with this mock...

{
  "mocks": [
    {
      "route": "/players/:id",
      "module": "/mocks/players.js"
    }
  ]
}

...the id value is passed to the response function. For example, a path of /players/10?name=Lionel would pass 10 to the response function. Additional, the value Lionel would be available on ctx.query.name:

module.exports = {
  response: function (ctx, id) {
    ctx.body = `<h1>id: ${id}, name: ${ctx.query.name}</h1>`
  }
}

RESTful Resource example

Here's an example of a REST collection (users). We'll create two routes, one for actions on the resource collection, one for individual resource actions.

{
  "mocks": [
    { "route": "/users", "module": "/mocks/users.js" },
    { "route": "/users/:id", "module": "/mocks/user.js" }
  ]
}

Define a module (users.json) defining seed data:

[
  { "id": 1, "name": "Lloyd", "age": 40, "nationality": "English" },
  { "id": 2, "name": "Mona", "age": 34, "nationality": "Palestinian" },
  { "id": 3, "name": "Francesco", "age": 24, "nationality": "Italian" }
]

The collection module:

const users = require('./users.json')

/* responses for /users */
const mockResponses = [
  /* Respond with 400 Bad Request for PUT and DELETE - inappropriate on a collection */
  { request: { method: 'PUT' }, response: { status: 400 } },
  { request: { method: 'DELETE' }, response: { status: 400 } },
  {
    /* for GET requests return a subset of data, optionally filtered on 'minAge' and 'nationality' */
    request: { method: 'GET' },
    response: function (ctx) {
      ctx.body = users.filter(user => {
        const meetsMinAge = (user.age || 1000) >= (Number(ctx.query.minAge) || 0)
        const requiredNationality = user.nationality === (ctx.query.nationality || user.nationality)
        return meetsMinAge && requiredNationality
      })
    }
  },
  {
    /* for POST requests, create a new user and return the path to the new resource */
    request: { method: 'POST' },
    response: function (ctx) {
      const newUser = ctx.request.body
      users.push(newUser)
      newUser.id = users.length
      ctx.status = 201
      ctx.response.set('Location', `/users/${newUser.id}`)
    }
  }
]

module.exports = mockResponses

The individual resource module:

const users = require('./users.json')

/* responses for /users/:id */
const mockResponses = [
  /* don't support POST here */
  { request: { method: 'POST' }, response: { status: 400 } },

  /* for GET requests, return a particular user */
  {
    request: { method: 'GET' },
    response: function (ctx, id) {
      ctx.body = users.find(user => user.id === Number(id))
    }
  },

  /* for PUT requests, update the record */
  {
    request: { method: 'PUT' },
    response: function (ctx, id) {
      const updatedUser = ctx.request.body
      const existingUserIndex = users.findIndex(user => user.id === Number(id))
      users.splice(existingUserIndex, 1, updatedUser)
      ctx.status = 200
    }
  },

  /* DELETE request: remove the record */
  {
    request: { method: 'DELETE' },
    response: function (ctx, id) {
      const existingUserIndex = users.findIndex(user => user.id === Number(id))
      users.splice(existingUserIndex, 1)
      ctx.status = 200
    }
  }
]

module.exports = mockResponses

© 2017-20 Lloyd Brookes [email protected].