Skip to content

Commit 66d76ef

Browse files
committed
fix(kitsu-core): optional chain constructor calls to allow invalid JSON values
Closes #416
1 parent 924af18 commit 66d76ef

3 files changed

Lines changed: 11 additions & 3 deletions

File tree

packages/kitsu-core/src/deattribute/index.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@
2929
export function deattribute (data) {
3030
if (typeof data === 'object' && data !== null) {
3131
if (Array.isArray(data)) data.map(el => deattribute(el))
32-
else if (data.attributes && data.attributes.constructor === Object) {
32+
else if (data.attributes?.constructor === Object) {
3333
for (const key of Object.keys(data.attributes)) {
3434
// Hoist everything but attributes to parent to avoid issues with deleting
3535
// as can't delete data.attributes[key] as it will belete data[key] too

packages/kitsu-core/src/serialise/index.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ function isValid (isArray, type, payload, method) {
2424
}
2525
}
2626
} else {
27-
if (payload.constructor !== Object || Object.keys(payload).length === 0) {
27+
if (payload?.constructor !== Object || Object.keys(payload).length === 0) {
2828
throw new Error(`${method} requires an object or array body`)
2929
}
3030
// A POST request is the only request to not require an ID in spec
@@ -146,7 +146,7 @@ function serialiseRootObject (type, payload, method, options) {
146146
const node = payload[key]
147147
const nodeType = options.pluralTypes(options.camelCaseTypes(key))
148148
// 1. Skip null nodes, 2. Only grab objects, 3. Filter to only serialise relationable objects
149-
if (node !== null && node.constructor === Object && hasID(node)) {
149+
if (node !== null && node?.constructor === Object && hasID(node)) {
150150
data = serialiseObject(node, nodeType, key, data, method)
151151
// 1. Skip null nodes, 2. Only grab arrays, 3. Filter to only serialise relationable arrays
152152
} else if (node !== null && Array.isArray(node) && (node.length > 0 && hasID(node[0]))) {

packages/kitsu-core/src/serialise/index.spec.js

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -422,5 +422,13 @@ describe('kitsu-core', () => {
422422
data: [ resourceOutput, resourceOutput ]
423423
})
424424
})
425+
426+
it('does not error with an invalid JSON value (undefined)', () => {
427+
expect.assertions(1)
428+
const resource = { id: '1', content: undefined }
429+
const resourceOutput = { id: '1', type: 'posts', attributes: { content: undefined } }
430+
const input = serialise('posts', resource)
431+
expect(input).toEqual({ data: resourceOutput })
432+
})
425433
})
426434
})

0 commit comments

Comments
 (0)