Skip to content

Commit 30017b7

Browse files
authored
Fix #dup() with relationships (#106)
This is a simpler implementation that doesn't blow up when the object has relationships.
1 parent c9ce488 commit 30017b7

File tree

2 files changed

+21
-5
lines changed

2 files changed

+21
-5
lines changed

src/model.ts

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -653,11 +653,8 @@ export class JSORMBase {
653653
}
654654

655655
dup(): this {
656-
let nonEnums = getNonEnumerables(this)
657-
flipEnumerable(this, nonEnums, true)
658-
let cloned = cloneDeep(this)
659-
flipEnumerable(this, nonEnums, false)
660-
flipEnumerable(cloned, nonEnums, false)
656+
let attrs = Object.assign({}, this.attributes, this.relationships)
657+
let cloned = new this.klass(attrs) as any
661658
return cloned
662659
}
663660

test/unit/model.test.ts

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ import {
1818
} from "../fixtures"
1919

2020
import { Model, Attr, HasOne, HasMany, BelongsTo } from "../../src/decorators"
21+
import { eq } from 'lodash-es';
2122

2223
// Accessing private property in unit tests so we need a type-loose conversion function
2324
const modelAttrs = (model: JSORMBase): Record<string, any> =>
@@ -1426,6 +1427,24 @@ describe("Model", () => {
14261427
descriptor = Object.getOwnPropertyDescriptor(duped, 'relationships') as PropertyDescriptor
14271428
expect(descriptor.enumerable).to.eq(false)
14281429
})
1430+
1431+
// NB: does NOT dupe the relationships
1432+
describe("when nested relationships", () => {
1433+
it("still works", () => {
1434+
let author = new Author({ firstName: "Stephen" })
1435+
author.isPersisted = true
1436+
let genre = new Genre({ name: 'Horror' })
1437+
genre.isPersisted = true
1438+
let book1 = new Book({ genre })
1439+
book1.isPersisted = true
1440+
author.books = [book1]
1441+
let duped = author.dup()
1442+
expect(duped.books).to.deep.eq([book1])
1443+
expect(duped.books[0].isPersisted).to.eq(true)
1444+
expect(duped.books[0].genre).to.eq(genre)
1445+
expect(duped.books[0].genre.isPersisted).to.eq(true)
1446+
})
1447+
})
14291448
})
14301449

14311450
describe("#fetchOptions", () => {

0 commit comments

Comments
 (0)