Skip to content

Commit

Permalink
fix: πŸ› Ensure undefined is not serialzed (#21)
Browse files Browse the repository at this point in the history
* fix: πŸ› Ensure undefined is not serialzed

Prior to this change, messages that 'undefined' are attempted to
be serialized - this would cause the following exception to be
raised:

```bash
TypeError: Cannot read properties of undefined (reading 'type')
```

After this change, a simple non-null assertion is made to ensure
the type of the value is not accessed if the value is undefined

* refactor: ♻️  Return early if falsy

* Update src/serializers/JSONSerializer/index.ts

Co-authored-by: Peter McIntyre <[email protected]>

---------

Co-authored-by: Peter McIntyre <[email protected]>
  • Loading branch information
srizzling and pwmcintyre authored Feb 21, 2023
1 parent 2e9ee75 commit 7591024
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 5 deletions.
11 changes: 10 additions & 1 deletion src/serializers/JSONSerializer/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,20 @@ describe(`when serializing errors`, () => {

describe(`when serializing buffers`, () => {
test('should stringify the buffer', () => {
const got = JSONSerializer({ word: Buffer.from('example') })
const got = JSONSerializer({ word: Buffer.from('example') })
expect(got).toEqual(`{"word":"example"}`)
})
})

describe(`when serializing undefined or null objects`, () => {
test.each([
[undefined, undefined],
[null, 'null'],
])('should not attempt to serialize', (input, expected) => {
expect(JSONSerializer(input)).toEqual(expected)
})
})

// more info
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Cyclic_object_value
describe(`when serializing recursive objects`, () => {
Expand Down
8 changes: 4 additions & 4 deletions src/serializers/JSONSerializer/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,14 @@ function getCircularReplacer() {

// toStringers strigifies some specific types
function toStringers(_: any, value: any) {
// exit early for null and undefined
if (value === undefined || value === null) return value

// error
if (value instanceof Error)
return value.toString()
if (value instanceof Error) return value.toString()

// buffer
if (value.type !== undefined && value.type === "Buffer")
return Buffer.from(value).toString()
if (value.type === 'Buffer') return Buffer.from(value).toString()

return value
}

0 comments on commit 7591024

Please sign in to comment.