Skip to content

Instantly share code, notes, and snippets.

@xxzefgh
Last active February 1, 2023 15:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xxzefgh/8968c9c0def949f334fcc8c7b0c97a26 to your computer and use it in GitHub Desktop.
Save xxzefgh/8968c9c0def949f334fcc8c7b0c97a26 to your computer and use it in GitHub Desktop.
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