Skip to content

Set default resource #22

@AdamQuadmon

Description

@AdamQuadmon

I'm trying to have synth returning a default resource.

The following code in the back/back-app.js works, is there a better way to do it?

/**
 * Array of available resources.
 * Those resource names should not be used as url slugs for pages.
 *
 * @type {string[]}
 */
var availableResources = ['categories', 'pages'];

var defaultPage = 'home';

/**
 * Return an array of path parts.
 * It removes the first part of the array if it's empty.
 *
 * @param {string} path
 * @returns {Array}
 */
var getPathTokens = function (path) {
  /**
   * Array of url path parts.
   *
   * For a path like `/` it returns an array
   * of two empty strings.
   *
   * For a path like `/my-slug` it returns an array
   * of two strings: ['', 'my-slug']
   *
   * @type {Array}
   */
  var pathTokens = path.split('/');

  if (pathTokens[0] === '') {
    pathTokens = pathTokens.splice(1);
  }

  return pathTokens;
};

synth.app.use(function (req, res, next) {

  var currentPathTokens = getPathTokens(req.originalUrl);

  /**
   * If `currentPathTokens` contains only one element
   * and this element is not one of the available resources
   * it assumes it's a page slug and change the route to point
   * to `/page/slug-name`.
   *
   * If `currentPathTokens[0]` is empty it routes to the default one.
   */
  if (currentPathTokens.length === 1
    && currentPathTokens[0].indexOf(availableResources) === -1) {
    req.url = '/pages/' + (currentPathTokens[0] || defaultPage);
  }

  next();
});

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions