Socket
Socket
Sign inDemoInstall

redux-orm

Package Overview
Dependencies
Maintainers
1
Versions
70
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

redux-orm - npm Package Compare versions

Comparing version 0.1.13 to 0.1.14

.publish/Backend.html

6

lib/descriptors.js

@@ -37,3 +37,3 @@ 'use strict';

this.getClass().addMutation({
this.getClass().addUpdate({
type: _constants2['default'],

@@ -82,4 +82,4 @@ payload: {

var fromFieldName = (0, _utils.m2mFromFieldName)(declaredFromModel.getName());
var toFieldName = (0, _utils.m2mToFieldName)(declaredToModel.getName());
var fromFieldName = (0, _utils.m2mFromFieldName)(declaredFromModel.modelName);
var toFieldName = (0, _utils.m2mToFieldName)(declaredToModel.modelName);

@@ -86,0 +86,0 @@ var lookupObj = {};

@@ -13,5 +13,5 @@ 'use strict';

var _Meta = require('./Meta');
var _Backend = require('./Backend');
var _Meta2 = _interopRequireDefault(_Meta);
var _Backend2 = _interopRequireDefault(_Backend);

@@ -45,3 +45,3 @@ var _Model = require('./Model');

exports.QuerySet = _QuerySet2['default'];
exports.Meta = _Meta2['default'];
exports.Backend = _Backend2['default'];
exports.Model = _Model2['default'];

@@ -48,0 +48,0 @@ exports.Schema = _Schema2['default'];

@@ -7,4 +7,2 @@ 'use strict';

var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };
var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();

@@ -16,4 +14,2 @@

function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

@@ -27,4 +23,2 @@

var _fields = require('./fields');
var _Session = require('./Session');

@@ -34,5 +28,5 @@

var _Meta = require('./Meta');
var _Backend = require('./Backend');
var _Meta2 = _interopRequireDefault(_Meta);
var _Backend2 = _interopRequireDefault(_Backend);

@@ -49,3 +43,3 @@ var _QuerySet = require('./QuerySet');

* The heart of an ORM, the data model.
* The static class methods manages the mutations
* The static class methods manages the updates
* passed to this. The class itself is connected to a session,

@@ -98,3 +92,3 @@ * and because of this you can only have a single session at a time

ModelClass.addMutation({
ModelClass.addUpdate({
type: _constants.UPDATE,

@@ -146,3 +140,3 @@ payload: (_payload = {}, _defineProperty(_payload, idAttribute, _this.getId()), _defineProperty(_payload, fieldName, value), _payload)

var className = this.getClass().getName();
var className = this.getClass().modelName;
var fields = this._fieldNames.map(function (fieldName) {

@@ -178,3 +172,3 @@ var val = _this2._fields[fieldName];

/**
* Records a mutation to the {@link Model} instance for a single
* Records a update to the {@link Model} instance for a single
* field value assignment.

@@ -192,3 +186,3 @@ * @param {string} propertyName - name of the property to set

/**
* Records a mutation to the {@link Model} instance for multiple field value assignments.
* Records a update to the {@link Model} instance for multiple field value assignments.
* @param {Object} mergeObj - an object that will be merged with this instance.

@@ -200,3 +194,3 @@ * @return {undefined}

value: function update(mergeObj) {
this.getClass().addMutation({
this.getClass().addUpdate({
type: _constants.UPDATE,

@@ -217,3 +211,3 @@ payload: {

value: function _delete() {
this.getClass().addMutation({
this.getClass().addUpdate({
type: _constants.DELETE,

@@ -226,111 +220,54 @@ payload: [this.getId()]

value: function toString() {
return 'ModelClass: ' + this.getName();
return 'ModelClass: ' + this.modelName;
}
/**
* Returns the {@link Model} class used to instantiate a possible Through model.
* @return {Model} The Through model class used to handle many-to-many relations declared
* in this model.
*/
}, {
key: 'getThroughModelClass',
value: function getThroughModelClass() {
return Model;
}
}, {
key: 'getManyToManyModels',
value: function getManyToManyModels() {
var _this4 = this;
var fields = this.fields;
var thisModelName = this.getName();
var models = [];
(0, _lodashObjectForOwn2['default'])(fields, function (fieldInstance, fieldName) {
if (fieldInstance instanceof _fields.ManyToMany) {
var _Through$fields;
var toModelName = undefined;
if (fieldInstance.toModelName === 'this') {
toModelName = thisModelName;
} else {
toModelName = fieldInstance.toModelName;
}
var fromFieldName = (0, _utils.m2mFromFieldName)(thisModelName);
var toFieldName = (0, _utils.m2mToFieldName)(toModelName);
var Through = (function (_getThroughModelClass) {
_inherits(ThroughModel, _getThroughModelClass);
function ThroughModel() {
_classCallCheck(this, ThroughModel);
_get(Object.getPrototypeOf(ThroughModel.prototype), 'constructor', this).apply(this, arguments);
}
return ThroughModel;
})(_this4.getThroughModelClass());
Through.meta = {
name: (0, _utils.m2mName)(thisModelName, fieldName)
};
Through.fields = (_Through$fields = {}, _defineProperty(_Through$fields, fromFieldName, new _fields.ForeignKey(thisModelName)), _defineProperty(_Through$fields, toFieldName, new _fields.ForeignKey(toModelName)), _Through$fields);
models.push(Through);
}
});
return models;
}
/**
* Returns the options object passed to the {@link Meta} class constructor.
* You need to define this for every subclass.
* Returns the options object passed to the {@link Backend} class constructor.
*
* @return {Object} the options object used to instantiate a {@link Meta} class.
* @return {Object} the options object used to instantiate a {@link Backend} class.
*/
}, {
key: 'meta',
value: function meta() {
throw new Error('You must declare a static "meta" function in your Model class.');
key: 'backend',
value: function backend() {
return {
branchName: this.modelName
};
}
}, {
key: 'getMeta',
value: function getMeta() {
if (typeof this.meta === 'function') {
return this.meta();
key: '_getBackendOpts',
value: function _getBackendOpts() {
if (typeof this.backend === 'function') {
return this.backend();
}
if (typeof this.meta === 'undefined') {
throw new Error('You must declare either a \'meta\' class method or\n a \'meta\' class variable in your Model Class');
if (typeof this.backend === 'undefined') {
throw new Error('You must declare either a \'backend\' class method or\n a \'backend\' class variable in your Model Class');
}
return this.meta;
return this.backend;
}
/**
* Returns the {@link Meta} class used to instantiate
* the {@link Meta} instance for this {@link Model}.
* Returns the {@link Backend} class used to instantiate
* the {@link Backend} instance for this {@link Model}.
*
* Override this if you want to use a custom {@link Meta} class.
* @return {Meta} The {@link Meta} class or subclass to use for this {@link Model}.
* Override this if you want to use a custom {@link Backend} class.
* @return {Backend} The {@link Backend} class or subclass to use for this {@link Model}.
*/
}, {
key: 'getMetaClass',
value: function getMetaClass() {
return _Meta2['default'];
key: 'getBackendClass',
value: function getBackendClass() {
return _Backend2['default'];
}
/**
* Gets the {@link Meta} instance linked to this {@link Model}.
* @return {Meta} The {@link Meta} instance linked to this {@link Model}.
* Gets the {@link Backend} instance linked to this {@link Model}.
* @return {Backend} The {@link Backend} instance linked to this {@link Model}.
*/
}, {
key: 'getMetaInstance',
value: function getMetaInstance() {
if (!this._meta) {
var MetaClass = this.getMetaClass();
this._meta = new MetaClass(this.getMeta());
key: 'getBackend',
value: function getBackend() {
if (!this._backend) {
var BackendClass = this.getBackendClass();
this._backend = new BackendClass(this._getBackendOpts());
}
return this._meta;
return this._backend;
}

@@ -340,3 +277,3 @@

* Gets the Model's next state by applying the recorded
* mutations.
* updates.
* @return {Object} The next state.

@@ -351,14 +288,14 @@ */

var meta = this.getMetaInstance();
var backend = this.getBackend();
var mutations = this.session.getMutationsFor(this);
var updates = this.session.getUpdatesFor(this);
return mutations.reduce(function (state, action) {
return updates.reduce(function (state, action) {
switch (action.type) {
case _constants.CREATE:
return meta.insert(state, action.payload);
return backend.insert(state, action.payload);
case _constants.UPDATE:
return meta.update(state, action.payload.idArr, action.payload.updater);
return backend.update(state, action.payload.idArr, action.payload.updater);
case _constants.DELETE:
return meta['delete'](state, action.payload);
return backend['delete'](state, action.payload);
default:

@@ -392,3 +329,3 @@ return state;

* Gets the default, empty state of the branch.
* Delegates to a {@link Meta} instance.
* Delegates to a {@link Backend} instance.
* @return {Object} The default state.

@@ -399,23 +336,8 @@ */

value: function getDefaultState() {
return this.getMetaInstance().getDefaultState();
return this.getBackend().getDefaultState();
}
/**
* Gets the name of this {@link Model} class.
* Delegates to {@link Meta}.
*
* Constructors have a name property which we cannot
* override, so this is implemented as a method.
*
* @return {string} The name of this {@link Model} class.
*/
}, {
key: 'getName',
value: function getName() {
return this.getMetaInstance().name;
}
/**
* Returns the id attribute of this {@link Model}.
* Delegates to the related {@link Meta} instance.
* Delegates to the related {@link Backend} instance.
*

@@ -428,3 +350,3 @@ * @return {string} The id attribute of this {@link Model}.

/**
* A convenience method to call {@link Meta#accessId} from
* A convenience method to call {@link Backend#accessId} from
* the {@link Model} class.

@@ -436,7 +358,7 @@ *

value: function accessId(id) {
return this.getMetaInstance().accessId(this.state, id);
return this.getBackend().accessId(this.state, id);
}
/**
* A convenience method to call {@link Meta#accessIdList} from
* A convenience method to call {@link Backend#accessIdList} from
* the {@link Model} class with the current state.

@@ -447,3 +369,3 @@ */

value: function accessIds() {
return this.getMetaInstance().accessIdList(this.state);
return this.getBackend().accessIdList(this.state);
}

@@ -453,3 +375,3 @@ }, {

value: function accessList() {
return this.getMetaInstance().accessList(this.state);
return this.getBackend().accessList(this.state);
}

@@ -459,3 +381,3 @@ }, {

value: function iterator() {
return this.getMetaInstance().iterator(this.state);
return this.getBackend().iterator(this.state);
}

@@ -484,12 +406,12 @@

}, {
key: 'addMutation',
key: 'addUpdate',
/**
* A convenience method that delegates to the current {@link Session} instane.
* Adds the required metadata about this {@link Model} to the mutation object.
* @param {Object} mutation - the mutation to add.
* Adds the required backenddata about this {@link Model} to the update object.
* @param {Object} update - the update to add.
*/
value: function addMutation(mutation) {
mutation.meta = { name: this.getName() };
this.session.addMutation(mutation);
value: function addUpdate(update) {
update.meta = { name: this.modelName };
this.session.addUpdate(update);
}

@@ -526,3 +448,3 @@

this._cachedQuerySet = undefined;
this._meta = undefined;
this._backend = undefined;
this._setupDone = undefined;

@@ -556,3 +478,3 @@ }

this.addMutation({
this.addUpdate({
type: _constants.CREATE,

@@ -582,3 +504,3 @@ payload: props

if (!this.accessIds().length) {
throw new Error('No entities found for model ' + this.getName());
throw new Error('No entities found for model ' + this.modelName);
}

@@ -613,3 +535,3 @@ var ModelClass = this;

/**
* Records an ordering mutation for the objects.
* Records an ordering update for the objects.
* Note that if you create or update any objects after

@@ -626,3 +548,3 @@ * calling this, they won't be in order.

value: function setOrder(orderArg) {
this.addMutation({
this.addUpdate({
type: _constants.ORDER,

@@ -635,3 +557,3 @@ payload: orderArg

get: function get() {
return this.session.getState(this.getName());
return this.session.getState(this.modelName);
}

@@ -641,3 +563,3 @@ }, {

get: function get() {
return this.getMetaInstance().idAttribute;
return this.getBackend().idAttribute;
}

@@ -644,0 +566,0 @@ }, {

@@ -33,3 +33,3 @@ 'use strict';

* - returns a subset clone of itself with [filter]{@link QuerySet#filter} and [exclude]{@link QuerySet#exclude}
* - records mutations to objects with [update]{@link QuerySet#update} and [delete]{@link QuerySet#delete}
* - records updates to objects with [update]{@link QuerySet#update} and [delete]{@link QuerySet#delete}
*

@@ -283,3 +283,3 @@ */

/**
* Records a mutation specified with `updater` to all the objects in the {@link QuerySet}.
* Records a update specified with `updater` to all the objects in the {@link QuerySet}.
* @param {Object|function} updater - an object to merge with all the objects in this

@@ -294,3 +294,3 @@ * queryset, or a mapper function that takes the

value: function update(updater) {
this.modelClass.addMutation({
this.modelClass.addUpdate({
type: _constantsJs.UPDATE,

@@ -311,3 +311,3 @@ payload: {

value: function _delete() {
this.modelClass.addMutation({
this.modelClass.addUpdate({
type: _constantsJs.DELETE,

@@ -314,0 +314,0 @@ payload: this.idArr

@@ -13,3 +13,3 @@ 'use strict';

function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; return arr2; } else { return Array.from(arr); } }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

@@ -32,5 +32,5 @@ function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var _Model2 = require('./Model');
var _Model3 = require('./Model');
var _Model3 = _interopRequireDefault(_Model2);
var _Model4 = _interopRequireDefault(_Model3);

@@ -72,3 +72,3 @@ var _fields = require('./fields');

* @param {Function} [reducer] - the reducer function to use for this model
* @param {Object} [metaOpts] -Meta options for this model.
* @param {Object} [backendOpts] -Backend options for this model.
* @return {Model} The defined model class.

@@ -79,3 +79,3 @@ */

key: 'define',
value: function define(modelName, relatedFields, reducer, metaOpts) {
value: function define(modelName, relatedFields, reducer, backendOpts) {
var ShortcutDefinedModel = (function (_Model) {

@@ -91,5 +91,6 @@ _inherits(ShortcutDefinedModel, _Model);

return ShortcutDefinedModel;
})(_Model3['default']);
})(_Model4['default']);
ShortcutDefinedModel.meta = Object.assign({ name: modelName }, metaOpts);
ShortcutDefinedModel.modelName = modelName;
ShortcutDefinedModel.backend = backendOpts;
ShortcutDefinedModel.fields = relatedFields;

@@ -135,16 +136,52 @@

models.forEach(function (model) {
var _implicitThroughModels;
model.invalidateCaches();
var m2m = model.getManyToManyModels();
m2m.forEach(function (m2mModel) {
return m2mModel.invalidateCaches();
});
(_implicitThroughModels = _this.implicitThroughModels).push.apply(_implicitThroughModels, _toConsumableArray(m2m));
_this.registerManyToManyModelsFor(model);
_this.registry.push(model);
});
}
}, {
key: 'registerManyToManyModelsFor',
value: function registerManyToManyModelsFor(model) {
var _this2 = this;
var fields = model.fields;
var thisModelName = model.modelName;
(0, _lodashObjectForOwn2['default'])(fields, function (fieldInstance, fieldName) {
if (fieldInstance instanceof _fields.ManyToMany) {
var _Through$fields;
var toModelName = undefined;
if (fieldInstance.toModelName === 'this') {
toModelName = thisModelName;
} else {
toModelName = fieldInstance.toModelName;
}
var fromFieldName = (0, _utils.m2mFromFieldName)(thisModelName);
var toFieldName = (0, _utils.m2mToFieldName)(toModelName);
var Through = (function (_Model2) {
_inherits(ThroughModel, _Model2);
function ThroughModel() {
_classCallCheck(this, ThroughModel);
_get(Object.getPrototypeOf(ThroughModel.prototype), 'constructor', this).apply(this, arguments);
}
return ThroughModel;
})(_Model4['default']);
Through.modelName = (0, _utils.m2mName)(thisModelName, fieldName);
Through.fields = (_Through$fields = {}, _defineProperty(_Through$fields, fromFieldName, new _fields.ForeignKey(thisModelName)), _defineProperty(_Through$fields, toFieldName, new _fields.ForeignKey(toModelName)), _Through$fields);
Through.invalidateCaches();
_this2.implicitThroughModels.push(Through);
}
});
}
/**

@@ -160,3 +197,3 @@ * Gets a model by its name from the registry.

var found = (0, _lodashCollectionFind2['default'])(this.registry.concat(this.implicitThroughModels), function (model) {
return model.getName() === modelName;
return model.modelName === modelName;
});

@@ -184,3 +221,3 @@ if (typeof found === 'undefined') {

value: function setupModelPrototypes() {
var _this2 = this;
var _this3 = this;

@@ -192,3 +229,3 @@ this.registry.forEach(function (model) {

var toModelName = fieldInstance.toModelName;
var toModel = toModelName === 'this' ? model : _this2.get(toModelName);
var toModel = toModelName === 'this' ? model : _this3.get(toModelName);

@@ -201,3 +238,3 @@ if (fieldInstance instanceof _fields.ForeignKey) {

// Backwards.
var backwardsFieldName = (0, _utils.reverseFieldName)(model.getName());
var backwardsFieldName = (0, _utils.reverseFieldName)(model.modelName);
Object.defineProperty(toModel.prototype, backwardsFieldName, (0, _descriptors.backwardManyToOneDescriptor)(fieldName, model));

@@ -207,4 +244,4 @@ toModel.definedProperties[backwardsFieldName] = true;

// Forwards.
var throughModelName = (0, _utils.m2mName)(model.getName(), fieldName);
var throughModel = _this2.get(throughModelName);
var throughModelName = (0, _utils.m2mName)(model.modelName, fieldName);
var throughModel = _this3.get(throughModelName);

@@ -215,3 +252,3 @@ Object.defineProperty(model.prototype, fieldName, (0, _descriptors.manyToManyDescriptor)(model, toModel, throughModel, false));

// Backwards.
var backwardsFieldName = (0, _utils.reverseFieldName)(model.getName());
var backwardsFieldName = (0, _utils.reverseFieldName)(model.modelName);
Object.defineProperty(toModel.prototype, backwardsFieldName, (0, _descriptors.manyToManyDescriptor)(model, toModel, throughModel, true));

@@ -225,3 +262,3 @@ toModel.definedProperties[backwardsFieldName] = true;

// Backwards.
var backwardsFieldName = model.getName().toLowerCase();
var backwardsFieldName = model.modelName.toLowerCase();
Object.defineProperty(toModel.prototype, backwardsFieldName, (0, _descriptors.backwardOneToOneDescriptor)(fieldName, model));

@@ -231,3 +268,3 @@ model.definedProperties[backwardsFieldName] = true;

});
_this2._attachQuerySetMethods(model);
_this3._attachQuerySetMethods(model);
model._setupDone = true;

@@ -241,3 +278,3 @@ }

var toModelName = fieldInstance.toModelName;
var toModel = toModelName === 'this' ? model : _this2.get(toModelName);
var toModel = toModelName === 'this' ? model : _this3.get(toModelName);
// Only Forwards.

@@ -247,3 +284,3 @@ Object.defineProperty(model.prototype, fieldName, (0, _descriptors.forwardManyToOneDescriptor)(fieldName, toModel));

});
_this2._attachQuerySetMethods(model);
_this3._attachQuerySetMethods(model);
model._setupDone = true;

@@ -291,6 +328,6 @@ }

value: function reducer() {
var _this3 = this;
var _this4 = this;
return function (state, action) {
return _this3.from(state, action).reduce();
return _this4.from(state, action).reduce();
};

@@ -297,0 +334,0 @@ }

@@ -43,6 +43,6 @@ 'use strict';

this.mutations = [];
this.updates = [];
models.forEach(function (modelClass) {
Object.defineProperty(_this, modelClass.getName(), {
Object.defineProperty(_this, modelClass.modelName, {
get: function get() {

@@ -58,4 +58,4 @@ return modelClass;

/**
* Records a mutation to the session.
* @param {Object} mutation - the mutation object. Must have keys
* Records an update to the session.
* @param {Object} update - the update object. Must have keys
* `type`, `payload` and `meta`. `meta`

@@ -67,28 +67,26 @@ * must also include a `name` attribute

_createClass(Session, [{
key: 'addMutation',
value: function addMutation(mutation) {
this.mutations.push(mutation);
key: 'addUpdate',
value: function addUpdate(update) {
this.updates.push(update);
}
/**
* Gets the recorded mutations for `modelClass` and
* deletes them from the Session instance mutations list.
* Gets the recorded updates for `modelClass` and
* deletes them from the Session instance updates list.
*
* @param {Model} modelClass - the model class to get mutations for
* @return {Object[]} A list of the user-recorded mutations for `modelClass`.
* @param {Model} modelClass - the model class to get updates for
* @return {Object[]} A list of the user-recorded updates for `modelClass`.
*/
}, {
key: 'getMutationsFor',
value: function getMutationsFor(modelClass) {
var modelName = modelClass.getName();
key: 'getUpdatesFor',
value: function getUpdatesFor(modelClass) {
var _partition = (0, _lodashCollectionPartition2['default'])(this.updates, 'meta.name', modelClass.modelName);
var _partition = (0, _lodashCollectionPartition2['default'])(this.mutations, 'meta.name', modelName);
var _partition2 = _slicedToArray(_partition, 2);
var mutations = _partition2[0];
var updates = _partition2[0];
var other = _partition2[1];
this.mutations = other;
return mutations;
this.updates = other;
return updates;
}

@@ -100,3 +98,3 @@ }, {

this.models.forEach(function (modelClass) {
state[modelClass.getName()] = modelClass.getDefaultState();
state[modelClass.modelName] = modelClass.getDefaultState();
});

@@ -124,10 +122,10 @@ return state;

this.mutations = [];
this.updates = [];
var nextState = {};
this.models.forEach(function (modelClass) {
nextState[modelClass.getName()] = modelClass.callUserReducer();
nextState[modelClass.modelName] = modelClass.callUserReducer();
});
// The remaining mutations are for M2M tables.
return this.mutations.reduce(function (state, action) {
// The remaining updates are for M2M tables.
return this.updates.reduce(function (state, action) {
var modelName = action.meta.name;

@@ -134,0 +132,0 @@ state[modelName] = _this2[modelName].getNextState();

@@ -50,7 +50,3 @@ 'use strict';

Model = Object.create(_Model2['default']);
Model.meta = function () {
return {
name: 'Model'
};
};
Model.modelName = 'Model';
});

@@ -84,19 +80,19 @@

it('getMetaInstance works correctly', function () {
var MetaMockClass = _sinon2['default'].stub();
Model.getMetaClass = function () {
return MetaMockClass;
it('getBackend works correctly', function () {
var BackendMockClass = _sinon2['default'].stub();
Model.getBackendClass = function () {
return BackendMockClass;
};
var instance = Model.getMetaInstance();
expect(instance).to.be.an.instanceOf(MetaMockClass);
var instance = Model.getBackend();
expect(instance).to.be.an.instanceOf(BackendMockClass);
// Make sure the previous instance is cached
expect(Model.getMetaInstance()).to.equal(instance);
expect(Model.getBackend()).to.equal(instance);
});
});
describe('static method delegates to Meta', function () {
describe('static method delegates to Backend', function () {
var Model = undefined;
var metaMock = undefined;
var backendMock = undefined;
var stateMock = {};

@@ -106,11 +102,7 @@

Model = Object.create(_Model2['default']);
Model.meta = function () {
return {
name: 'Model'
};
Model.modelName = 'Model';
backendMock = {};
Model.getBackend = function () {
return backendMock;
};
metaMock = {};
Model.getMetaInstance = function () {
return metaMock;
};
Object.defineProperty(Model, 'state', {

@@ -125,3 +117,3 @@ get: function get() {

var accessIdSpy = _sinon2['default'].spy();
metaMock.accessId = accessIdSpy;
backendMock.accessId = accessIdSpy;

@@ -137,3 +129,3 @@ var arg = 1;

var accessIdsSpy = _sinon2['default'].spy();
metaMock.accessIdList = accessIdsSpy;
backendMock.accessIdList = accessIdsSpy;

@@ -148,3 +140,3 @@ Model.accessIds();

var accessIdsSpy = _sinon2['default'].spy();
metaMock.accessIdList = accessIdsSpy;
backendMock.accessIdList = accessIdsSpy;

@@ -186,7 +178,4 @@ Model.accessIds();

})(_Model2['default']);
Model.meta = function () {
return {
name: 'Model'
};
};
Model.modelName = 'Model';
instance = new Model({ id: 0, name: 'Tommi' });

@@ -196,9 +185,9 @@ });

it('delete works correctly', function () {
var addMutationSpy = _sinon2['default'].spy();
Model.addMutation = addMutationSpy;
var addUpdateSpy = _sinon2['default'].spy();
Model.addUpdate = addUpdateSpy;
expect(addMutationSpy).not.called;
expect(addUpdateSpy).not.called;
instance['delete']();
expect(addMutationSpy).calledOnce;
expect(addMutationSpy.getCall(0).args[0]).to.deep.equal({
expect(addUpdateSpy).calledOnce;
expect(addUpdateSpy.getCall(0).args[0]).to.deep.equal({
type: _constants.DELETE,

@@ -210,9 +199,9 @@ payload: [instance.id]

it('update works correctly', function () {
var addMutationSpy = _sinon2['default'].spy();
Model.addMutation = addMutationSpy;
var addUpdateSpy = _sinon2['default'].spy();
Model.addUpdate = addUpdateSpy;
expect(addMutationSpy).not.called;
expect(addUpdateSpy).not.called;
instance.update({ name: 'Matt' });
expect(addMutationSpy).calledOnce;
expect(addMutationSpy.getCall(0).args[0]).to.deep.equal({
expect(addUpdateSpy).calledOnce;
expect(addUpdateSpy.getCall(0).args[0]).to.deep.equal({
type: _constants.UPDATE,

@@ -229,3 +218,3 @@ payload: {

it('set works correctly', function () {
Model.addMutation = function () {
Model.addUpdate = function () {
return undefined;

@@ -232,0 +221,0 @@ };

@@ -87,3 +87,4 @@ 'use strict';

})(_Model3['default']);
PersonClass.meta = { name: 'Person' };
PersonClass.modelName = 'Person';
schema.register(PersonClass);

@@ -143,9 +144,9 @@ session = schema.from(state);

it('update records a mutation', function () {
it('update records a update', function () {
var updater = { name: 'Mark' };
expect(session.mutations).to.have.length(0);
expect(session.updates).to.have.length(0);
qs.update(updater);
expect(session.mutations).to.have.length(1);
expect(session.updates).to.have.length(1);
expect(session.mutations[0]).to.deep.equal({
expect(session.updates[0]).to.deep.equal({
type: _constants.UPDATE,

@@ -162,8 +163,8 @@ payload: {

it('delete records a mutation', function () {
expect(session.mutations).to.have.length(0);
it('delete records a update', function () {
expect(session.updates).to.have.length(0);
qs['delete']();
expect(session.mutations).to.have.length(1);
expect(session.updates).to.have.length(1);
expect(session.mutations[0]).to.deep.equal({
expect(session.updates[0]).to.deep.equal({
type: _constants.DELETE,

@@ -215,3 +216,4 @@ payload: qs.idArr,

PersonSub.meta = { name: 'Person' };
PersonSub.modelName = 'Person';
PersonSub.querySetClass = CustomQuerySet;

@@ -218,0 +220,0 @@ var aSchema = new _Schema2['default']();

@@ -42,9 +42,2 @@ 'use strict';

_createClass(PersonModel, null, [{
key: 'meta',
value: function meta() {
return {
name: 'Person'
};
}
}, {
key: 'fields',

@@ -61,2 +54,4 @@ get: function get() {

Person.modelName = 'Person';
Location = (function (_Model2) {

@@ -71,13 +66,5 @@ _inherits(LocationModel, _Model2);

_createClass(LocationModel, null, [{
key: 'meta',
value: function meta() {
return {
name: 'Location'
};
}
}]);
return LocationModel;
})(_Model10['default']);
Location.modelName = 'Location';
});

@@ -112,9 +99,2 @@

_createClass(PersonModel, null, [{
key: 'meta',
value: function meta() {
return {
name: 'Person'
};
}
}, {
key: 'fields',

@@ -131,2 +111,4 @@ get: function get() {

PersonModel.modelName = 'Person';
var LocationModel = (function (_Model4) {

@@ -141,14 +123,7 @@ _inherits(LocationModel, _Model4);

_createClass(LocationModel, null, [{
key: 'meta',
value: function meta() {
return {
name: 'Location'
};
}
}]);
return LocationModel;
})(_Model10['default']);
LocationModel.modelName = 'Location';
schema.register(PersonModel);

@@ -218,9 +193,2 @@ schema.register(LocationModel);

_createClass(PersonModel, null, [{
key: 'meta',
value: function meta() {
return {
name: 'Person'
};
}
}, {
key: 'reducer',

@@ -249,2 +217,4 @@ value: function reducer(state, action, Person) {

PersonModel.modelName = 'Person';
var LocationModel = (function (_Model6) {

@@ -264,9 +234,2 @@ _inherits(LocationModel, _Model6);

}
}], [{
key: 'meta',
value: function meta() {
return {
name: 'Location'
};
}
}]);

@@ -277,2 +240,4 @@

LocationModel.modelName = 'Location';
schema.register(PersonModel);

@@ -368,9 +333,2 @@ schema.register(LocationModel);

_createClass(UserModel, null, [{
key: 'meta',
value: function meta() {
return {
name: 'User'
};
}
}, {
key: 'reducer',

@@ -403,2 +361,4 @@ value: function reducer(state, action, User) {

UserModel.modelName = 'User';
var ProfileModel = (function (_Model8) {

@@ -414,9 +374,2 @@ _inherits(ProfileModel, _Model8);

_createClass(ProfileModel, null, [{
key: 'meta',
value: function meta() {
return {
name: 'Profile'
};
}
}, {
key: 'reducer',

@@ -443,2 +396,4 @@ value: function reducer(state, action, Profile) {

ProfileModel.modelName = 'Profile';
schema.register(UserModel);

@@ -445,0 +400,0 @@ schema.register(ProfileModel);

{
"name": "redux-orm",
"version": "0.1.13",
"version": "0.1.14",
"description": "Simple ORM to manage and query your state trees",

@@ -5,0 +5,0 @@ "main": "lib/index.js",

@@ -33,5 +33,4 @@ redux-orm

}
Book.modelName = 'Book';
Book.meta = {name: 'Book'};
// Declare your related fields.

@@ -85,3 +84,3 @@ Book.fields = {

### Connecting to Redux
### Connect to Redux

@@ -113,3 +112,3 @@ To create our data schema, we create a Schema instance and register our models.

### Using with React
### Use with React

@@ -198,3 +197,3 @@ In your top level component, you can begin a `Session` to query your data with `redux-orm`.

This representation maintains an array of object ID's and an index of id's for quick access. (A single object array representation is also provided for use. It is possible to subclass `Meta` to use any structure you want).
This representation maintains an array of object ID's and an index of id's for quick access. (A single object array representation is also provided for use. It is possible to subclass `Backend` to use any structure you want).

@@ -205,3 +204,3 @@ `redux-orm` runs a mini-redux inside it. It queues any updates the library user records with action-like objects, and when `getNextState` is called, it applies those actions with its internal reducers. There's some room here to provide performance optimizations similar to Immutable.js.

Just like you can extend `Model`, you can do the same for `QuerySet` (customize methods on Model instance collections) and `Meta` (customize store access and updates).
Just like you can extend `Model`, you can do the same for `QuerySet` (customize methods on Model instance collections) and `Backend` (customize store access and updates).

@@ -227,3 +226,3 @@ ### Caveats

- `register(model1, model2, ...modelN)`: registers Model classes to the `Schema` instance.
- `define(name, [relatedFields], [metaOpts])`: shortcut to define and register simple models.
- `define(name, [relatedFields], [backendOpts])`: shortcut to define and register simple models.
- `from(state, [action])`: begins a new `Session` with `state`. If `action` is omitted, the session can be used to query the state data.

@@ -280,15 +279,13 @@ - `reducer()`: returns a reducer function that can be plugged into Redux. The reducer will return the next state of the database given the provided action. You need to register your models before calling this.

When declaring model classes, always remember to set the `meta` property, which must include at least the name of the model. You need to set the name explicitly because running your code through a mangler would otherwise break functionality. The name you declare in `meta` will be used to resolve all related fields.
When declaring model classes, always remember to set the `modelName` property. It needs to be set explicitly, because running your code through a mangler would otherwise break functionality. The `modelName` will be used to resolve all related fields.
**Declaring `meta`**:
**Declaring `backend`**:
```javascript
class Book extends Model {
static meta() {
return {
name: 'Book'
};
static get modelName() {
return 'Book';
}
}
// alternative:
Book.meta = {name: 'Book'};
Book.modelName = 'Book';
```

@@ -358,25 +355,13 @@

### Meta
### Backend
Meta holds both the meta information for a model class and the database backend functionality. You can use a custom Meta if you want to change the underlying data structure (for performance reasons etc.).
Backend implements the logic and holds the information for Models' underlying data structure. If you want to change how that works, subclass `Backend` or implement your own with the same interface, and override your models' `getBackendClass` classmethod.
See the full documentation for `Meta` [here](http://tommikaikkonen.github.io/redux-orm/Meta.html)
See the full documentation for `Backend` [here](http://tommikaikkonen.github.io/redux-orm/Backend.html)
**Instantiation**: will be done for you, but you supply the options object in `YourModelClass.meta`.
**Instantiation**: will be done for you. If you want to specify custom options, you can override the `YourModelClass.backend` property with the custom options that will be merged with the defaults. For most cases, the default options work well. They are:
E.g., if you set this meta options object:
```javascript
class Book extends Model {}
Book.meta = {name: 'Book'};
```
The `Meta` instance will have the following options:
```javascript
{
name: 'Book',
idAttribute: 'id',
branchName: 'Book', // Name of the branch in the redux store
indexById: true, // if false, data will be held in a single object array

@@ -389,5 +374,4 @@ ordered: true,

## License
MIT. See `LICENSE`

@@ -24,3 +24,3 @@ import UPDATE from './constants';

this.getClass().addMutation({
this.getClass().addUpdate({
type: UPDATE,

@@ -71,4 +71,4 @@ payload: {

const fromFieldName = m2mFromFieldName(declaredFromModel.getName());
const toFieldName = m2mToFieldName(declaredToModel.getName());
const fromFieldName = m2mFromFieldName(declaredFromModel.modelName);
const toFieldName = m2mToFieldName(declaredToModel.modelName);

@@ -75,0 +75,0 @@ const lookupObj = {};

import QuerySet from './QuerySet';
import Meta from './Meta';
import Backend from './Backend';
import Model from './Model';

@@ -22,3 +22,3 @@ import Schema from './Schema';

QuerySet,
Meta,
Backend,
Model,

@@ -25,0 +25,0 @@ Schema,

import forOwn from 'lodash/object/forOwn';
import {ManyToMany, ForeignKey} from './fields';
import Session from './Session';
import Meta from './Meta';
import Backend from './Backend';
import QuerySet from './QuerySet';
import {CREATE, UPDATE, DELETE, ORDER} from './constants';
import {match, m2mName, m2mToFieldName, m2mFromFieldName} from './utils';
import {match} from './utils';
/**
* The heart of an ORM, the data model.
* The static class methods manages the mutations
* The static class methods manages the updates
* passed to this. The class itself is connected to a session,

@@ -49,3 +48,3 @@ * and because of this you can only have a single session at a time

set: (value) => {
ModelClass.addMutation({
ModelClass.addUpdate({
type: UPDATE,

@@ -68,96 +67,52 @@ payload: {

static get state() {
return this.session.getState(this.getName());
return this.session.getState(this.modelName);
}
static toString() {
return `ModelClass: ${this.getName()}`;
return `ModelClass: ${this.modelName}`;
}
/**
* Returns the {@link Model} class used to instantiate a possible Through model.
* @return {Model} The Through model class used to handle many-to-many relations declared
* in this model.
*/
static getThroughModelClass() {
return Model;
}
static getManyToManyModels() {
const fields = this.fields;
const thisModelName = this.getName();
const models = [];
forOwn(fields, (fieldInstance, fieldName) => {
if (fieldInstance instanceof ManyToMany) {
let toModelName;
if (fieldInstance.toModelName === 'this') {
toModelName = thisModelName;
} else {
toModelName = fieldInstance.toModelName;
}
const fromFieldName = m2mFromFieldName(thisModelName);
const toFieldName = m2mToFieldName(toModelName);
const Through = class ThroughModel extends this.getThroughModelClass() {};
Through.meta = {
name: m2mName(thisModelName, fieldName),
};
Through.fields = {
[fromFieldName]: new ForeignKey(thisModelName),
[toFieldName]: new ForeignKey(toModelName),
};
models.push(Through);
}
});
return models;
}
/**
* Returns the options object passed to the {@link Meta} class constructor.
* You need to define this for every subclass.
* Returns the options object passed to the {@link Backend} class constructor.
*
* @return {Object} the options object used to instantiate a {@link Meta} class.
* @return {Object} the options object used to instantiate a {@link Backend} class.
*/
static meta() {
throw new Error('You must declare a static "meta" function in your Model class.');
static backend() {
return {
branchName: this.modelName,
};
}
static getMeta() {
if (typeof this.meta === 'function') {
return this.meta();
static _getBackendOpts() {
if (typeof this.backend === 'function') {
return this.backend();
}
if (typeof this.meta === 'undefined') {
throw new Error(`You must declare either a 'meta' class method or
a 'meta' class variable in your Model Class`);
if (typeof this.backend === 'undefined') {
throw new Error(`You must declare either a 'backend' class method or
a 'backend' class variable in your Model Class`);
}
return this.meta;
return this.backend;
}
/**
* Returns the {@link Meta} class used to instantiate
* the {@link Meta} instance for this {@link Model}.
* Returns the {@link Backend} class used to instantiate
* the {@link Backend} instance for this {@link Model}.
*
* Override this if you want to use a custom {@link Meta} class.
* @return {Meta} The {@link Meta} class or subclass to use for this {@link Model}.
* Override this if you want to use a custom {@link Backend} class.
* @return {Backend} The {@link Backend} class or subclass to use for this {@link Model}.
*/
static getMetaClass() {
return Meta;
static getBackendClass() {
return Backend;
}
/**
* Gets the {@link Meta} instance linked to this {@link Model}.
* @return {Meta} The {@link Meta} instance linked to this {@link Model}.
* Gets the {@link Backend} instance linked to this {@link Model}.
* @return {Backend} The {@link Backend} instance linked to this {@link Model}.
*/
static getMetaInstance() {
if (!this._meta) {
const MetaClass = this.getMetaClass();
this._meta = new MetaClass(this.getMeta());
static getBackend() {
if (!this._backend) {
const BackendClass = this.getBackendClass();
this._backend = new BackendClass(this._getBackendOpts());
}
return this._meta;
return this._backend;
}

@@ -167,3 +122,3 @@

* Gets the Model's next state by applying the recorded
* mutations.
* updates.
* @return {Object} The next state.

@@ -176,14 +131,14 @@ */

const meta = this.getMetaInstance();
const backend = this.getBackend();
const mutations = this.session.getMutationsFor(this);
const updates = this.session.getUpdatesFor(this);
return mutations.reduce((state, action) => {
return updates.reduce((state, action) => {
switch (action.type) {
case CREATE:
return meta.insert(state, action.payload);
return backend.insert(state, action.payload);
case UPDATE:
return meta.update(state, action.payload.idArr, action.payload.updater);
return backend.update(state, action.payload.idArr, action.payload.updater);
case DELETE:
return meta.delete(state, action.payload);
return backend.delete(state, action.payload);
default:

@@ -214,25 +169,12 @@ return state;

* Gets the default, empty state of the branch.
* Delegates to a {@link Meta} instance.
* Delegates to a {@link Backend} instance.
* @return {Object} The default state.
*/
static getDefaultState() {
return this.getMetaInstance().getDefaultState();
return this.getBackend().getDefaultState();
}
/**
* Gets the name of this {@link Model} class.
* Delegates to {@link Meta}.
*
* Constructors have a name property which we cannot
* override, so this is implemented as a method.
*
* @return {string} The name of this {@link Model} class.
*/
static getName() {
return this.getMetaInstance().name;
}
/**
* Returns the id attribute of this {@link Model}.
* Delegates to the related {@link Meta} instance.
* Delegates to the related {@link Backend} instance.
*

@@ -242,7 +184,7 @@ * @return {string} The id attribute of this {@link Model}.

static get idAttribute() {
return this.getMetaInstance().idAttribute;
return this.getBackend().idAttribute;
}
/**
* A convenience method to call {@link Meta#accessId} from
* A convenience method to call {@link Backend#accessId} from
* the {@link Model} class.

@@ -254,19 +196,19 @@ *

static accessId(id) {
return this.getMetaInstance().accessId(this.state, id);
return this.getBackend().accessId(this.state, id);
}
/**
* A convenience method to call {@link Meta#accessIdList} from
* A convenience method to call {@link Backend#accessIdList} from
* the {@link Model} class with the current state.
*/
static accessIds() {
return this.getMetaInstance().accessIdList(this.state);
return this.getBackend().accessIdList(this.state);
}
static accessList() {
return this.getMetaInstance().accessList(this.state);
return this.getBackend().accessList(this.state);
}
static iterator() {
return this.getMetaInstance().iterator(this.state);
return this.getBackend().iterator(this.state);
}

@@ -298,8 +240,8 @@

* A convenience method that delegates to the current {@link Session} instane.
* Adds the required metadata about this {@link Model} to the mutation object.
* @param {Object} mutation - the mutation to add.
* Adds the required backenddata about this {@link Model} to the update object.
* @param {Object} update - the update to add.
*/
static addMutation(mutation) {
mutation.meta = {name: this.getName()};
this.session.addMutation(mutation);
static addUpdate(update) {
update.meta = {name: this.modelName};
this.session.addUpdate(update);
}

@@ -331,3 +273,3 @@

this._cachedQuerySet = undefined;
this._meta = undefined;
this._backend = undefined;
this._setupDone = undefined;

@@ -364,3 +306,3 @@ }

this.addMutation({
this.addUpdate({
type: CREATE,

@@ -387,3 +329,3 @@ payload: props,

if (!this.accessIds().length) {
throw new Error(`No entities found for model ${this.getName()}`);
throw new Error(`No entities found for model ${this.modelName}`);
}

@@ -418,3 +360,3 @@ const ModelClass = this;

/**
* Records an ordering mutation for the objects.
* Records an ordering update for the objects.
* Note that if you create or update any objects after

@@ -429,3 +371,3 @@ * calling this, they won't be in order.

static setOrder(orderArg) {
this.addMutation({
this.addUpdate({
type: ORDER,

@@ -460,3 +402,3 @@ payload: orderArg,

toString() {
const className = this.getClass().getName();
const className = this.getClass().modelName;
const fields = this._fieldNames.map(fieldName => {

@@ -487,3 +429,3 @@ const val = this._fields[fieldName];

/**
* Records a mutation to the {@link Model} instance for a single
* Records a update to the {@link Model} instance for a single
* field value assignment.

@@ -499,3 +441,3 @@ * @param {string} propertyName - name of the property to set

/**
* Records a mutation to the {@link Model} instance for multiple field value assignments.
* Records a update to the {@link Model} instance for multiple field value assignments.
* @param {Object} mergeObj - an object that will be merged with this instance.

@@ -505,3 +447,3 @@ * @return {undefined}

update(mergeObj) {
this.getClass().addMutation({
this.getClass().addUpdate({
type: UPDATE,

@@ -520,3 +462,3 @@ payload: {

delete() {
this.getClass().addMutation({
this.getClass().addUpdate({
type: DELETE,

@@ -523,0 +465,0 @@ payload: [this.getId()],

@@ -14,3 +14,3 @@ import reject from 'lodash/collection/reject';

* - returns a subset clone of itself with [filter]{@link QuerySet#filter} and [exclude]{@link QuerySet#exclude}
* - records mutations to objects with [update]{@link QuerySet#update} and [delete]{@link QuerySet#delete}
* - records updates to objects with [update]{@link QuerySet#update} and [delete]{@link QuerySet#delete}
*

@@ -227,3 +227,3 @@ */

/**
* Records a mutation specified with `updater` to all the objects in the {@link QuerySet}.
* Records a update specified with `updater` to all the objects in the {@link QuerySet}.
* @param {Object|function} updater - an object to merge with all the objects in this

@@ -236,3 +236,3 @@ * queryset, or a mapper function that takes the

update(updater) {
this.modelClass.addMutation({
this.modelClass.addUpdate({
type: UPDATE,

@@ -251,3 +251,3 @@ payload: {

delete() {
this.modelClass.addMutation({
this.modelClass.addUpdate({
type: DELETE,

@@ -254,0 +254,0 @@ payload: this.idArr,

@@ -13,4 +13,12 @@ import forOwn from 'lodash/object/forOwn';

} from './descriptors';
import {m2mName, attachQuerySetMethods, reverseFieldName} from './utils';
import {
m2mName,
attachQuerySetMethods,
m2mToFieldName,
m2mFromFieldName,
reverseFieldName,
} from './utils';
/**

@@ -42,9 +50,9 @@ * Schema's responsibility is tracking the set of {@link Model} classes used in the database.

* @param {Function} [reducer] - the reducer function to use for this model
* @param {Object} [metaOpts] -Meta options for this model.
* @param {Object} [backendOpts] -Backend options for this model.
* @return {Model} The defined model class.
*/
define(modelName, relatedFields, reducer, metaOpts) {
define(modelName, relatedFields, reducer, backendOpts) {
class ShortcutDefinedModel extends Model {}
ShortcutDefinedModel.meta = Object.assign({name: modelName}, metaOpts);
ShortcutDefinedModel.modelName = modelName;
ShortcutDefinedModel.backend = backendOpts;
ShortcutDefinedModel.fields = relatedFields;

@@ -86,6 +94,3 @@

const m2m = model.getManyToManyModels();
m2m.forEach(m2mModel => m2mModel.invalidateCaches());
this.implicitThroughModels.push(...m2m);
this.registerManyToManyModelsFor(model);
this.registry.push(model);

@@ -95,2 +100,33 @@ });

registerManyToManyModelsFor(model) {
const fields = model.fields;
const thisModelName = model.modelName;
forOwn(fields, (fieldInstance, fieldName) => {
if (fieldInstance instanceof ManyToMany) {
let toModelName;
if (fieldInstance.toModelName === 'this') {
toModelName = thisModelName;
} else {
toModelName = fieldInstance.toModelName;
}
const fromFieldName = m2mFromFieldName(thisModelName);
const toFieldName = m2mToFieldName(toModelName);
const Through = class ThroughModel extends Model {};
Through.modelName = m2mName(thisModelName, fieldName);
Through.fields = {
[fromFieldName]: new ForeignKey(thisModelName),
[toFieldName]: new ForeignKey(toModelName),
};
Through.invalidateCaches();
this.implicitThroughModels.push(Through);
}
});
}
/**

@@ -103,3 +139,3 @@ * Gets a model by its name from the registry.

get(modelName) {
const found = find(this.registry.concat(this.implicitThroughModels), (model) => model.getName() === modelName);
const found = find(this.registry.concat(this.implicitThroughModels), (model) => model.modelName === modelName);
if (typeof found === 'undefined') {

@@ -139,3 +175,3 @@ throw new Error(`Did not find model ${modelName} from registry.`);

// Backwards.
const backwardsFieldName = reverseFieldName(model.getName());
const backwardsFieldName = reverseFieldName(model.modelName);
Object.defineProperty(

@@ -149,3 +185,3 @@ toModel.prototype,

// Forwards.
const throughModelName = m2mName(model.getName(), fieldName);
const throughModelName = m2mName(model.modelName, fieldName);
const throughModel = this.get(throughModelName);

@@ -161,3 +197,3 @@

// Backwards.
const backwardsFieldName = reverseFieldName(model.getName());
const backwardsFieldName = reverseFieldName(model.modelName);
Object.defineProperty(

@@ -179,3 +215,3 @@ toModel.prototype,

// Backwards.
const backwardsFieldName = model.getName().toLowerCase();
const backwardsFieldName = model.modelName.toLowerCase();
Object.defineProperty(

@@ -182,0 +218,0 @@ toModel.prototype,

@@ -22,6 +22,6 @@ import partition from 'lodash/collection/partition';

this.mutations = [];
this.updates = [];
models.forEach(modelClass => {
Object.defineProperty(this, modelClass.getName(), {
Object.defineProperty(this, modelClass.modelName, {
get: () => modelClass,

@@ -35,4 +35,4 @@ });

/**
* Records a mutation to the session.
* @param {Object} mutation - the mutation object. Must have keys
* Records an update to the session.
* @param {Object} update - the update object. Must have keys
* `type`, `payload` and `meta`. `meta`

@@ -42,19 +42,21 @@ * must also include a `name` attribute

*/
addMutation(mutation) {
this.mutations.push(mutation);
addUpdate(update) {
this.updates.push(update);
}
/**
* Gets the recorded mutations for `modelClass` and
* deletes them from the Session instance mutations list.
* Gets the recorded updates for `modelClass` and
* deletes them from the Session instance updates list.
*
* @param {Model} modelClass - the model class to get mutations for
* @return {Object[]} A list of the user-recorded mutations for `modelClass`.
* @param {Model} modelClass - the model class to get updates for
* @return {Object[]} A list of the user-recorded updates for `modelClass`.
*/
getMutationsFor(modelClass) {
const modelName = modelClass.getName();
getUpdatesFor(modelClass) {
const [updates, other] = partition(
this.updates,
'meta.name',
modelClass.modelName);
const [mutations, other] = partition(this.mutations, 'meta.name', modelName);
this.mutations = other;
return mutations;
this.updates = other;
return updates;
}

@@ -65,3 +67,3 @@

this.models.forEach(modelClass => {
state[modelClass.getName()] = modelClass.getDefaultState();
state[modelClass.modelName] = modelClass.getDefaultState();
});

@@ -84,10 +86,10 @@ return state;

reduce() {
this.mutations = [];
this.updates = [];
const nextState = {};
this.models.forEach(modelClass => {
nextState[modelClass.getName()] = modelClass.callUserReducer();
nextState[modelClass.modelName] = modelClass.callUserReducer();
});
// The remaining mutations are for M2M tables.
return this.mutations.reduce((state, action) => {
// The remaining updates are for M2M tables.
return this.updates.reduce((state, action) => {
const modelName = action.meta.name;

@@ -94,0 +96,0 @@ state[modelName] = this[modelName].getNextState();

@@ -25,7 +25,3 @@ import chai from 'chai';

Model = Object.create(BaseModel);
Model.meta = () => {
return {
name: 'Model',
};
};
Model.modelName = 'Model';
});

@@ -59,17 +55,17 @@

it('getMetaInstance works correctly', () => {
const MetaMockClass = sinon.stub();
Model.getMetaClass = () => MetaMockClass;
it('getBackend works correctly', () => {
const BackendMockClass = sinon.stub();
Model.getBackendClass = () => BackendMockClass;
const instance = Model.getMetaInstance();
expect(instance).to.be.an.instanceOf(MetaMockClass);
const instance = Model.getBackend();
expect(instance).to.be.an.instanceOf(BackendMockClass);
// Make sure the previous instance is cached
expect(Model.getMetaInstance()).to.equal(instance);
expect(Model.getBackend()).to.equal(instance);
});
});
describe('static method delegates to Meta', () => {
describe('static method delegates to Backend', () => {
let Model;
let metaMock;
let backendMock;
const stateMock = {};

@@ -79,9 +75,5 @@

Model = Object.create(BaseModel);
Model.meta = () => {
return {
name: 'Model',
};
};
metaMock = {};
Model.getMetaInstance = () => metaMock;
Model.modelName = 'Model';
backendMock = {};
Model.getBackend = () => backendMock;
Object.defineProperty(Model, 'state', {

@@ -94,3 +86,3 @@ get: () => stateMock,

const accessIdSpy = sinon.spy();
metaMock.accessId = accessIdSpy;
backendMock.accessId = accessIdSpy;

@@ -106,3 +98,3 @@ const arg = 1;

const accessIdsSpy = sinon.spy();
metaMock.accessIdList = accessIdsSpy;
backendMock.accessIdList = accessIdsSpy;

@@ -117,3 +109,3 @@ Model.accessIds();

const accessIdsSpy = sinon.spy();
metaMock.accessIdList = accessIdsSpy;
backendMock.accessIdList = accessIdsSpy;

@@ -143,7 +135,4 @@ Model.accessIds();

Model = class TestModel extends BaseModel {};
Model.meta = () => {
return {
name: 'Model',
};
};
Model.modelName = 'Model';
instance = new Model({id: 0, name: 'Tommi'});

@@ -153,9 +142,9 @@ });

it('delete works correctly', () => {
const addMutationSpy = sinon.spy();
Model.addMutation = addMutationSpy;
const addUpdateSpy = sinon.spy();
Model.addUpdate = addUpdateSpy;
expect(addMutationSpy).not.called;
expect(addUpdateSpy).not.called;
instance.delete();
expect(addMutationSpy).calledOnce;
expect(addMutationSpy.getCall(0).args[0]).to.deep.equal({
expect(addUpdateSpy).calledOnce;
expect(addUpdateSpy.getCall(0).args[0]).to.deep.equal({
type: DELETE,

@@ -167,9 +156,9 @@ payload: [instance.id],

it('update works correctly', () => {
const addMutationSpy = sinon.spy();
Model.addMutation = addMutationSpy;
const addUpdateSpy = sinon.spy();
Model.addUpdate = addUpdateSpy;
expect(addMutationSpy).not.called;
expect(addUpdateSpy).not.called;
instance.update({name: 'Matt'});
expect(addMutationSpy).calledOnce;
expect(addMutationSpy.getCall(0).args[0]).to.deep.equal({
expect(addUpdateSpy).calledOnce;
expect(addUpdateSpy.getCall(0).args[0]).to.deep.equal({
type: UPDATE,

@@ -186,3 +175,3 @@ payload: {

it('set works correctly', () => {
Model.addMutation = () => undefined;
Model.addUpdate = () => undefined;

@@ -189,0 +178,0 @@ const updateSpy = sinon.spy(instance, 'update');

@@ -50,3 +50,4 @@ import chai from 'chai';

PersonClass = class Person extends Model {};
PersonClass.meta = {name: 'Person'};
PersonClass.modelName = 'Person';
schema.register(PersonClass);

@@ -106,9 +107,9 @@ session = schema.from(state);

it('update records a mutation', () => {
it('update records a update', () => {
const updater = {name: 'Mark'};
expect(session.mutations).to.have.length(0);
expect(session.updates).to.have.length(0);
qs.update(updater);
expect(session.mutations).to.have.length(1);
expect(session.updates).to.have.length(1);
expect(session.mutations[0]).to.deep.equal({
expect(session.updates[0]).to.deep.equal({
type: UPDATE,

@@ -125,8 +126,8 @@ payload: {

it('delete records a mutation', () => {
expect(session.mutations).to.have.length(0);
it('delete records a update', () => {
expect(session.updates).to.have.length(0);
qs.delete();
expect(session.mutations).to.have.length(1);
expect(session.updates).to.have.length(1);
expect(session.mutations[0]).to.deep.equal({
expect(session.updates[0]).to.deep.equal({
type: DELETE,

@@ -152,3 +153,4 @@ payload: qs.idArr,

PersonSub.meta = {name: 'Person'};
PersonSub.modelName = 'Person';
PersonSub.querySetClass = CustomQuerySet;

@@ -155,0 +157,0 @@ const aSchema = new Schema();

@@ -19,17 +19,8 @@ import {expect} from 'chai';

}
static meta() {
return {
name: 'Person',
};
}
};
Location = class LocationModel extends Model {
static meta() {
return {
name: 'Location',
};
}
};
Person.modelName = 'Person';
Location = class LocationModel extends Model {};
Location.modelName = 'Location';
});

@@ -60,17 +51,7 @@

}
static meta() {
return {
name: 'Person',
};
}
}
PersonModel.modelName = 'Person';
class LocationModel extends Model {
static meta() {
return {
name: 'Location',
};
}
}
class LocationModel extends Model {}
LocationModel.modelName = 'Location';

@@ -137,8 +118,2 @@ schema.register(PersonModel);

static meta() {
return {
name: 'Person',
};
}
static reducer(state, action, Person) {

@@ -154,10 +129,5 @@ Person.create({id: 5, name: 'Mike', age: 30});

}
PersonModel.modelName = 'Person';
class LocationModel extends Model {
static meta() {
return {
name: 'Location',
};
}
toString() {

@@ -168,2 +138,4 @@ return `${this.name}, ${this.country}`;

LocationModel.modelName = 'Location';
schema.register(PersonModel);

@@ -256,7 +228,2 @@ schema.register(LocationModel);

}
static meta() {
return {
name: 'User',
};
}

@@ -278,9 +245,5 @@ static reducer(state, action, User) {

UserModel.modelName = 'User';
class ProfileModel extends Model {
static meta() {
return {
name: 'Profile',
};
}
static reducer(state, action, Profile) {

@@ -302,2 +265,4 @@ switch (action.type) {

ProfileModel.modelName = 'Profile';
schema.register(UserModel);

@@ -304,0 +269,0 @@ schema.register(ProfileModel);

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc