npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

weare-pages

v0.2.5

Published

Routing helper for pages

Downloads

3

Readme

Repository https://npm.dev.studioweare.com

WE_ARE Pages

Handle many properties of a page (localized) and generate routes.

Installation

$ npm install weare-pages

Usage

var express = require('express');
var app = express();
var pages = require('weare-pages')({
  locales: ['en', 'fr']
});

// "router" can also be setted when the module is initialized.
pages.setRouter(app);

// The main controller.
var mainController = function (req, res) {
  // Getting the "title" attribute of the current page in the current locale.
  res.send(req.page.getTitle());
};

// Pages definition.
pages.addPage('index', {
  path: '',
  ctrl: mainController,
  title: 'Home',
  // The main locale in this case is "en". These are properties for other locales.
  altLocales: {
    fr: {
      title: 'Accueil',
    }
  }
})
// Can be chained.
.addPage('bikeCategory', {
  path: '/bikes/:cat',
  // Middlewares can be added.
  middlewares: [function (req, res, next) {
    req.page.title = req.params.cat.charAt(0).toUpperCase() + req.params.cat.slice(1);
    next()
  }]
  altLocales: {
    fr: {
        path: '/velos/:cat',
    }
  }
});

// Controller can be setted after the page is added.
pages.get('bikeCategory').setCtrl(mainController);

// Generate routes in all locales for each page.
pages.generateRoutes();

This will generate these routes:

  • /
  • /fr
  • /bikes/:cat
  • /fr/velos/:cat

Each show the title attribute of the page. For the bikeCategory page, the title is setted as the :cat param later, in a middleware. There's no /en directory here cause the default settings for the localizationMode is setted to directoriesButHideDefault so the defaultLocale don't have directory. So if you don't have only one locale which is fr setted in locales, you'll not have to worry about locale directories in your routes.

Chainable

pages.addPage('index')
  .setPath('')
  .setCtrl(mainController)
  .setTitle('Home').setTitle('Accueil', 'fr')
;
pages.addPage('bikeCategory')
  .setPath('/bikes/:cat').setPath('/velos/:cat', 'fr')
  .addMiddleware(function (req, res, next) {
    req.page.title = req.params.cat.charAt(0).toUpperCase() + req.params.cat.slice(1);
    next()
  })
;

Function references

Functions available for both the Pages object and Page.

Pages

What you get when initializing the module.

setRouter

/**
 * Set the router. This will also add a middleware to the router that will add
 * this module instance to "req.pages" as well as adding the "app.mountpath" to
 * "pages.mountpath" if there's one so "fullPath" will be generated correctly.
 *
 * @param Router router
 *   The router.
 *
 * @return Pages
 *   This module. So other actions can be chained.
 */

addGlobalMiddleware

/**
 * Add a middleware to the group of middlewares that will be executed right after
 * the locale will be setted using the "path".
 *
 * @param Function globalMiddleware
 *   The middleware.
 *
 * @return Pages
 *   This module. So other actions can be chained.
 */

addPage

/**
 * Add a page.
 *
 * @param String slug
 *   The page slug.
 * @param Object page
 *   Optionnal.
 *   {
 *     // The controller, can be assign later with the "Page.setCtrl" function.
 *     ctrl: Function,          // The controller.
 *     path: String,            // The "mainLocale" path.
 *     title: String,           // The "mainLocale" title.
 *     description: String,     // The "mainLocale" description.
 *     image: String,           // The "mainLocale" image.
 *     // Middlewares assign to the route of this page.
 *     middlewares: [Function], // The "mainLocale" middlewares.
 *     // Additionnal infos to stick with the page. Can be access with "Page.getMeta" function.
 *     metas: Object,           // The "mainLocale" metas.
 *     // Locales' specific values. If a value is not specified, the "mainLocale" one will be use.
 *     altLocales: {
 *       '{locale}': {
 *         path: String,            // The "{locale}" path.
 *         title: String,           // The "{locale}" title.
 *         description: String,     // The "{locale}" description.
 *         image: String,           // The "{locale}" image.
 *         middlewares: [Function], // The "{locale}" middlewares.
 *         metas: Object,           // The "{locale}" metas.
 *       }
 *     }
 *   }
 *
 * @return Pages
 *   The new Page, so additionnal action can be chained.
 */

get

/**
 * Get a specific page by slug.
 *
 * @param String slug
 *   The page slug.
 *
 * @return Page
 *   The page object.
 */

getAll

/**
 * Get all pages.
 *
 * @return Array
 *   An array of all the page objects.
 */

getLocales

/**
 * Get locales.
 *
 * @return Array
 *   The setting "locales".
 */

generateRoutes

/**
 * Generate the routes of all the pages.
 *
 * @return Pages
 *   This module. So multiple "addPage" can be chained.
 */

Page

A single page, available in req.page, res.locals.page or by using pages.get('{page-slug}').

The Page object keep a reference to the Pages object: Page.pages.

getSlug

Get the slug of the page.

Some getters/setters

These function get the page properties in the current locale. However, a locale argument can be passed to get the property in a specific locale.

  • getTitle(locale);
  • getDescription(locale);
  • getImage(locale);
  • getPath(locale) (This is the raw path as specified when the page was added.);
  • getMiddlewares(locale);

These function set the page properties in the current locale. However, a locale argument can be passed to set the property in a specific locale. The return is the page itself so multiple setters can be chained.

  • setTitle(value, locale);
  • setDescription(value, locale);
  • setImage(value, locale);
  • setPath(value, locale);

addMiddleware

Add an additionnal middleware for this page. These middlewares will be executed after the global middlewares setted with Page.addGlobalMiddleware.

  • middleware argument required.
  • locale optionnal argument.

getFullPath

Give you the path with mountpath, the locale directory (if applicable) and prePath . If the path contain parameters (/users/:id), this function will use the Page.filterPath function to try to recreate the correct path by using req.params.

There's actually no support for RegExp paths. If you have specific need, you can override the Page.filterPath function in a middleware.

  • locale optionnal argument.

getMeta

Will get the meta page properties in the current locale.

  • prop String required argument. This use the same syntax as Lodash's _.get function (path argument);
  • locale optionnal argument to force the locale.

setMeta

Will set the meta page properties in the current locale.

  • prop String required argument. This use the same syntax as Lodash's _.get function (path argument);
  • value required argument.
  • locale optionnal argument to force the locale.

getLocale

Get the locale that has been setted for this page.

setLocale

Set the locale of this page.

  • locale argument required.

setCtrl

Set the page's controller if not already setted when the page was added.

generateRoutes

Generate this single page. If you use Pages.generateRoutes after, this page will be generate 2 times which is probably not a what you want.

Settings

instance (String)

When you first require this module, it create an instance that is cached and return it whenever you require it again. If you need another instance of the module to run aside for, let's say, a different mount path (like for the weare-major-tom CMS module), you can use this option to specify a name to access a specific instance.

Ex: major-tom

prePath (String)

Add a prefix to all path. *Will be place just after the locale directory. Useful to emulate the Express' mount feature. If you use the mount feature directly, you'll end up with path like /blog/en/posts.

Ex: /blog

localizationMode (String)

How routes paths are build considering locales.

directoriesButHideDefault (default setting)

Add a locale directory before each path except for the defaultLocale.

Ex: /, /fr, /bikes, /fr/velos

directories

Add a locale directory before each path.

Ex: /en, /fr, /en/bikes, /fr/velos

path

The locale of the page will be determined by the path, which will not be altered. Be sure to have setted a different path for each of your locale. Not doing so will create all your routes for this page with the same path.

Ex: /home, /accueil, /bikes, /velos

locales (Array)

List of locales in which to create routes from. The routes will be create in the same order as this array.

mainLocale (String)

Root properties of a page are assigned to this locale. Properties assigned to other locales are in the alternateLocale property of a page.

Default to the first locales.

defaultLocale (String)

This is the default language from which to get properties of a page. If it's different than the mainLocale, default properties will be fetch from the alternateLocale property of pages, if the according locale is there.

Default to the mainLocale.

Example

// Simplified page.
{
  title: 'Vélos',
  path: '/velos',
  altLocales: {
    en: {
      title: 'Bikes',
      path: '/bikes'
    }
  }
}

If settings are like these:

{
  localizationMode: 'directoriesButHideDefault',
  locales: ['en', 'fr'],
  mainLocale: 'fr',
  defaultLocale: 'en'
}

These will be the routes generated:

  • /bikes;
  • /fr/velos.

In a controller, this call req.page.getTitle('es') will return Bikes cause es is not supported and the default locale is en.

This feature can be use as a fail safe if you define all your pages and the default locale as to change.