server/api/utils/api

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
Name Type Attributes Description
model function

The database model to use to fetch the resource.

resourceName string

The name of the API resource (used in error messages).

column string <optional>

The database column containing the identifier (defaults to api_id).

urlParameter string <optional>

The URL parameter containing the resource identifier (defaults to id).

queryHandler function <optional>

An optional function to modify the database query (it will receive the query and the request as arguments, and should return the updated query).

requestProperty string <optional>

The request property to attach the fetched record to (defaults to options.resourceName).

eagerLoad Array.<string> <optional>

Relations to eager-load when fetching the resource.

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