From ad8815dcf25bf74198964a779f6b02b7de8c8f1f Mon Sep 17 00:00:00 2001 From: Hans Pagel Date: Thu, 14 Dec 2023 16:15:46 +0100 Subject: [PATCH] fix: JSON.stringify for undici body --- .../snippetz-core/src/utils/objectToString.ts | 23 ++++++++++++++++++- .../src/undici.test.ts | 4 ++-- .../snippetz-plugin-node-undici/src/undici.ts | 2 +- 3 files changed, 25 insertions(+), 4 deletions(-) diff --git a/packages/snippetz-core/src/utils/objectToString.ts b/packages/snippetz-core/src/utils/objectToString.ts index f3d5411..30687f4 100644 --- a/packages/snippetz-core/src/utils/objectToString.ts +++ b/packages/snippetz-core/src/utils/objectToString.ts @@ -29,7 +29,28 @@ export function objectToString(obj: Record, indent = 0): string { )}` ) } else if (typeof value === 'string') { - parts.push(`${innerIndentation}${formattedKey}: '${value}'`) + let formattedValue = `${value}` + + if (value.startsWith('JSON.stringify')) { + // If it has more than one line, add indentation to the other lines + const lines = value.split('\n') + + if (lines.length > 1) { + formattedValue = lines + .map((line, index) => { + if (index === 0) { + return line + } + + return `${innerIndentation}${line}` + }) + .join('\n') + } + } else { + formattedValue = `'${value}'` + } + + parts.push(`${innerIndentation}${formattedKey}: ${formattedValue}`) } else { parts.push(`${innerIndentation}${formattedKey}: ${value}`) } diff --git a/packages/snippetz-plugin-node-undici/src/undici.test.ts b/packages/snippetz-plugin-node-undici/src/undici.test.ts index 738ba71..6a0611e 100644 --- a/packages/snippetz-plugin-node-undici/src/undici.test.ts +++ b/packages/snippetz-plugin-node-undici/src/undici.test.ts @@ -87,9 +87,9 @@ const { statusCode, body } = await request('https://example.com', { headers: { 'Content-Type': 'application/json' }, - body: { + body: JSON.stringify({ hello: 'world' - } + }) })`) }) diff --git a/packages/snippetz-plugin-node-undici/src/undici.ts b/packages/snippetz-plugin-node-undici/src/undici.ts index 0d76b09..208b979 100644 --- a/packages/snippetz-plugin-node-undici/src/undici.ts +++ b/packages/snippetz-plugin-node-undici/src/undici.ts @@ -63,7 +63,7 @@ export function undici(request?: Partial): Source { // JSON if (normalizedRequest.postData.mimeType === 'application/json') { - options.body = JSON.parse(options.body) + options.body = `JSON.stringify(${objectToString(JSON.parse(options.body))})` } }