npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

bookshelf-express-mw

v0.7.3

Published

Bookshelf express middleware

Downloads

2

Readme

bookshelf-express-mw

NPM

A bookshelf middleware for express framework designed to work with routemap-express-mw.

Pagination

When querying large amounts of data, we might want to implement pagination in our response. We will showcase pagination with an example solution using routemap for relational databases.

Installation

npm install logging-express-mw --save
npm install bookshelf-express-mw --save
npm install routemap-express-mw --save

Bookshelf Configuration

Bookshelf needs a configuration object with following properties:

  • client - database type, can be one of:
    • pg (Postgres)
    • mssql (MSSQL)
    • mysql/mysql2 (MySQL)
    • ariasql (MariaDB)
    • sqlite3 (SQLite3)
    • oracle/strong-oracle (Oracle)
  • connection - database connection string with the following fields
    • host
    • user
    • password
    • database
  • pool - can provide min and max pool size
    • min
    • max

For example our configuration object can be:

const config = {
  client: 'mysql',
  connection: {
    host : '127.0.0.1',
    user : 'your_database_user',
    password : 'your_database_password',
    database : 'myapp_test'
  },
  pool: { min: 0, max: 7 }
}

Express integration

In your server code, such as app.js add the following code:

const app = require('express')();
const logger = require('logging-express-mw');
const bookshelf = require('bookshelf-express-mw');
const routeMap = require('routemap-express-mw');

const config = {
  client: 'mysql',
  connection: {
    host : '127.0.0.1',
    user : 'your_database_user',
    password : 'your_database_password',
    database : 'myapp_test'
  },
  pool: { min: 0, max: 7 }
}

// mw to add bookshelf to express
app.use(bookshelf.middleware(config));

// mw to add logging to express
app.use(logger.middleware());
// mw to write elegant apis
app.use(routeMap());

Models

We have a user table in our relational database and made a corresponding bookshelf model.

// user.js in models folder
const bookshelf = require('bookshelf-express-mw');

module.exports = () => {
  bookshelf.bookshelf().Model.extend({
    tableName: 'user',
    hasTimestamps: true,
  });
};

Controllers

We are going to make a user controller user.js. Please refer to routemap-express-mw for more information on [routemap] (https://github.com/admurali/routemap-express-mw/)

const User = require('../models/user');
const _ = require('lodash');

const USERS_KEY = 'USERS';

function getUser(req, res) {
  req.routeMap.push(serializeUsers);
  req.routeMap.push(fetchUsers);
  req.routeMap.makeResponse(res);
}

module.exports = {
  getUser,
};

Pagination Example

We can make a fetchUsers implementation as shown below:

function fetchUsers(req) {
  return new Promise((resolve, reject) => {
    User.query((qb) => {
      qb.where({
        is_deleted: 0,
      });
    }).fetchPage(
      _.extend({
        columns: [
          'id',
          'name',
          'is_deleted',
        ],
      }, req.routeMap.pageObject),
    ).then((users) => {
      req.routeMap.setPageResponseObject(
        users.pagination,
      );
      req.routeMap.addOrUpdateObject(
        USERS_KEY,
        users.toJSON(),
      );
      resolve();
    }).catch((error) => {
      reject(error);
    });
  });
}

We used the following routemap properties:

  • pageObject - for GET requests query by either
    • limit and offset

      --OR--

    • page and pageSize

  • setPageResponseObject - sets the bookshelf object using pagination

We can then make a serializeUsers function as shown below:

function serializeUsers(req) {
  return new Promise((resolve, reject) => {
    try {
      const users = req.routeMap.getObject(
        USERS_KEY,
      );
      resolve(users.map(
        (user) => {
          const result = _.pick(user, [
            'id',
            'name',
          ]);
          return result;
        }));
    } catch (error) {
      reject(error);
    }
  });
}