FFC Database Module

1.0.24 · active · verified Wed Apr 22

ffc-database is an npm module developed by DEFRA, providing a structured utility layer for database interactions within FFC services. It is built upon the Sequelize ORM, abstracting common setup and model loading patterns. The module simplifies connecting to SQL databases (e.g., PostgreSQL, as shown in examples) by taking a configuration object, dynamically loading Sequelize models from a specified filesystem path, and exposing the connected Sequelize instance and loaded models. The current stable version is 1.0.24. While specific release cadence is not provided, its versioning and association with government services suggest a focus on stability and compatibility within its ecosystem. Its key differentiator lies in its opinionated, service-centric wrapper around Sequelize, streamlining database access for specific internal FFC applications.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to instantiate the `ffc-database` module, connect to a PostgreSQL database using environment variables for sensitive data, dynamically load Sequelize models, execute a simple raw SQL query, and gracefully close the database connection.

const Base = require('ffc-database');

const config = {
  dialect: 'postgres',
  host: process.env.DB_HOST ?? 'localhost',
  port: parseInt(process.env.DB_PORT ?? '5432', 10),
  database: process.env.DB_NAME ?? 'ffc_pay',
  username: process.env.DB_USER ?? 'ffc_user',
  password: process.env.DB_PASSWORD ?? 'ffc_password',
  modelPath: './models', // Assuming models directory exists in CWD
  ssl: process.env.DB_SSL === 'true' ?? false,
  logging: process.env.NODE_ENV !== 'production'
};

// Minimal model file example (./models/payment.js):
// module.exports = (sequelize, DataTypes) => {
//   const Payment = sequelize.define('Payment', {
//     amount: { type: DataTypes.DECIMAL },
//     status: { type: DataTypes.STRING }
//   });
//   Payment.associate = (models) => {}; // Define associations here
//   return Payment;
// };

async function runDbOperations() {
  let dbBase;
  let db;
  try {
    dbBase = new Base(config);
    db = await dbBase.connect();
    console.log('Database connected successfully.');

    // Example: Run a raw query
    const [results, metadata] = await db.sequelize.query(
      'SELECT 1 + 1 as solution;',
      { type: db.sequelize.QueryTypes.SELECT }
    );
    console.log('Query result:', results);

    // Assuming a 'Payment' model exists and is defined in './models/payment.js'
    // const payments = await db.Payment.findAll();
    // console.log('Found payments:', payments);

  } catch (error) {
    console.error('Database operation failed:', error);
  } finally {
    if (db && db.sequelize) {
      await db.sequelize.close();
      console.log('Database connection closed.');
    }
  }
}

runDbOperations();

view raw JSON →