Created
September 11, 2024 16:52
-
-
Save JavascriptMick/72fab79e399abaf48429a7a1e2d6f3b2 to your computer and use it in GitHub Desktop.
Accept gzipped json POST request in Nuxt3/H3
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { H3Event, readBody, eventHandler } from 'h3'; | |
import { createGunzip } from 'zlib'; | |
import { pipeline } from 'stream'; | |
import { promisify } from 'util'; | |
const pipelineAsync = promisify(pipeline); | |
export default eventHandler(async (event: H3Event) => { | |
let rawBody = '{}'; | |
if (event.headers.get('content-encoding') === 'gzip') { | |
const { req } = event; // deprecated but it works... open to suggestion, readBody fails | |
const gunzip = createGunzip(); | |
const decompressedData: Buffer = await new Promise((resolve, reject) => { | |
const chunks: Buffer[] = []; | |
pipelineAsync(req, gunzip) | |
.then(() => { | |
gunzip.on('data', chunk => chunks.push(chunk)); | |
gunzip.on('end', () => resolve(Buffer.concat(chunks))); | |
gunzip.on('error', reject); | |
}) | |
.catch(reject); | |
}); | |
rawBody = JSON.parse(decompressedData.toString()); | |
} else { | |
rawBody = await readBody(event); | |
} | |
// .... Do something with rawBody | |
return 'ok'; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
In case you want to send a gzipped post request from some client.