Security News
Node.js EOL Versions CVE Dubbed the "Worst CVE of the Year" by Security Experts
Critics call the Node.js EOL CVE a misuse of the system, sparking debate over CVE standards and the growing noise in vulnerability databases.
connect-mock-api
Advanced tools
Express / Connect middleware for programmable fake APIs
npm install connect-mock-api --save
const express = require('express');
const mockApiMiddleware = require('connect-mock-api').middleware;
const app = express();
const mocks = mockApiMiddleware({
baseUrl: '', //optional
endpoints: [
//... endpoints configuration object here, see below
]
});
app.use(mocks);
app.listen(8000);
Endpoints are objects with the following properties:
method
(string
): The expected methods of the incoming request (default: GET
),path
(string|regexp|function
): the path to match relative to the root URL. If a function it must return a string or a regular expression (default: null
),delay
(number|function
): force a delay in milliseconds for the response. If a function it must return a number (default: 0
),contentType
(string
): Response content type (default: application/json
),template
(*|function
): Response body template. Could be any type of content in relation to the ContentType
parameter.
If a function it will be executed with a params
object and the endpoint
itself as arguments. (default: null
)Note: The params
object contains 3 properties:
$req
: the original express / connect request object$parsedUrl
: The request URL parsed by NodeJS native url.parse
method$routeMatch
: either an object (when path
is a string) or an array of matched segments (when path
is a regular expression). See below for details.$routeMatch
Endpoint's path
configuration could be a plain string, a regular expression or a string with Express-like parameters (see path-to-regexp for details).
$routeMatch
format will vary based on the provided path
:
$routeMatch
will be the resulting array of calling RegExp.prototype.exec
on it$routeMatch
will be and object with named parameters as keys. Note that even numeric parameters will be strings.
Examples:/* Plain string */
{
path: '/api/v1/users'
// /api/v1/users/ -> $routeMatch === {}
}
/* Express-like path */
{
path: '/api/v1/users/:id'
// /api/v1/users/10 -> $routeMatch === {id: '10'}
}
/* RegExp */
{
path: /^\/api\/v1\/users\/(\d+)$/
// /api/v1/users/10 -> $routeMatch === ['/api/v1/users/10', '10']
}
Any key in the response template could be either a plan value or a function. If a function, it will be executed at response time
with a params
object and the endpoint
itself as arguments.
Note: The params
object contains two property:
$req
: the original express / connect request object$parsedUrl
: The request URL parsed by NodeJS native url.parse
method$routeMatch
: either a boolean (when path
is a string) or an array of matched segments (when path
is a regular expression)The baseUrl
configuration option sets up a base URL for every relative endpoint path provided. To override the base URL use absolute URLs.
Note: baseUrl
applies just to string paths.
const mocks = mockApiMiddleware({
baseUrl: '/api/v1/', //optional
endpoints: [
{
// this endpoint will respond at /api/v1/users
path: 'users',
template: {
// ...
}
}, {
// this endpoint will respond at /custom/path
path: '/custom/path',
template: {
// ...
}
}
]
});
const enpoint = {
path: '/api/v1/user',
template: {
name: 'John',
surname: 'Doe'
}
};
const chance = require('connect-mock-api/lib/utils').chance;
const enpoint = {
path: '/api/v1/user',
template: {
name: () => chance.first(),
surname: () => chance.last()
}
};
const chance = require('connect-mock-api/lib/utils').chance;
const enpoint = {
//matches either a male of female user request
path: /\/api\/v1\/user\/(male|female)$/,
template: {
name: (params) => chance.first({
gender: params.$routeMatch[1]
}),
surname: (params) => chance.last({
gender: params.$routeMatch[1]
})
}
};
const chance = require('connect-mock-api/lib/utils').chance;
const enpoint = {
path: '/api/v1/:frag',
template: (params) => {
//calling /api/v1/user
//params.$routeMatch === {'frag': 'user'}
if (params.$routeMatch.frag === 'user') {
return {
name: () => chance.first(),
surname: () => chance.last()
};
}
return {
error: 'Not matching anything'
};
}
};
Note: to parse the request body you should append body-parser middleware to the express / connect middleware list.
const enpoint = {
path: '/api/v1/send',
method: 'POST',
template: (params) => {
if (!params.$req.body.username || !params.$req.body.password) {
return {
success: false,
msg: 'You must provide a username and a password'
};
}
return {
success: true,
msg: 'Succesfully logged in!'
};
}
};
npm install
npm start
to launch a development servertests
folder.npm test
and npm run eslint
Created by Marco Solazzi
FAQs
Fake API server and middleware for connect and express
The npm package connect-mock-api receives a total of 10 weekly downloads. As such, connect-mock-api popularity was classified as not popular.
We found that connect-mock-api demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Critics call the Node.js EOL CVE a misuse of the system, sparking debate over CVE standards and the growing noise in vulnerability databases.
Security News
cURL and Go security teams are publicly rejecting CVSS as flawed for assessing vulnerabilities and are calling for more accurate, context-aware approaches.
Security News
Bun 1.2 enhances its JavaScript runtime with 90% Node.js compatibility, built-in S3 and Postgres support, HTML Imports, and faster, cloud-first performance.