Need private packages and team management tools?Check out npm Teams »

helio-api-boilerplate

0.7.2 • Public • Published

Helio API Boilerplate

Built with Science

Helio is an easily extensible backend utilizing Express.js, Mongoose, JWT, and User registration/authentication.


Build Status Dependency Status Last Commit Open issues Closed issues Known Vulnerabilities

Version GitHub license Standardjs PRs Welcome Hire Me Gitter Beerpay Beerpay

“This is what I have learned, Malenfant. This is how it is, how it was, how it came to be.”

― Stephen Baxter, Manifold: Time

Tweet Help spread the word and share this project!


asciicast



Overview

Helio was created to address the scenario where you find yourself creating multiple projects that use Express.js/Mongoose and having to reinvent the wheel every time, implementing an authentication system, routers, etc.

Using Helio, you can quickly build new projects with a ready-to-deploy server.

It's designed to be flexible, so you can create a new project in these ways:

Important Notes

Click to collapse/expand

Most of the examples are using ES6 imports, so if you're not using Helio as a boilerplate, you'll need to setup your babel/webpack build environment or replace the import statements with:

const Helio = require('helio-api-boilerplate').default

const SomeMod = require(<package>).default

There are two required options, and these can be set in any of the following ways:

  • Environment Variables
    • DB_URI=[your MongoDB Connection URI]
    • JWT_SECRET=[a random string to sign user tokens]
  • Module Options
    • new Helio({ dbUri: 'mongo-uri', jwtSecret: 'my-secret })
  • CLI Options
    • helio --dbUri mongo-uri --jwtSecret my-secret

By default, a server will load the following mods:

  • helio-mod-users
  • helio-mod-jokes
  • src/mods/example-mod
  • src/mods/blog-mod

A bit about mods and models

Mods are nothing more than objects with an Express router and some sugar.

Models are just normal Mongoose models.

The mods will handle routes under a given /path. Models are not loaded directly by mods, but are provided by Helio when the mod is instantiated with the needModels property, which is an array of models to be loaded when the mod is instantiated. The mod can then use its own schemas to extend the models provided by Helio.

If that's confusing, just look at the example-mod and you'll see what's going on.

Using as a boilerplate

Click to collapse/expand

You probably want to use this repository as a template, then replace the clone URL and directory name below.

git clone https://github.com/mathiscode/helio-api-boilerplate.git
cd helio-api-boilerplate
cp .env.example .env # use the example environment; modify as needed 
yarn # to install dependencies; or npm install 
yarn server # for development; or npm run server 
yarn start # for production; or npm start 

You'll want to start by exploring src/config.js and src/index.js.

Using from the command line

Click to collapse/expand

Arguments that you don't pass to the CLI will use env variables or defaults.

Without installing

npx helio-api-boilerplate --help

Installing globally

yarn global add helio-api-boilerplate # or npm install -g helio-api-boilerplate 
helio --help

Installing locally

yarn add helio-api-boilerplate # or npm install helio-api-boilerplate 
npx helio --help

Specifying mods and models from the CLI

You can override the default mods and models with the --mod and --model arguments.

  • Mod Syntax: modRootPath:pathOrModule
  • Model Syntax: modelName:pathOrModule

If you want to use one of Helio's default models (eg. User, BlogPost, or TokenWhitelist), use the Helio:ModelName syntax.

Examples:

helio --mod /user:helio-mod-users --model Helio:User --model Helio:TokenWhitelist
helio --mod /myMod:/path/to/myMod --model MyModel:/path/to/MyModel

Importing as a module

Click to collapse/expand
yarn add helio-api-boilerplate helio-mod-users
import Helio from 'helio-api-boilerplate'
import UsersMod from 'helio-mod-users'
import UsersModel from 'helio-api-boilerplate/src/models/User'
import TokenWhitelist from 'helio-api-boilerplate/src/models/TokenWhitelist'
 
const server = new Helio({
  // DB URI of a MongoDB instance
  dbUri: 'mongodb+srv://USER:PASS@HOST/myapp?retryWrites=true', // required or DB_URI env
  // Random string used to sign JWT tokens
  jwtSecret: 'supersecret123!', // required or JWT_SECRET env
  // Timeout for JWT tokens
  jwtTimeout: '1h',
  // Port number for the server
  port: process.env.PORT || 3001,
  // Prevent automatically listening on startup
  noListen: false,
  // Log to DB
  logToDB: false,
  // Operational log output to console
  consoleLog: true,
  // Errors output to console
  consoleErrors: true,
  // Path to serve static content
  staticPath: null,
  // Verbose output from mongoose operations
  mongooseDebug: false,
  // Options passed to the Mongoose connect method
  // (defaults fix deprecation notices)
  mongooseOptions: null,
  // Whether to show the figlet banner in the console
  hideBanner: false,
  // Text for the figlet banner
  bannerText: 'Helio',
  // Figlet font name (from https://github.com/patorjk/figlet.js/tree/master/fonts)
  bannerFont: 'The Edge',
 
  // Root handler; to handle requests to /
  // Do not use this if you just want to serve an index.html
  rootHandler: (req, res, next) => {
    res.json({
      name: process.env.HELIO_NAME || 'Helio API Server'
    })
  }
 
  // Mods that will be loaded
  mods: [
    { path: '/user', module: UsersMod }
  ],
 
  // Models that will be provided to mods
  // It's recommended that you at least include:
  // { name: 'TokenWhitelist', model: TokenWhitelistModel }
  models: [
    { name: 'Users', model: UsersModel },
    { name: 'TokenWhitelist', model: TokenWhitelistModel }
  ],
 
  // Custom middleware that will run before mods
  // May be simple functions (req, res, next) or Express modules
  middleware: [
    (req, res, next) => {
      console.log('Hello from custom middleware')
      return next()
    }
  ]
})

On the server object, you can access the following properties and methods:

Properties

  • app: the Express app object
  • options: the options that were used to create the Helio server
  • db: the Mongoose connection object

Methods

  • listen(): start Helio listening for requests - only useful if using noListen

Mods

Click to collapse/expand

Helio Mods are the easiest way to extend Helio and they remove the need to modify core routes.

They're just classes, so don't feel overwhelmed.

Using packaged mods

  1. yarn add <package> or npm install <package> (eg. helio-mod-jokes)
  2. Boilerplate Method
    • Modify src/config.js:
      • import ModName from <package> under the "Import mods" comment
      • Add an object to the Mods array under the "Set mods to load" comment:
        • { path: '/my-mod', module: ModName }
  3. CLI Method
    • helio --mod /my-mod:<package>
  4. Module Method
    • import ModName from <package>
    • new Helio({ mods: [{ path: '/my-mod', module: ModName }] })

Creating custom mods

  1. Boilerplate Method
    • Create a folder for your mod in src/mods and create an index.js
    • Modify src/config.js:
      • import MyMod from './mods/my-mod' under the "Import mods" comment
      • Add an object to the Mods array under the "Set mods to load" comment:
        • { path: '/my-mod', module: MyMod }
  2. CLI Method
    • helio --mod /my-mod:./path/to/my-mod
  3. Module Method
    • import MyMod from './path/to/my-mod'
    • new Helio({ mods: [{ path: '/my-mod', module: MyMod }] })
  4. For reference, see:

Official Helio mods

  • Helio Users - npm

    • yarn add helio-mod-users or npm install helio-mod-users
    • import UsersMod from 'helio-mod-users'
    • { path: '/user', module: UsersMod }
  • Helio Jokes - npm

    • yarn add helio-mod-jokes or npm install helio-mod-jokes
    • import JokesMod from 'helio-mod-jokes'
    • { path: '/jokes', module: JokesMod }

Deploying

Click to collapse/expand

Heroku

  1. heroku git:remote -a your-app-name
  2. heroku plugins:install heroku-config
  3. cp .env.heroku.example .env.heroku
  4. Modify .env.heroku as needed
  5. heroku config:push -f .env.heroku -a your-app-name
  6. git push heroku master

Testing

Click to collapse/expand

The normal testing process is handled with yarn test, which does the following:

If you don't want to enforce the standard code style, just remove standard && from the package.json test script.

The more comprehensive testing during development happens with Postman collections and newman. More documentation about that will come soon.

For now, if you're interested in using it, collections are found in test/postman/collections and while the development server is running (with yarn server), run yarn test:mods

I don't like how Helio does [X]

In essence, this is a ready-to-deploy Express server, so if you're comfortable with Express you can easily modify any part of it to fit your needs. Please feel free to gut the code and just keep what makes your life easier! 😁

Is it perfect?

😐

Install

npm i helio-api-boilerplate

DownloadsWeekly Downloads

0

Version

0.7.2

License

MIT

Unpacked Size

940 kB

Total Files

48

Last publish

Collaborators

  • avatar