API utilities.
- Source:
Methods
(static) fetcher(options) → {function}
- Source:
Creates a middleware function that will fetch the record identified by the current URL and attach it to the request. If no record is found, an HTTP 404 Not Found response will be sent.
const fetcher = require('./fetcher');
const User = require('./models/user');
const fetchUser = fetcher({
model: User,
resourceName: 'user'
});
router.get('/api/users/:id', fetchUser, (req, res) => {
// req.user has been fetched, or HTTP 404 not found sent
res.send(req.user);
});
Parameters:
Name | Type | Description | ||||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
options |
object | Fetcher options. Properties
|
Returns:
A middleware function.
- Type
- function
(static) route(routeFunc) → {function}
- Source:
Converts a promise-based function into an Express middleware function.
route(async (req, res) => {
// Asynchronous code
const data = await fetchData();
// Errors caught by promise chain and automatically passed to next(err)
if (!data) {
throw new Error('No data available');
}
res.send(data);
});
Parameters:
Name | Type | Description |
---|---|---|
routeFunc |
function | The asynchronous route implementation. |
Returns:
A middleware function.
- Type
- function
(static) transactionalRoute(routeFunc) → {function}
- Source:
Converts a promise-based function into an Express middleware function (like
route
), and wraps the route into a database transaction.
Any error thrown will cause the transaction to be rolled back.
transactionalRoute(async (req, res) => {
// Asynchronous code
const user = await fetchUser();
// Any error will roll back the transaction.
await user.save(req.body);
res.send(user);
});
Parameters:
Name | Type | Description |
---|---|---|
routeFunc |
function | The asynchronous route implementation. |
Returns:
A middleware function.
- Type
- function