Last active
February 1, 2023 15:45
-
-
Save xxzefgh/8968c9c0def949f334fcc8c7b0c97a26 to your computer and use it in GitHub Desktop.
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 {Multipart, MultipartFile, MultipartValue} from '@fastify/multipart'; | |
import {FastifyRequest} from 'fastify'; | |
function isMultipartFile(m: Multipart): m is MultipartFile { | |
return !!m['toBuffer']; | |
} | |
async function getValueOrBuffer(m: Multipart): Promise<string | Buffer> { | |
if (isMultipartFile(m)) { | |
return m.toBuffer(); | |
} else { | |
return (m as MultipartValue<string>).value; | |
} | |
} | |
export async function parseMultipartRequest( | |
req: FastifyRequest | |
): Promise<Record<string, string | Buffer | (string | Buffer)[]>> { | |
let data: MultipartFile; | |
for await (const part of req.files()) { | |
await part.toBuffer(); | |
data = part; | |
} | |
const result: Record<string, string | Buffer | (string | Buffer)[]> = {}; | |
if (!data) { | |
return result; | |
} | |
for await (const [key, fieldObject] of Object.entries(data.fields)) { | |
let value: string | Buffer | (string | Buffer)[]; | |
if (Array.isArray(fieldObject)) { | |
value = await Promise.all(fieldObject.map((field) => getValueOrBuffer(field))); | |
} else { | |
value = await getValueOrBuffer(fieldObject); | |
} | |
result[key] = value; | |
} | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment