Skip to content

Commit

Permalink
Merge pull request #47 from nobitagit/fix/27/constructor-vs-direct-re…
Browse files Browse the repository at this point in the history
…lationship

Fix/27/constructor vs direct relationship
  • Loading branch information
richmolj authored Oct 25, 2019
2 parents 08d112e + efe25fa commit b684fd4
Show file tree
Hide file tree
Showing 2 changed files with 71 additions and 2 deletions.
4 changes: 3 additions & 1 deletion src/util/write-payload.ts
Original file line number Diff line number Diff line change
Expand Up @@ -118,11 +118,13 @@ export class WritePayload<T extends SpraypaintBase> {
} else {
// Either the related model is dirty, or it's a dirty relation
// (maybe the "department" is not dirty, but the employee changed departments
// or the model is new
if (
!this._isNewAndMarkedForDestruction(relatedModels) &&
(idOnly ||
this.model.hasDirtyRelation(key, relatedModels) ||
relatedModels.isDirty(nested))
relatedModels.isDirty(nested) ||
!this.model.isPersisted)
) {
data = this._processRelatedModel(relatedModels, nested, idOnly)
}
Expand Down
69 changes: 68 additions & 1 deletion test/unit/write-payload.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { sinon, expect } from "../test-helper"
import { WritePayload } from "../../src/util/write-payload"
import { Person, PersonWithDasherizedKeys } from "../fixtures"
import { Person, PersonWithDasherizedKeys, Author, Genre } from "../fixtures"

describe("WritePayload", () => {
it("Does not serialize number attributes as empty string", () => {
Expand Down Expand Up @@ -45,4 +45,71 @@ describe("WritePayload", () => {
}
})
})

it("sends persisted relationships defined via direct assignment", () => {
const genre = new Genre({ name: "Horror", id: "1" })
genre.isPersisted = true
const author = new Author()
author.genre = genre
const payload = new WritePayload(author, ["genre"])
expect(payload.asJSON()).to.deep.equal({
data: {
type: "authors",
relationships: {
genre: {
data: {
id: "1",
type: "genres",
method: "update"
}
}
}
},
included: [
{
id: "1",
type: "genres"
}
]
})
})

it("sends persisted relationships defined via constructor", () => {
const genre = new Genre({ name: "Horror", id: "1" })
genre.isPersisted = true
const author = new Author({ genre })
const payload = new WritePayload(author, ["genre"])
expect(payload.asJSON()).to.deep.equal({
data: {
type: "authors",
relationships: {
genre: {
data: {
id: "1",
type: "genres",
method: "update"
}
}
}
},
included: [
{
id: "1",
type: "genres"
}
]
})
})

it("does not send persisted relationships defined via constructor if not included", () => {
const genre = new Genre({ name: "Horror", id: "1" })
genre.isPersisted = true
const author = new Author({ genre })
const payload = new WritePayload(author)
expect(payload.asJSON()).to.deep.equal({
data: {
type: "authors"
}
})
})
})

0 comments on commit b684fd4

Please sign in to comment.