From 75910240f0232cb6afdda2f95c10a3097e4c0025 Mon Sep 17 00:00:00 2001 From: Sriram Venkatesh Date: Tue, 21 Feb 2023 16:11:59 +1300 Subject: [PATCH] =?UTF-8?q?fix:=20=F0=9F=90=9B=20Ensure=20undefined=20is?= =?UTF-8?q?=20not=20serialzed=20(#21)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * 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 --------- Co-authored-by: Peter McIntyre --- src/serializers/JSONSerializer/index.test.ts | 11 ++++++++++- src/serializers/JSONSerializer/index.ts | 8 ++++---- 2 files changed, 14 insertions(+), 5 deletions(-) diff --git a/src/serializers/JSONSerializer/index.test.ts b/src/serializers/JSONSerializer/index.test.ts index e38c10a..afd9c1b 100644 --- a/src/serializers/JSONSerializer/index.test.ts +++ b/src/serializers/JSONSerializer/index.test.ts @@ -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`, () => { diff --git a/src/serializers/JSONSerializer/index.ts b/src/serializers/JSONSerializer/index.ts index 2b5d4be..9d60ad3 100644 --- a/src/serializers/JSONSerializer/index.ts +++ b/src/serializers/JSONSerializer/index.ts @@ -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 }