Skip to content
This repository has been archived by the owner on Sep 14, 2023. It is now read-only.

Commit

Permalink
Better error handling
Browse files Browse the repository at this point in the history
  • Loading branch information
Darko Kukovec committed Dec 16, 2017
1 parent 2178f19 commit 60135f4
Show file tree
Hide file tree
Showing 4 changed files with 43 additions and 1 deletion.
4 changes: 3 additions & 1 deletion .gitignore
Expand Up @@ -4,4 +4,6 @@ node_modules/*
npm-debug.log

.nyc_output
coverage
coverage

.vscode
7 changes: 7 additions & 0 deletions dist/Model.js
Expand Up @@ -480,6 +480,13 @@ var Model = /** @class */ (function () {
*/
Model.prototype.__setRef = function (ref, val) {
var _this = this;
var isArray = val instanceof Array || mobx_1.isObservableArray(val);
var hasModelInstances = isArray
? val.some(function (item) { return item instanceof Model; })
: val instanceof Model;
if (!this.__collection && hasModelInstances) {
throw new Error('Model needs to be in a collection to set a reference');
}
var type = this.__refs[ref];
var refs = utils_1.mapItems(val, this.__getValueRefs.bind(this, type));
var getRef = function () { return _this.__collection ? (_this.__getReferencedModels(ref) || undefined) : undefined; };
Expand Down
8 changes: 8 additions & 0 deletions src/Model.ts
Expand Up @@ -595,6 +595,14 @@ export class Model implements IModel {
* @memberOf Model
*/
private __setRef<T>(ref: string, val: T|Array<T>): IModel|Array<IModel> {
const isArray = val instanceof Array || isObservableArray(val);
const hasModelInstances = isArray
? (val as Array<T>).some((item) => item instanceof Model)
: val instanceof Model;

if (!this.__collection && hasModelInstances) {
throw new Error('Model needs to be in a collection to set a reference');
}
const type = this.__refs[ref];
const refs = mapItems<number|string>(val, this.__getValueRefs.bind(this, type));

Expand Down
25 changes: 25 additions & 0 deletions test/main.ts
Expand Up @@ -1615,4 +1615,29 @@ describe('MobX Collection Store', () => {
expect(foo.bar[2].id).to.equal(5);
});
});

describe('Error handling', () => {
it('Should throw when setting references on a model not in a collection', () => {
class FooModel extends Model {
public static type = 'foo';
public static refs = {bar: 'bar'};

public id: number|string;
public bar: BarModel;
}

class BarModel extends Model {
public static type = 'bar';

public id: number|string;
}

const bar = new BarModel({id: 1});

const foo1 = new FooModel({id: 1});
expect(foo1).to.be.an('object');

expect(() => new FooModel({id: 2, bar})).to.throw(Error, 'Model needs to be in a collection to set a reference');
});
});
});

0 comments on commit 60135f4

Please sign in to comment.