From 3800693d8d63ce6cd9efdacb391161330f3eb7df Mon Sep 17 00:00:00 2001 From: Timo van Veenendaal Date: Tue, 2 Apr 2024 11:07:29 -0700 Subject: [PATCH] Helper types for FormData --- sdk/core/core-client-rest/src/multipart.ts | 66 +++++++++++++++++++++- 1 file changed, 64 insertions(+), 2 deletions(-) diff --git a/sdk/core/core-client-rest/src/multipart.ts b/sdk/core/core-client-rest/src/multipart.ts index cda5285b8733..f05a2628ab26 100644 --- a/sdk/core/core-client-rest/src/multipart.ts +++ b/sdk/core/core-client-rest/src/multipart.ts @@ -50,7 +50,69 @@ export interface PartDescriptor { body?: unknown; } -type MultipartBodyType = BodyPart["body"]; +export type RawMultipartBodyType = BodyPart["body"]; + +/** + * A part descriptor representing a multipart/form-data field with binary content. + */ +export interface BinaryFormDataPart< + TPartName extends string, + TPartType extends RawMultipartBodyType, +> extends PartDescriptor { + name: TPartName; + body: TPartType; + dispositionType?: "form-data"; + contentType?: string; + filename?: string; +} + +/** + * A part descriptor representing a multipart/form-data field with JSON content. + */ +export interface JsonFormDataPart extends PartDescriptor { + name: TPartName; + body: TPartType; + dispositionType?: "form-data"; + contentType?: "application/json; charset=UTF-8"; +} + +/** + * A part descriptor representing a multipart/form-data field with textual content. + */ +export interface TextFormDataPart extends PartDescriptor { + name: TPartName; + body: string; + dispositionType?: "form-data"; + contentType?: "text/plain; charset=UTF-8"; +} + +/** + * A type alias providing an appropriate multipart/form-data part descriptor for a part with + * name restricted to TPartName and part type restricted to TPartType. + */ +export type FormDataPart = + TPartType extends Array + ? FormDataPart + : TPartType extends string + ? TextFormDataPart + : TPartType extends RawMultipartBodyType + ? BinaryFormDataPart + : JsonFormDataPart; + +/** + * For a model TModel, returns a union of possible parts in a multipart/form-data request + */ +export type FormDataParts = { + [K in keyof TModel & string]: FormDataPart; +}[keyof TModel & string]; + +/** + * Utility type representing the expected body shape for a multipart/form-data request with + * the given model as a body. + */ +export type FormDataPayload> = + | Array> + | FormData; /** * Get value of a header in the part descriptor ignoring case @@ -139,7 +201,7 @@ function getContentDisposition(descriptor: PartDescriptor): string | undefined { return disposition; } -function normalizeBody(body?: unknown, contentType?: string): MultipartBodyType { +function normalizeBody(body?: unknown, contentType?: string): RawMultipartBodyType { if (body === undefined) { // zero-length body return new Uint8Array([]);