- All application code will reside in the
/lib
directory. - Use plugins to organize everything
I like to organize everything (business logic, routes, server extensions, etc.) into plugins. This makes the code easy to navigate and test. If your application grows beyond what can be contained in a single application, the plugins can be moved into separate repositories and maintained there.
The lib/services
directory is used for plugins that are re-used across many parts of the application such as configuration and authentication.
Location: /lib/services/config.js
Purpose: Use nconf to combine environment variables with default config options. The config object can be accessed anywhere in the application via server.plugins.config.app
.
Example:
var env = server.plugins.config.app.get('NODE_ENV');
Location: /lib/services/errors
Purpose: Use create-boom-error to create boom errors that can be easily accessed and thrown to the API.
Example:
throw new server.plugins.errors.api.ErrorName();
Location: /lib/services/db.js
Purpose: Use knex.js to create a connection to a database. The config is exposed for testing purposes as well as the knex
object for running queries.
Example:
// Access knex config
var dbConfig = server.plugins.db.config;
// Access instantiated knex object to run database queries
var knex = server.plugins.db.knex;
Location: /lib/services/models
Purpose: Use the Bookshelf ORM and the https://github.com/lob/hapi-bookshelf-models plugin to load our models and have them available across the application. This project is already configured to use the knex.js migration and seed utility. It provides db configuration via /db/knexfile.js
, and the relevant commands are exposed in the package.json
Example:
// Access the registered `User` model
var User = server.plugins.bookshelf.model('User');
# Create New Migration
npm run create-migration <name>
# Run Migrations
npm run migrate
# Rollback Migrations
npm run rollback
# Create New Seed
npm run create-seed <name>
# Run Seeds
npm run seed
Location: /lib/services/authentication.js
Purpose: Use hapi-auth-basic to enforce a simple API key based authentication for our API users.
The tests for the application reside in the /test
directory. The structure of the directory mirrors the code in /lib
and files are suffixed with .test.js
rather than just .js
. I am using lab for the testing framework and code for the assertion library. The test suite can be run using npm test
. I will be enforcing 100% code coverage on this repository.