exframe-stubs
v1.0.0
Published
Wrapper around nock to stub endpoints using json configuration
Downloads
3
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:
- self - An object containing the intercepted request. In certain cases, this information may be useful for logging requests or forming the response body.
- statusCode - The status code specified in the endpoint object (or undefined if not specified)
- 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;