Skip to content
This repository has been archived by the owner on Jul 20, 2019. It is now read-only.

Creating a Strategy

Aaron Pettengill edited this page Jan 9, 2018 · 1 revision

The whole purpose of express-reuse is to be able to easily reuse your own express routes in multiple apps. Strategies are how you do this.

At the most basic level, a strategy is a function that takes one argument (the config object) and returns an express router. A valid strategy looks like this:

var express = require('express')
var router = express.Router()

module.exports = (config) => {

  /*
    Anything you want
  */

  return router
}

So how is this any different from just making a router.js file and exporting the router? The key is in the config variable we take as an argument.

The config object

The config object is where a lot of express-reuse's flexibility comes from. It provides strategies with access to the three main modules:

  • database
  • mailer
  • encrypt

2 helper functions:

  • useSerializer
  • useDeserializer

The options object

  • options

And any other custom modules that have been used.

database, mailer and encrypt modules

If a strategy needs to access the database, send an email, or do any encryption, it should do so through these modules. If the default modules don't have what you need, you can easily replace them. While it is possible to simply access your database in your strategy, it is preferable to replace the database module. That way, it's significantly easier to change databases later on (e.g. prototyping in mongoDB and switching to SQL for production).

If you want extend this kind of modularity to your own modules, you can do that to.

useSerializer and useDeserializer

If you want to use passport, express-reuse does a lot of the work for you. The base router of express-reuse already uses passport.initialize() and passport.session(), and express-reuse takes care of passport.serializeUser and passport.deserializeUser.

But in many cases, you need to have control over what happens in serializeUser and deserializerUser. This is where useSerializer and useDeserializer come in. All you have to do is create a function that looks like this:

function yourSerializer(user, serializedUser) {
  //Add properties to serializedUser
  //Example:
  serializedUser.profileName = user.profileName
}

function yourDeserializer(serializedUser, user) {
  //Add properties to user
}

You can also use async/await or return a Promise.

Now that you have your serialize/deserialize function you simply:

config.useSerializer( yourSerializer )
config.useDeserializer( yourDeserializer )

options

This is the options object that gets passed to express-reuse. If you want, you can make your strategy configurable by checking for options on this. You can use the default options or add your own.