Skip to content
This repository has been archived by the owner on Jan 24, 2022. It is now read-only.

Commit

Permalink
#15 Each method from the CreateRelated should be with new record as c…
Browse files Browse the repository at this point in the history
…ontext
  • Loading branch information
onechiporenko committed Jul 17, 2017
1 parent b4f0e74 commit 502ea60
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 4 deletions.
2 changes: 1 addition & 1 deletion lib/lair.ts
Original file line number Diff line number Diff line change
Expand Up @@ -371,7 +371,7 @@ export class Lair {
keys(createRelated).forEach(attrName => {
const fName = meta[attrName].factoryName;
const isHasMany = meta[attrName].type === MetaAttrType.HAS_MANY;
const relatedCount = isHasMany ? getOrCalcValue(createRelated[attrName], record.id) : 1;
const relatedCount = isHasMany ? getOrCalcValue(createRelated[attrName], record, record.id) : 1;
const relatedRecords = this.internalCreateRecords(fName, relatedCount, {factoryName, attrName}, [...relatedChain, factoryName]);
this.db[factoryName][record.id][attrName] = isHasMany ? relatedRecords : relatedRecords[0];
});
Expand Down
4 changes: 2 additions & 2 deletions lib/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@ export function copy(val: any): any {
return JSON.parse(JSON.stringify(val));
}

export function getOrCalcValue(v: any, ...args): any {
return v instanceof Function ? v.apply(null, args) : v;
export function getOrCalcValue(v: any, context = {}, ...args): any {
return v instanceof Function ? v.apply(context, args) : v;
}

export function getVal(obj, key, defaultVal) {
Expand Down
20 changes: 19 additions & 1 deletion tests/lair.ts
Original file line number Diff line number Diff line change
Expand Up @@ -317,7 +317,7 @@ describe('Lair', () => {
});

describe('allow function for `createRelated` value', () => {
it('record id is passed to the function', () => {
it('record id is passed to the function [backward compatibility]', () => {
this.lair.registerFactory(Factory.create({
attrs: {
b: Factory.hasOne('b', null),
Expand All @@ -333,6 +333,24 @@ describe('Lair', () => {
this.lair.createRecords('a', 1);
expect(this.lair.getAll('b').map(c => c.id)).to.be.eql(['1']);
});
it('record is used as context for the function', () => {
this.lair.registerFactory(Factory.create({
attrs: {
b: Factory.hasOne('b', null),
c: 'some val',
},
createRelated: {
b() {
expect(this.id).to.be.equal('1');
expect(this.c).to.be.equal('some val');
return 1;
},
},
}), 'a');
this.lair.registerFactory(Factory.create({}), 'b');
this.lair.createRecords('a', 1);
expect(this.lair.getAll('b').map(r => r.id)).to.be.eql(['1']);
});
});

describe('should create records with reflexive relations', () => {
Expand Down

0 comments on commit 502ea60

Please sign in to comment.