Create a Trailpack for Trails

Hi guys ! Here you will learn how to create a customized Trailpack for Trails. You will see project’s structure and how to run and test it before publishing on npm. Hope you’re ready !

NOTE: This tutorial assumes that you have previously installed Node.js 4.0.0 (or more) on your machine, also have a Trails project created (see Getting started with trails).

What is a Trailpack ?

If you followed my first tutorial carefully, you already know this ! But I do not blame you if you forgot ^^, a Trailpack is a simple module which extends Trails functionalities. It can be a web server like express4, a tasks runner like grunt…

Installation

Trailpack can be generated with yeoman. So if you didn’t install it, you should do it now :

WARNING: if you don’t use yo to generate API, don’t forget to add those into index.js as in following: if it’s a model, add it in models/index.js, if it’s a controller add it in controllers/index.js… If your file is not in index.js, it will be ignored !

WARNING 2:
If your Trailpacks need Models, Controllers and Policies so your class must implement trails-model, trails-controller and trails-policy in order to work with more than one orm/webserver. Those class need to implement Waterline interface definition (models) and Hapi (controllers, policies).

Configuration

You can put your own file’s configuration here. As you can see, a trailpack.js file communicates Trails you provide some APIs and configuration to the project (provides field). But it allows you too to configure the lifcycle of your trailpack. Indeed, if your trailpack needs to wait for some events or emit ones, you can put those here :

First, you want to rename Archetype by your Trailspack’s name (here MyTrailpack). As you can see, you have three methods in it :

validate

configure

initialize

WARNING : if you want to create a Web Server or ORM compatible Trailpack you need to use trailpack-webserver / trailpack-datastore instead of trailpack. For more information see those repo : trailpack-webserver and trailpack-datastore

Validate

Validate function is the first called. As it’s named, you can check if the configuration of your trailpack is correct (if it’s needed). For example, the hapi trailpack checks if web server configuration under config/web.js is correct. In this tutorial we’ll just add some log.

At last, we call Promise.resolve() to tell Trails our Trailpack is valid, if it’s not we can call Promise.reject()

Configure

Next come the configure function, this method is called after all events waiting in your Trailpack (see Configuration section below).
You can configure your Trailpack removing the hapi Trailpack. Here, it’s created the web server and configured all routes bind controllers and policies…