Skip to content

Latest commit

 

History

History
621 lines (467 loc) · 31.1 KB

DEVELOPMENT.md

File metadata and controls

621 lines (467 loc) · 31.1 KB

BioPocket Backend Development Guide

Project structure

This is the overall project structure.

File/Directory Contents
bin/www Server launch script
config/index.js Configuration used by the server
config/local.js Optional local configuration file that is automatically loaded by config/index.js
config/local.sample.js Sample local configuration file; copy it to config/local.js and edit
coverage Test coverage report (created after running automated tests)
docs Project documentation (generate all documentation with npm run docs or npm run dev)
docs/api API documentation (created after running npm run docs:api, npm run docs or npm run dev)
docs/coverage Test coverage report (created after running npm test or npm run test:unit)
docs/database XML diagram of the database's relational model (editable with draw.io)
docs/index.html Home page of the project's documentation (with links to GitHub and the API & source code documentation)
docs/src Source code documentation (created after running npm run docs:src, npm run docs or npm run dev)
migrations Knex database migrations (see Database)
server Express server (API implementation with inline JSDoc, RAML documentation, automated tests)
scripts Node.js utility scripts; used in some Scripts below
utils Top-level utilities used in migrations and/or scripts

Server directory

This documents the contents of the server directory.

File/Directory Contents
server/api API implementation
server/api/{subject} Directory containing one or multiple related API resources (e.g. server/api/auth for the /api/auth authentication resource)
server/api/index.js API entrypoint which defines all top-level paths (e.g. /api/auth, /api/users) and generic error handling
server/api/index.raml API RAML documentation entrypoint which includes all other .raml files
server/app.js This file configures and exports the server's Express application
server/db.js This file exports an object that can be used to manage the application's database
server/models Bookshelf database models
server/models/abstract.js Abstract database model from which all other models should inherit
server/spec Automated test utilities
server/spec/expectations Reusable expectations for automated tests
server/spec/fixtures Fixtures to generate data for automated tests
server/spec/chai.js Chai assertion library configuration
server/spec/utils.js Other utility functions for automated tests
server/start.js This file exports a function that opens a connection to the database and starts the server
server/utils Generic server utilities

API resource directory

This documents the contents of one of the server/api/{subject} directory.

These files may be split if they become too large. For example, an .api.spec.js file for automated tests can become quite large and may benefit from being split into one file for each route for readability.

File/Directory Contents
{subject}/{subject}.api.js Route implementations and other middlewares related to the subject
{subject}/{subject}.api.spec.js Automated tests for the routes
{subject}/{subject}.policy.js Default authorization policy for the subject's resources (handling access, parsing and serializing)
{subject}/{subject}.routes.js Express router and route definitions (including authentication, authorization and methods not allowed)
{subject}/{subject}.raml API documentation for the routes
{subject}/{subject}.model.raml API documentation for the main model/resource used in this subject

Configuration & environments

The server can be configured through environment variables or a configuration file. This is implemented in config/index.js and documented in the README.

The server can run in 3 environments:

  • development - Used for local development with live reload.
  • test - Used to run automated tests.
  • production - Used to deploy the server for production.

Which environment the server starts in is determined by the value of the $NODE_ENV environment variable or the env config property. By default, it starts in the development environment.

Local configuration

You may use a local config/local.js configuration file (you can copy the example given in config/local.sample.js) to customize your configuration for local development.

It is recommended that you use this file to vary some of the configuration properties depending on the value of the $NODE_ENV environment variable, as is shown in the example.

Note that the automated tests wipe the database clean when running in the test environment, so you should connect to a different database in the development and test environments.

Scripts

Various npm scripts are available to facilite running the server in development, test or production mode.

Development scripts

Useful scripts for day-to-day development.

Script Purpose
npm run dev Run the server and open the project's documentation with live reload
npm run dev:all Run the server, open the project's documentation with live reload, and automatically run automated tests when code changes
npm run dev:docs Generate the project's documentation and opens it in your browser with live reload
npm run dev:lintAndTest Run code linting and automated tests
npm run dev:lintAndTest:watch Watch for code changes and automatically run code linting and automated tests when it changes
npm run dev:server Run the server in development mode with live reload
npm run dev:test Run code linting and automated tests and automatically re-runs them when code changes
npm run lint Run code linting with ESLint
npm run lint:watch Watch for code changes and automatically run code linting when it changes
npm start Run the server

Database scripts

See the Database section for more information.

Script Purpose
npm run migrate Migrate the configured database to the latest version
npm run migrate:make Create a new migration (e.g. npm run migrate:make -- my_migration_name)
npm run migrate:rollback Roll back the previous migration batch
npm run migrate:test Migrate the configured test database to the latest version
npm run migrate:test:rollback Roll back the previous migration batch on the test database
npm run sample-data Generate sample data for development (see scripts/sample-data.js)
npm run sync Synchronize the database from the data collection interface (see synchronization)

Documentation scripts

See the Documentation section for more information.

Script Purpose
npm run docs Generate the project's documentation (also runs all automated tests to generate the code coverage report)
npm run docs:api Generate the project's API documentation
npm run docs:api:clean Delete the project's API documentation
npm run docs:api:watch Watch the project's API documentation to automatically re-generate it when it changes
npm run docs:clean Delete the project's documentation
npm run docs:database Embed the draw.io XML database diagram into the documentation
npm run docs:publish Publish the project's documentation on GitHub Pages
npm run docs:serve Open the project's documentation in your browser with live reload
npm run docs:src Generate the project's source code documentation
npm run docs:src:clean Delete the project's source code documentation
npm run docs:src:watch Watch the project's source code documentation to automatically re-generate it when it changes
npm run docs:watch Watch the project's documentation to automatically re-generate it when it changes

Testing scripts

See the Testing section for more information.

Script Purpose
npm test Run all automated tests
npm run test:coveralls Send test coverage data to Coveralls (used on Travis CI)
npm run test:debug Run all automated tests with $LOG_LEVEL set to TRACE (all database queries will be logged)
npm run test:watch Watch code for changes and automatically run the automated tests when it changes
npm run start:e2e Run the server in the test environment with appropriate settings

Utility scripts

Script Purpose
npm run anonymize Anonymize the database (see scripts/anonymize.js)
npm run create-admin Create an admin user; requires $ADMIN_EMAIL and $ADMIN_PASSWORD to be set (see scripts/create-admin.js)
npm run doctoc Update the table of contents in README.md and DEVELOPMENT.md

Database

The server requires a PostgreSQL 9.6+ database with the following extensions enabled:

  • postgis to store geographic information.
  • uuid-ossp to generate UUIDs as API identifiers.

The following libraries are used to facilitate working with the database:

  • Knex - SQL query builder.
  • Bookshelf - JavaScript ORM for Node.js built on Knex.
    • bookshelf-touch - Bookshelf plugin to automatically updated created_at and updated_at timestamps.
  • pg Non-blocking PostgreSQL for Node.js (used by Knex).

Migrations

Database migration scripts are written in JavaScript in the migrations directory and managed by Knex. Read the documentation on Knex migrations for more information.

Several database scripts are available as shortcuts to often-used Knex commands.

TODO

Based on the state of the project, the current migrations might not fully implements the tables as described in the biopocket_structure_data_vX.xlsx file on the project SwitchDrive.

This can happen when a story or a task needs a new table, but does not need all the columns or relations that this table have.

To see what needs to be done on which table, please look at the MIGRATIONS_TODO.md file.

Synchronization

Some of the configuration data in the database, such as actions and themes, is managed in a separate project, the data collection interface.

A script is available to synchronize this project's database based on the database of the data collection interface. This script is in the file scripts/sync-interface-data.js, and is also available as an npm script by running the command npm run sync.

To run the script, you must have access to both this project's database and the data collection interface's database. The README documents how to configure the connection URL to the data collection interface's database (e.g. by setting $INTERFACE_DATABASE_URL).

ORM

Database models are implemented with the Bookshelf ORM. You will find them in the server/models directory.

The server has an Abstract base model which all other models extend. It itself extends Bookshelf's base Model.

Query builder

The ORM Query Builder library is used as a wrapper around Bookshelf to facilitate complex database queries with filters, pagination and sorting.

Logging

Console logging is done with the log4js library.

The configuration object (exported by config/index.js) has a logger function which creates a named logger. Loggers have methods to log message at the various log levels.

Guidelines:

  • trace - Low-level debugging information (e.g. HTTP requests, database queries).
  • debug - Debugging information.
  • info - Important high-level events (e.g. a resource was created, an e-mail was sent).
  • warn - An unexpected error or situation occurred but it was handled transparently for the user.
  • error - An unexpected error occurred (the user typically gets a 500 Internal Server Error response) but the server is still running normally.
  • fatal - An unexpected and unrecoverable error occurred. The server is not guaranteed to still be operating properly and should be restarted.

The server's log level can be configured by setting the $LOG_LEVEL environment variable or the logLevel configuration property. Only messages at or above the configured log level will be displayed. For example, if the configured log level is INFO, only messages at the INFO, WARN, ERROR and FATAL log levels will be displayed, while TRACE and DEBUG messages will not be.

It is recommended to set the log level to TRACE in development, as HTTP requests and databases queries are only logged at that level.

Usage example:

const config = require('../config');
const logger = config.logger('what');
logger.debug('Something happened')
// [2000-01-01T00:00:00.000] [DEBUG] what - Something happened

Security

The main security features of this server are:

  • User account passwords are stored as a bcrypt hash.

  • API authentication and authorization is implemented using the express-jwt-policies library which works with JWT tokens and user-provided policy functions.

    The configuration of the library can be found in server/api/utils/auth.js.

Password hashing

The bcryptjs library is used to compute the bcrypt hashes.

The bcrypt cost factor can be adjusted when launching the server by providing the $BCRYPT_COST environment variable or setting the bcryptCost configuration property (see Configuration).

Authentication

To authenticate to some API resources, the user must send an Authorization header with a bearer JWT token (i.e. Bearer TOKEN). If the token is missing, malformed, invalid or has expired, the response's status code will be 401 Unauthorized with a JSON error identifying the problem.

Authorization

BioPocket users can have a number of roles, such as admin. A standard user has no roles. Some API resources require the user to have specific roles in addition to being authenticated.

If the user does not have sufficient privileges, the response's status code will be 403 Forbidden. In some cases, the status code can also be 404 Not Found (e.g. if a user is trying to access a resource that exists but to which he does not have access).

Policies

The logic allowing the API to know if a request to a given resource is authorized is encapsulated into a policy function. You may find such a function in a .policy.js files in an API subject's directory, for example server/api/users/users.policy.js:

const { hasRole, sameRecord } = require('../utils/policy');

exports.canRetrieve = function(req) {
  return hasRole(req, 'admin') || sameRecord(req.currentUser, req.user);
};

This function checks whether the authenticated user (req.currentUser) can retrieve a user resource (req.user):

  • In this case, you are authorized to retrieve a user if you have the admin role or if you are authenticated as the user you are trying to retrieve.
  • You are not authorized, for example, to retrieve another user (unless you have the admin role).

All route access logic should be encapsulated in similar policy functions.

Policy functions may return a promise. Various authorization utilities are available in server/api/utils/policy.

Serializing

Policies should handle the serialization of database records into response bodies, because some properties might only be visible by users with specific roles.

Policies should have a serialize(req, resource) function, with the first argument being an Express request object (used to determine the authenticated user and roles), and the second being the resource to serialize.

For example:

const { ensureRequest } = require('../../utils/express');

exports.serialize = function(req, user) {
  ensureRequest(req);

  // Anyone can see the e-mail.
  const serialized = {
    email: user.get('email')
  };

  // Only an admin user can see the login count.
  const admin = req.currentUser && req.currentUser.hasRole('admin');
  if (admin) {
    serialized.loginCount = user.get('login_count');
  }

  return serialized;
}

Documentation

The README.md file documents basic setup instructions and how to configure the server. This DEVELOPMENT.md file explains how the server is developed.

Guidelines:

  • Always keep the README up-to-date.
  • When adding a new library or mechanism, document it in this DEVELOPMENT.md file if appropriate.

API RAML documentation

The API is documented with RAML, a YAML-based language to describe REST APIs.

The server/api/index.raml file is the entrypoint for that documentation. It includes other .raml files describing each resource under the server/api directory (e.g. server/api/auth/auth.raml) to form the documentation for the entire API.

You can generate this documentation by running npm run docs:api and will find the results in the docs/api directory. It is also generated and served in your browser automatically when running npm run dev.

Guidelines:

  • Always update the RAML documentation when making changes to the API.
  • Use the RAML specification as a reference.
  • Try to isolate repeated resource properties as traits

Source code JSDoc documentation

The source code is documented inline with JSDoc.

You can generate this documentation by running npm run docs:src and will find the results in the docs/src directory. It is also generated and served in your browser automatically when running npm run dev.

Guidelines:

  • Always update an existing function's JSDoc when modifying its inputs, outputs or behavior.
  • Document all reusable & utility functions (include an example if possible).
  • Document all database models:
    • Columns
    • Virtual properties
    • Extra methods
  • Document API routes (in .routes.js files) with a single-line comment (so that it doesn't show in the JSDoc) indicating only the HTTP method and full path to the resource, e.g. // POST /api/users.
  • Document API route implementations (in .api.js files) with a short sentence indicating what it does without too much detail. Detailed API documentation should be written in the RAML files.

Testing

The server has an automated test suite developed using the following tools:

  • Mocha - JavaScript test framework
  • Chai - BDD/TDD assertion library
  • Chance - Minimalist generator of random strings, numbers, etc.
  • Sinon - Test spies, stubs and mocks.
  • SuperTest - Super-agent driven library for testing Node.js HTTP servers using a fluent API
    • SuperREST - SuperTest helpers to test REST APIs
  • test-value-generator - Utility to generate incremental and unique values in automated tests

Additionally, the following tools are used to generate code coverage reports:

TODO: test coverage configuration with babel/nyc

Linting

ESLint is used to check the project's JavaScript code. It mainly does two things:

  • Check for syntax errors.
  • Enforce our style guide.

Our ESLint configuration is in the [.eslintrc.json][.eslintrc.json] file. Refer to ESLint's rules documentation for more information on how to configure specific rules.

These two additional plugins have been added:

Note the following special configurations regarding Lodash and Node.js's util package:

  • ESLint's id-blacklist and no-restricted-properties rules have been configured to avoid using specific deprecated util methods functions in the project, namely isBoolean, isFunction, isNumber and isString. Prefer using Lodash's corresponding functions:

    // INCORRECT
    const util = require('util');
    if (util.isString(x)) {
      // Do something.
    }
    
    // CORRECT
    const _ = require('lodash');
    if (_.isString(x)) {
      // Do something.
    }
    
    // CORRECT
    const { isString } = require('lodash');
    if (isString(x)) {
      // Do something.
    }

    Lodash's isNull and isUndefined functions should not be used, however:

    // INCORRECT
    const _ = require('lodash');
    if (_.isNull(x) || _.isUndefined(x)) {
      // Do something.
    }
    
    // CORRECT
    if (x === null || x === undefined) {
      // Do something.
    }