GithubHelp home page GithubHelp logo

sequelize-virtual-fields's Introduction

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

sequelize-virtual-fields's People

Contributors

overlookmotel avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

sequelize-virtual-fields's Issues

Fails to remove all virtually included models

My notes from a log time ago say "broken by recent changes to Sequelize". But I have no idea if this remains an issue or in what circumstances.

If anyone has come across this and can provide an example where this issue occurs, please post it.

Querying by virtual attribute

Hiya,

This might be a stupid question, but I'm assuming it's not possible to query by a virtual attribute e.g. in a "where"?

For example:

MyModel.find({
  where:{
    virtualAttribute: 'bob
  }
}).then(....)

If not, would it be a massive technical challenge to add this in? I'm happy to have a go at making a PR myself, but be good to know what the general feeling was!

Action required: Greenkeeper could not be activated 🚨

🚨 You need to enable Continuous Integration on all branches of this repository. 🚨

To enable Greenkeeper, you need to make sure that a commit status is reported on all branches. This is required by Greenkeeper because we are using your CI build statuses to figure out when to notify you about breaking changes.

Since we did not receive a CI status on the greenkeeper/initial branch, we assume that you still need to configure it.

If you have already set up a CI for this repository, you might need to check your configuration. Make sure it will run on all new branches. If you don’t want it to run on every branch, you can whitelist branches starting with greenkeeper/.

We recommend using Travis CI, but Greenkeeper will work with every other CI service as well.

include.where within virtual field ignored

Its appears include.where within a virtual field is ignored, for example.

this.Message = this.sequelize.define('message', {
    gid: Sequelize.STRING,
    outgoing: Sequelize.BOOLEAN,
    composed_time: Sequelize.DATE,
    sent_time: Sequelize.DATE,
}, {
    timestamps: false,
    getterMethods: {
        friendly_time() { return (this.outgoing) ? this.composed_time : this.sent_time; }
    }
});

this.GroupChat = this.sequelize.define('groupchat', {
    uuid: { type: Sequelize.STRING, unique: true },
    updated_at: {
        type: Sequelize.VIRTUAL,
        get: function() { return this.latest_message ? this.latest_message.friendly_time : this.created_at; },
        include: [{ model: self.Message, as: 'latest_message', where: { gid: this.uuid } }]
    }
}, {
    timestamps: false
});


this.Message.belongsTo(this.GroupChat, { as: 'groupchat', targetKey: 'uuid', foreignKey: 'gid', constraints: false });
this.GroupChat.hasOne(this.Message, { as: 'latest_message', targetKey: 'uuid', foreignKey: 'gid', constraints: false });

I would expect the above code to return a message where the gid of the message matches the uuid of a group. No matter what the where clause states it always returns the same message, as if it is being ignored.

This is supposedly supported within the Model object itself. http://docs.sequelizejs.com/en/latest/docs/models-usage/#eager-loading

PS: Its possible Im doing something obviously wrong, as Im still new to sequelise.

Patches use Sequelize version string from Sequelize object in use

At present the patches which deal with changes in Sequelize API, to allow support for both v3.x.x and v2.x.x decide what version of Sequelize is in use with require('sequelize/package.json'). This may be incorrect if module has been invoked with require('sequelize-virtual-fields')(SomeSequelizeVersion).

Awaiting merge of a PR in Sequelize to add a version property to Sequelize object: sequelize/sequelize#4459

Custom getters with own values

We followed the discussion on "How to store a json field in mysql?" at sequelize/sequelize#2774. As a result we implemented a custom getter/setter on a data field. We noticed the setter is been called fine, but the getter just does never fire up. Tracking the issue we noticed its the virtual fields that prevent this case.

Is there a particular reason for excluding custom getters if a data value is available?

// lib/instanceGet.js#L27
if (!this.dataValues.hasOwnProperty(key) && this._customGetters[key]) return this._customGetters[key].call(this);

As a quick fix we changed it to

// lib/instanceGet.js#L27
if (this._customGetters[key]) return this._customGetters[key].call(this);

This basically solves the case, but may cause some unwanted side effects.

Action required: Greenkeeper could not be activated 🚨

🚨 You need to enable Continuous Integration on all branches of this repository. 🚨

To enable Greenkeeper, you need to make sure that a commit status is reported on all branches. This is required by Greenkeeper because we are using your CI build statuses to figure out when to notify you about breaking changes.

Since we did not receive a CI status on the greenkeeper/initial branch, we assume that you still need to configure it.

If you have already set up a CI for this repository, you might need to check your configuration. Make sure it will run on all new branches. If you don’t want it to run on every branch, you can whitelist branches starting with greenkeeper/.

We recommend using Travis CI, but Greenkeeper will work with every other CI service as well.

Sequelize init error

Sequelize try to fetch model, but models not compiled yet

export default (sequelize, DataTypes) => { const AppUser = sequelize.define( 'AppUser', { name: { type: DataTypes.VIRTUAL, get: () =>${this.Local.name || this.Facebook.name || this.Google.name || this.Linkedin.name}, include: [ { model: 'Local', attributes: ['name'] }, { model: 'Facebook', attributes: ['name'] }, { model: 'Google', attributes: ['name'] }, { model: 'Linkedin', attributes: ['name'] } ], order: [['Local', 'name'], ['Facebook', 'name'], ['Google', 'name'], ['Linkedin', 'name']] }, birthDate: { type: DataTypes.VIRTUAL, get: () => ${this.Local.birthDate ||
this.Facebook.birthDate ||
this.Google.birthDate ||
this.Linkedin.birthDate}`,
include: [
{ model: 'Local', attributes: ['birthDate'] },
{ model: 'Facebook', attributes: ['birthDate'] },
{ model: 'Google', attributes: ['birthDate'] },
{ model: 'Linkedin', attributes: ['birthDate'] }
],
order: [
['Local', 'birthDate'],
['Facebook', 'birthDate'],
['Google', 'birthDate'],
['Linkedin', 'birthDate']
]
}
}
);

// relations
AppUser.associate = (models) => {
AppUser.hasOne(models.Facebook, { as: 'facebookId' });
AppUser.hasOne(models.Google, { as: 'googleId' });
AppUser.hasOne(models.Linkedin, { as: 'linkedinId' });
AppUser.hasOne(models.Local, { as: 'localId' });
};

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

return AppUser;
};
`

getAssociation is in sequelize 4 for a many association: getAssociations

We fixed it by doing this in init.js (line 148)

// check if is valid association from parent
if(parent.getAssiciation) {
	if (!parent.getAssociation(item.model, item.as)) throw new Sequelize.VirtualFieldsError(clauseType + " of virtual field '" + modelName + "'.'" + fieldName + "' includes invalid association from '" + parent.name + "' to '" + item.model.name + (item.as ? ' (' + item.as + ')' : '') + "'");
} else {
	if (!parent.getAssociations(item.model, item.as)) throw new Sequelize.VirtualFieldsError(clauseType + " of virtual field '" + modelName + "'.'" + fieldName + "' includes invalid association from '" + parent.name + "' to '" + item.model.name + (item.as ? ' (' + item.as + ')' : '') + "'");
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.