Skip to content

Commit

Permalink
Merge pull request #12 from wadetandy/master
Browse files Browse the repository at this point in the history
Allow Number types not to write empty string
  • Loading branch information
richmolj authored Jan 28, 2019
2 parents afa6707 + 1758fef commit 4eef84d
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 5 deletions.
18 changes: 13 additions & 5 deletions src/util/write-payload.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
JsonapiResourceMethod,
JsonapiResource
} from "../jsonapi-spec"
import { Attribute } from "../attribute"

export class WritePayload<T extends SpraypaintBase> {
model: T
Expand All @@ -31,9 +32,15 @@ export class WritePayload<T extends SpraypaintBase> {
attributes() {
const attrs: ModelRecord<T> = {}

this._eachAttribute((key, value) => {
this._eachAttribute((key, value, attrDef) => {
if (!this.model.isPersisted || (<any>this.model.changes())[key]) {
attrs[this.model.klass.serializeKey(key)] = value
let writeKey = this.model.klass.serializeKey(key)

if (attrDef.type === Number && (value as any) === "") {
attrs[writeKey] = null
} else {
attrs[writeKey] = value
}
}
})

Expand Down Expand Up @@ -242,14 +249,15 @@ export class WritePayload<T extends SpraypaintBase> {
}

private _eachAttribute<K extends Extract<keyof T, string>>(
callback: (key: K, val: T[K]) => void
callback: (key: K, val: T[K], attrDef: Attribute) => void
): void {
const modelAttrs = this.model.typedAttributes

Object.keys(modelAttrs).forEach(key => {
if (this.model.klass.attributeList[key].persist) {
let attrDef = this.model.klass.attributeList[key]
if (attrDef.persist) {
const value = modelAttrs[key]
callback(key as K, value)
callback(key as K, value, attrDef)
}
})
}
Expand Down
1 change: 1 addition & 0 deletions test/fixtures.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ export class Person extends ApplicationRecord {

@Attr firstName!: string | null
@Attr lastName!: string | null
@Attr({ type: Number }) age!: number | null
}

@Model()
Expand Down
17 changes: 17 additions & 0 deletions test/unit/write-payload.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,23 @@ import { WritePayload } from "../../src/util/write-payload"
import { Person, PersonWithDasherizedKeys } from "../fixtures"

describe("WritePayload", () => {
it("Does not serialize number attributes as empty string", () => {
let person = new Person({ first_name: "Joe", age: 23 })
;(person.age as any) = ""
person.lastName = ""
let payload = new WritePayload(person)
expect(payload.asJSON()).to.deep.equal({
data: {
type: "people",
attributes: {
first_name: "Joe",
last_name: "",
age: null
}
}
})
})

it("underscores attributes", () => {
let person = new Person({ first_name: "Joe" })
let payload = new WritePayload(person)
Expand Down

0 comments on commit 4eef84d

Please sign in to comment.