Skip to content

Commit

Permalink
feat: stringify buffers (#19)
Browse files Browse the repository at this point in the history
previously Buffers are stringified as objects - eg:
```json
> JSONSerializer({ word: Buffer.from('example') })
{"word":{"type":"Buffer","data":[101,120,97,109,112,108,101]}}
```

this proposal updates the default JSON Serializer to stringify buffers - eg:
```json
> JSONSerializer({ word: Buffer.from('example') })
{"word":"example"}
```
  • Loading branch information
pwmcintyre authored Feb 6, 2023
1 parent d603716 commit 5360142
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 7 deletions.
13 changes: 9 additions & 4 deletions src/serializers/JSONSerializer/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,19 @@
import { JSONSerializer } from '.'

describe(`when serializing an error`, () => {
const error = new Error('example')
const got = JSONSerializer({ error })

describe(`when serializing errors`, () => {
test('should stringify the error', () => {
const got = JSONSerializer({ error: new Error('example') })
expect(got).toEqual(`{"error":"Error: example"}`)
})
})

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

// more info
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Cyclic_object_value
describe(`when serializing recursive objects`, () => {
Expand Down
15 changes: 12 additions & 3 deletions src/serializers/JSONSerializer/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,20 @@ function getCircularReplacer() {
}
seen.add(value)
}
return replaceErrors(key, value)
return toStringers(key, value)
}
}

function replaceErrors(_: any, value: any) {
if (value instanceof Error) return value.toString()
// toStringers strigifies some specific types
function toStringers(_: any, value: any) {

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

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

return value
}

0 comments on commit 5360142

Please sign in to comment.