Skip to content
This repository has been archived by the owner on Aug 28, 2024. It is now read-only.

Commit

Permalink
fix: JSON.stringify for undici body
Browse files Browse the repository at this point in the history
  • Loading branch information
hanspagel committed Dec 14, 2023
1 parent 67bbfde commit ad8815d
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 4 deletions.
23 changes: 22 additions & 1 deletion packages/snippetz-core/src/utils/objectToString.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,28 @@ export function objectToString(obj: Record<string, any>, 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}`)
}
Expand Down
4 changes: 2 additions & 2 deletions packages/snippetz-plugin-node-undici/src/undici.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,9 +87,9 @@ const { statusCode, body } = await request('https://example.com', {
headers: {
'Content-Type': 'application/json'
},
body: {
body: JSON.stringify({
hello: 'world'
}
})
})`)
})

Expand Down
2 changes: 1 addition & 1 deletion packages/snippetz-plugin-node-undici/src/undici.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ export function undici(request?: Partial<Request>): Source {

// JSON
if (normalizedRequest.postData.mimeType === 'application/json') {
options.body = JSON.parse(options.body)
options.body = `JSON.stringify(${objectToString(JSON.parse(options.body))})`
}
}

Expand Down

0 comments on commit ad8815d

Please sign in to comment.