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

sequelize-virtual-fields

v1.1.1

Published

Sequelize virtual fields magic

Downloads

609

Readme

sequelize-virtual-fields.js

Sequelize virtual fields magic

NPM version Dependency Status Dev dependency Status Coverage Status

What's it for?

This plugin for Sequelize adds some magic to VIRTUAL fields, so that they can be used the same as normal fields.

If a virtual field references attributes of an associated model, this can be defined in the model's definition and the required associations are loaded automatically by Model#find().

Why is this useful? You might, for example, want to build a Drupal-style framework where every model instance has a 'name' field which which may take its value from fields in associated models.

Current status

API is stable. All features and options are fairly well tested. Works with all dialects of SQL supported by Sequelize (MySQL, Postgres, SQLite) except for Microsoft SQL Server.

Requires Sequelize v2.x.x, v3.x.x or v4.x.x.

Version v1.0.0 onwards supports only Node v4 or higher. Currently, all tests pass on Node v0.10 and v0.12, but these versions of Node will no longer be tested against so this cannot be guaranteed in future releases.

Usage

Loading module

To load module:

var Sequelize = require('sequelize-virtual-fields')();
// NB Sequelize must also be present in `node_modules`

or, a more verbose form useful if chaining multiple Sequelize plugins:

var Sequelize = require('sequelize');
require('sequelize-virtual-fields')(Sequelize);

Defining virtual fields

Define the dependency of the virtual fields on other attributes or models:

// define models
var Person = sequelize.define('Person', { name: Sequelize.STRING });
var Task = sequelize.define('Task', {
	name: Sequelize.STRING,
	nameWithPerson: {
		type: Sequelize.VIRTUAL,
		get: function() { return this.name + ' (' + this.Person.name + ')' }
		attributes: [ 'name' ],
		include: [ { model: Person, attributes: [ 'name' ] } ],
		order: [ ['name'], [ Person, 'name' ] ]
	}
});

// define associations
Task.belongsTo(Person);
Person.hasMany(Task);

// activate virtual fields functionality
sequelize.initVirtualFields();

Create some data:

// create a person and task and associate them
Promise.all({
	person: Person.create({ name: 'Brad Pitt' }),
	task: Task.create({ name: 'Do the washing' })
}).then(function(r) {
	return r.task.setPerson(r.person);
});

Retrieving virtual fields

find() a task, referencing the virtual field:

Task.find({ attributes: [ 'nameWithPerson' ] })
.then(function(task) {
	// task.values = { nameWithPerson: 'Do the washing (Brad Pitt)' }
});

The associated model 'Person' has been automatically fetched in order to get the name of the person.

The fields and eager-loaded associations necessary (Person, Company) are deleted from the result before returning.

Ordering by virtual fields

You can also order by a virtual field:

Task.findAll({
	attributes: [ 'nameWithPerson' ],
	order: [ [ 'nameWithPerson' ] ]
});

Notes

The behaviour of find() in examples above works because of the definition of attribute, include and order in the Task model's definition, as well as the getter function get.

IMPORTANT NOTE

This plugin changes the normal function of Instance#get() and Instance.values in Sequelize.

Usually virtual fields are not present in Instance#dataValues and have to be accessed with Instance#get() or by <instance>.<attribute name>. This plugin alters that behaviour - virtual fields' values are added to dataValues before results are returned from Model#find(), and then calling get() basically just retrieves dataValues.

The purpose is for virtual fields to look and behave exactly like normal fields for getting purposes (setting is another matter!)

Errors

Errors thrown by the plugin are of type VirtualFieldsError. The error class can be accessed at Sequelize.VirtualFieldsError.

Tests

Use npm test to run the tests. Use npm run cover to check coverage. Requires a database called 'sequelize_test' and a db user 'sequelize_test' with no password.

Changelog

See changelog.md

Known issues

  • Does not work with use of association in place of model in include or order e.g. someModel.findAll({ include: [ {association: someAssociation } ] }) - throws error if encountered
  • No support for Sequelize.col() in order clauses
  • Crashes when using '.getXXX()' accessors to get many-to-many association if virtual fields defined in through model
  • Fails to remove all virtually included models (broken by recent changes to Sequelize, am working on a fix)

If you discover a bug, please raise an issue on Github. https://github.com/overlookmotel/sequelize-virtual-fields/issues

Contribution

Pull requests are very welcome. Please:

  • ensure all tests pass before submitting PR
  • add an entry to changelog
  • add tests for new features
  • document new functionality/API additions in README