Framework Examples

Need a copy&paste cookbook for initializing Massive with your web framework or context? Look no further!

If you're using Massive with a framework not already here, feel free to submit a pull request with your own example.

Koa

const Koa = require('koa');
const Router = require('koa-router');
const massive = require('massive');

const app = new Koa();
const router = new Router();

(async () => {
  app.context.db = await massive({
    host: '127.0.0.1',
    port: 5432,
    database: 'appdb',
    user: 'appuser',
    password: 'apppwd'
  });

  router.get('/', async ctx => {
    ctx.body = await ctx.db.feed_items.find({
      'rating >': 0
    }, {
      order: [{field: 'created_at', direction: 'desc'}]
    });
  });

  app
    .use(router.routes())
    .use(router.allowedMethods())
    .listen(3000);
})();

Express

const express = require('express');
const http = require('http');
const massive = require('massive');

const app = express();

(async () => {
  const db = await massive({
    host: '127.0.0.1',
    port: 5432,
    database: 'appdb',
    user: 'appuser',
    password: 'apppwd'
  });

  app.set('db', db);

  app.get('/', async (req, res) => {
    const items = await req.app.get('db').feed_items.find({
      'rating >': 0
    }, {
      order: [{field: 'created_at', direction: 'desc'}]
    });

    res.json(items);
  });

  http.createServer(app).listen(3000);
})();

NestJS

NestJS can make use of Massive through the npm package @nestjsplus/massive. In a typical NestJS application, you'd use it like this:

// src/app.module.ts
// MassiveModule.register() creates a singleton
// connection pool to PostgreSQL
//
// Importing it makes the connection pool available as a
// shared "provider" to any other module
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { MassiveModule } from '@nestjsplus/massive';

@Module({
  imports: [
    MassiveModule.register({
      user: 'john',
      password: 'password',
      host: 'localhost',
      port: 5432,
      database: 'nest',
    }),
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}
// src/app.service.ts
import { Inject, Injectable } from '@nestjs/common';
import { MASSIVE_CONNECTION } from '@nestjsplus/massive';

@Injectable()
export class AppService {
  // Inject the singleton DB connection pool
  constructor(
    @Inject(MASSIVE_CONNECTION) private readonly db
  ) {}

  async find(age) {
    const criteria = age ? { 'age >=': age } : {};
    // make normal Massive API calls on the db object
    return await this.db.cats.find(criteria);
  }

View a complete NestJS/Massive sample repository here.

Fastify

Fastify can use the fastify-massive plugin.

const Fastify = require('fastify')
const massive = require('fastify-massive')
const fastify = Fastify()
fastify.register(massive, {
  massive: connInfo,
  async onLoad(db) {
    // use this one-time startup hook to perform any
    // database initialization. Fastify will reload the
    // schema afterwards.
  }
})

fastify.get('/', async (req, res) => {
  // list available tables
  return fastify.massive.listTables()
})

Synchronous Wrapped Connection

If you want to acquire an already-connected instance synchronously without a central app or similar object, you can wrap the Massive instance in your own module and require it where you need it.

db.js

If you've already connected once (which is an asynchronous process and must be awaited or similar), the instance is cached so future invocations resolve synchronously.

const massive = require('massive');

let db;

exports = module.exports = function () {
  if (db) {
    return db;
  }

  return massive({
    host: '127.0.0.1',
    port: 5432,
    database: 'appdb',
    user: 'appuser',
    password: 'apppwd'
  }).then(instance => {
    db = instance;

    return Promise.resolve(db);
  });
};

index.js

const getDb = require('./db');

getDb().then(db => {
  console.log(db.listTables());

  // don't pass the instance
  return Promise.resolve();
}).then(() => {
  // retrieve the already-connected instance
  // synchronously
  const db = getDb();

  console.log(db.listTables());

  process.exit(0);
});