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

visions

v2.6.0

Published

Wrapper for knex to reduce boilerplate for basic queries

Downloads

38

Readme

Visions

Visions is very much a QueryBuilder not a full ORM. It will not handle schema definitions or migrations, but instead reduce the amount of repetitive boilerplate queries required for basic selects and joins. There are a couple of interesting features that are not consistently offered in existing nodejs QueryBuilder libraries.

  • Clean database view support
  • Model association population using proper database joins (one database query per logical query)

Support for database views are implemented by overlaying a set of view names over the original table names, then using this "overlay" to generate and rename queries. Once the wrapper function is created, the high-level interface will substitute all uses of the original table name with the overlayed view. This both simplifies the ease of use as well as protecting against bugs that use the wrong view in a query.

Model associations are used to dynamically create common query patterns without the boilerplate. The high-level interface exposes basic options when querying a model, but the KnexWrapper.getViewName() method can be used along with knex to implement more specialised queries when required.

Install

npm install --save visions

Docs

https://playground-xyz.github.io/visions/

Usage

Setup your model schema (see JoinJs for details on the structure for this declaration step). The only difference is that columnPrefix is overwritten internally as it must match the query generation.


const models = [
  {
    mapId: 'owner',
    idProperty: 'id',
    properties: ['age', 'birthday'],
    collections: [
      { name: 'pets', mapId: 'pet' }
    ]
  },
  {
    mapId: 'pet',
    idProperty: 'id',
    associations: [
      { name: 'owner', mapId: 'owner' }
    ]
  }
];

Use a middleware to determine a set of database views for the request. This part of the code example is very vague as the structure of views in an application varies based on the use-case.

const Visions = require('visions');
const app = express();
const knex = require('knex')(config.database);

app.use(async (req, res, next) => {

  // The structure of your views is completely up to your use-case
  const viewId = await determineViewIdForRequest(req.user.id);
  const views = {
    owner: `${viewId}__owner`,
    pet: `${viewId}__pet`
  };

  // Attach the querybuilder instance to the request object
  req.visions = new Visions(models, knex, views);

  next();
});

Finally, in your controllers you can write simple, readable queries.

app.get('/owner/:id', (req, res) => {
  req.visions.generateQueryFor('owner')
      .populate('pet')
      .sort('birthday', 'asc')
      .limit(req.query.limit)
      .skip(req.query.skip)
      .where({
        key: 'id',
        value: req.params.id
      })
      .exec()
      .then(data => res.status(200).send(data))
      .catch(err => res.status(500).send({ error: err }));
});

Or use knex directly for more complex queries.

app.get('/owner/:id', (req, res) => {
  knex
    .select()
    // This will use the view you overlayed on the owner model for this request
    // (or just "owner") if you didn't specify a view for it
    .from(req.visions.getViewNameFor('owner'))
    .rightOuterJoin(
        req.visions.getViewNameFor('pet'),
        `${req.visions.getViewNameFor('pet')}.owner`,
        `${req.visions.getViewNameFor('owner')}.id`,
    ).then(data => res.status(200).send(data));
});

1-1 and M-N Relationships

1-1 and M-N are special cases of collections respectively and require flags in the mapping object to identify them.

1-1 Relationships

The only change required for 1-1 relationships is that a flag is added to the collection.

const models = [
  {
    mapId: 'person',
    idProperty: 'id',
    collections: [
      { name: 'father', mapId: 'father', isOneToOne: true }
    ]
  }
];

M-N Relationships

This library assumes that the database schema is properly normalised and therefore includes a minimal join table between the 2 joined entities. This is to be defined as part of the relationship in the mapping object.

const models = [
  {
    mapId: 'employee',
    idProperty: 'id',
    collections: [
      { name: 'managers', mapId: 'manager', joinTable: 'employee_manager_join' }
    ]
  },
  {
    mapId: 'manager',
    idProperty: 'id',
    associations: [
      { name: 'staff', mapId: 'employee', joinTable: 'employee_manager_join' }
    ]
  }
];

with the database schema defined as:

CREATE TABLE employee ( id integer NOT NULL PRIMARY KEY );
CREATE TABLE manager ( id integer NOT NULL PRIMARY KEY );

CREATE TABLE employee_manager_join (
  employee integer NOT NULL,
  manager integer NOT NULL,
  PRIMARY_KEY(employee, manager)
);

Note that the keys in the join table are the same as the original tables they reference.

Dependencies