api-delay
- Copyright:
- 2019 Kevin Godell
Example
Example usage for adding delay using middleware and route handlers:
//create express app
const express = require('express');
const app = express();
// require delayNext, delayNextIf from api-delay
const { delayNext, delayNextIf } = require('api-delay');
// add a middleware delay to all routes
app.use(delayNext({ time: 200 }));
// add a conditional middleware delay to all routes
app.use(
delayNextIf({
time: 300,
trigger: receiver => {
// will trigger delay if returns true/truthy
return receiver.req.method === 'POST';
}
})
);
// handle route post login and give slower response to non-premium user
app.post(
'/login',
// route handlers
[
// some middleware to authenticate user and set res.locals.premium value
authMiddleware,
// add 2 second delay to response if user does not have premium status
delayNextIf({
time: 2000,
trigger: receiver => {
return !receiver.res.locals.premium;
}
})
],
(req, res) => {
// send response after delay if finished
res.send('response');
}
);
Methods
(inner) delayNext(optionsopt) → {function}
Creates a middleware or route handler function that delays the call to next().
Parameters:
Name | Type | Attributes | Description | ||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
options |
object |
<optional> |
Configuration options Properties
|
Returns:
A function that can be used as app middleware or route handler structured as:
(req, res, next) => {
// magic delay code
next();
}
- Type
- function
(inner) delayNextIf(options) → {function}
Creates a middleware or route handler function that delays the call to next() if trigger function returns a truthy value.
Parameters:
Name | Type | Description | |||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
options |
object | Configuration options Properties
|
Throws:
-
- options.trigger must be a function
- Type
- TypeError
Returns:
A function that can be used as app middleware or route handler structured as:
(req, res, next) => {
// magic delay code
next();
}
- Type
- function
Type Definitions
Receiver
Object containing request and response properties.
Will be passed to Trigger function.
Type:
- object
Properties:
Name | Type | Description |
---|---|---|
req |
object | Request |
res |
object | Response |
Trigger(receiver) → {boolean}
Function will trigger a delayed called to next() if it returns a truthy value.
Parameters:
Name | Type | Description |
---|---|---|
receiver |
Receiver | Object containing request and response properties. see Receiver |
Returns:
- Return a truthy value
- Type
- boolean