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

exframe-stubs

v1.0.0

Published

Wrapper around nock to stub endpoints using json configuration

Downloads

4

Readme

Exframe Module: Stubs

Overview: This module is used to stub external dependencies that are accessed through http. The module reads configuration information, determines endpoints that need to be stubbed, intercepts outgoing requests to those endpoints, and sends a mock response.

Usage:

Stubs can be used simply by requiring the module in the base node application.

require('exframe-stubs')

By default, the module will look for a configuration file with the path '/stubs/config.js' relative to the root directory of the application. The location of the configuration file can be changed by setting the environment variable, 'EXFRAME_STUBS_PATH' to an alternative path relative to the root directory of the application.

If the path does not exist, an error will be thrown and the service will fail to start. So, do not require exframe-stubs if you don't plan on providing it with a configuration file.

Configuration file

The module expects the configuration file to export a json object with an array of endpoints to stub:

{
  endpoints: [
    {
      root: 'http://example.com',
      method: 'post',
      path: '/pathToStub',
      stubbed: true,
      status: 200,
      reply: (self, statusCode, callback) => callback(null, [statusCode, { message: 'some message' }, { header: 'value' }])
    },
    {
      ...
    }
  ]
}

The following are valid fields for the endpoint objects:

Field | Type | Description | Required ----- | ---- | ----------- | -------- root | string | The root domain of the endpoint to be stubbed | Required path | string | The path of the endpoint to be stubbed | Required stubbed | boolean | Whether the endpoint should be stubbed | Optional (defaults to false) status | integer | The http status code to return in the response. This is passed to the reply function. | Optional (...but a status still needs to be supplied in the callback) reply | function | Invokes a callback with the response status code and response body (see below) | Required

Reply function

The reply function can be as simple or as complex as is necessary. It receives three arguments:

  1. self - An object containing the intercepted request. In certain cases, this information may be useful for logging requests or forming the response body.
  2. statusCode - The status code specified in the endpoint object (or undefined if not specified)
  3. callback - An error first callback function. The first argument is an error (or null, if no error). The second argument is an array with the status code as the first element, the response body as the second element and optional headers as the third element.

For example,

const generateReply = (self, statusCode, callback) => {
  const requestBody = self.requestBody;
  if (requestBody.generateBadRequest) callback(null, [400, { message: 'Something is wrong with the request' }]);
  else callback(null, [200, { message: 'The request succeeded' }]);
}

Here is a subset of what's contained in the self object:

  • self.uri - The root url being stubbed (eg., 'http://www.example.com')
  • self.path - The path of the endpoint (eg., '/thingsToRetrieve')
  • self.method - The method used for the request (eg., 'GET')
  • self.requestBody - The body of the request
  • self.headers - The request headers

Examples

Simple series of endpoints that all return the same response

'use strict';

const theResponse = { message: 'Success!' };

const config = {
  endpoints: [
    {
      root: 'http://api.example.com',
      method: 'post',
      path: '/things',
      stubbed: true,
      reply: (self, statusCode, callback) => callback(null, [200, theResponse])
    },
    {
      root: 'http://api.example.com',
      method: 'post',
      path: '/stuff',
      stubbed: true,
      reply: (self, statusCode, callback) => callback(null, [200, theResponse])
    }
  ]
};

module.exports = config;

Using environment variables to determine whether the endpoint should be stubbed or not

'use strict';

const theResponse = { message: 'Success!' };

const config = {
  endpoints: [
    {
      root: 'http://api.example.com',
      method: 'post',
      path: '/things',
      stubbed: process.env.THINGS_STUBBED,
      reply: (self, statusCode, callback) => callback(null, [200, theResponse])
    },
    {
      root: 'http://api.example.com',
      method: 'post',
      path: '/stuff',
      stubbed: process.env.STUFF_STUBBED,
      reply: (self, statusCode, callback) => callback(null, [200, theResponse])
    }
  ]
};

module.exports = config;

Logging header information before sending the Response

'use strict';

const log = require('exframe-logger').create(process.env.LOGSENE_TOKEN || 'token');

const theResponse = { message: 'Success!' };

const generateResponse = (self, statusCode, callback) => {
  log.info(`harmony-access-key: ${self.headers['harmony-access-key']}`);
  callback(null, [statusCode, theResponse]);
};

const config = {
  endpoints: [
    {
      root: 'http://api.example.com',
      method: 'post',
      path: '/things',
      stubbed: process.env.THINGS_STUBBED,
      status: 200,
      reply: generateResponse
    },
    {
      root: 'http://api.example.com',
      method: 'post',
      path: '/stuff',
      stubbed: process.env.STUFF_STUBBED,
      status: 200,
      reply: generateResponse
    }
  ]
};

module.exports = config;

Determining the response based on information in the Request

'use strict';

const theResponse = { message: 'Success!' };

const generateResponse = (self, statusCode, callback) => {
  if (self.requestBody.error && self.requestBody.error === 'Bad Request') callback(null, [400, { message: 'Bad Request' }]);
  else if (self.requestBody.error && self.requestBody.error === 'Not Found') callback(null, [404, { message: 'Resource Not Found' }]);
  else callback(null, [statusCode, theResponse]);
};

const config = {
  endpoints: [
    {
      root: 'http://api.example.com',
      method: 'post',
      path: '/things',
      stubbed: process.env.THINGS_STUBBED,
      status: 200,
      reply: generateResponse
    },
    {
      root: 'http://api.example.com',
      method: 'post',
      path: '/stuff',
      stubbed: process.env.STUFF_STUBBED,
      status: 200,
      reply: generateResponse
    }
  ]
};

module.exports = config;

Do something asynchronous

'use strict';

const fs = require('fs');

const getResponseFromFile = (filePath) => {
  return new Promise((resolve, reject) => {
    fs.readFile(filePath, 'utf-8', (err, data) => {
      if (err) reject(err);
      resolve(data);
    });
  });
};

const generateResponse = (self, statusCode, callback) => {
  return getResponseFromFile(self.requestBody.filePath)
    .then(data => {
      callback(null, [200, data]);
    })
    .catch(err => {
      callback(err);
    });
};

const config = {
  endpoints: [
    {
      root: 'http://api.example.com',
      method: 'post',
      path: '/things',
      stubbed: process.env.THINGS_STUBBED,
      status: 200,
      reply: generateResponse
    },
    {
      root: 'http://api.example.com',
      method: 'post',
      path: '/stuff',
      stubbed: process.env.STUFF_STUBBED,
      status: 200,
      reply: generateResponse
    }
  ]
};

module.exports = config;

Responding with headers

'use strict';

const log = require('exframe-logger').create(process.env.LOGSENE_TOKEN || 'token');

const theResponse = { message: 'Success!' };

const generateResponse = (self, statusCode, callback) => {
  log.info(`harmony-access-key: ${self.headers['harmony-access-key']}`);
  callback(null, [statusCode, theResponse, { 'harmony-access-key': self.headers['harmony-access-key'] }]);
};

const config = {
  endpoints: [
    {
      root: 'http://api.example.com',
      method: 'post',
      path: '/things',
      stubbed: process.env.THINGS_STUBBED,
      status: 200,
      reply: generateResponse
    },
    {
      root: 'http://api.example.com',
      method: 'post',
      path: '/stuff',
      stubbed: process.env.STUFF_STUBBED,
      status: 200,
      reply: generateResponse
    }
  ]
};

module.exports = config;