From 50b2670d0102fa0686890e2fe6e282a6bb5b694c Mon Sep 17 00:00:00 2001 From: Valeri Karpov Date: Wed, 23 Oct 2024 14:03:03 -0400 Subject: [PATCH] types: handle buffers in JSONSerialized and fix issue with DocumentArrays --- test/types/schema.test.ts | 8 +++++--- types/index.d.ts | 20 +++++++++++++++++--- 2 files changed, 22 insertions(+), 6 deletions(-) diff --git a/test/types/schema.test.ts b/test/types/schema.test.ts index cc16a52341..2639c19f6c 100644 --- a/test/types/schema.test.ts +++ b/test/types/schema.test.ts @@ -1687,12 +1687,13 @@ async function gh14451() { const exampleSchema = new Schema({ myId: { type: 'ObjectId' }, myRequiredId: { type: 'ObjectId', required: true }, + myBuf: { type: Buffer, required: true }, subdoc: { type: new Schema({ subdocProp: Date }) - } - // docArr: [{ nums: [Number], times: [Date] }] + }, + docArr: [{ nums: [Number], times: [{ type: Date }] }] }); const Test = model('Test', exampleSchema); @@ -1701,9 +1702,10 @@ async function gh14451() { expectType<{ myId?: string | undefined | null, myRequiredId: string, + myBuf: { type: 'buffer', data: number[] }, subdoc?: { subdocProp?: string | undefined | null } | null, - // docArr: { nums: number[], times: string[] }[] + docArr: { nums: number[], times: string[] }[] }>({} as TestJSON); } diff --git a/types/index.d.ts b/types/index.d.ts index 2b557a7d3d..1f9692b14d 100644 --- a/types/index.d.ts +++ b/types/index.d.ts @@ -718,6 +718,18 @@ declare module 'mongoose' { : BufferToBinary; } : T; + export type BufferToJSON = T extends TreatAsPrimitives ? T : T extends Record ? { + [K in keyof T]: T[K] extends Buffer + ? { type: 'buffer', data: number[] } + : T[K] extends (Buffer | null | undefined) + ? { type: 'buffer', data: number[] } | null | undefined + : T[K] extends Types.DocumentArray + ? Types.DocumentArray> + : T[K] extends Types.Subdocument + ? HydratedSingleSubdocument + : BufferToBinary; + } : T; + export type ObjectIdToString = T extends TreatAsPrimitives ? T : T extends Record ? { [K in keyof T]: T[K] extends mongodb.ObjectId ? string @@ -748,7 +760,7 @@ declare module 'mongoose' { : T[K] extends (NativeDate | null | undefined) ? string | null | undefined : T[K] extends Types.DocumentArray - ? ItemType + ? ItemType[] : T[K] extends Types.Subdocument ? SubdocType : SubdocsToPOJOs; @@ -756,8 +768,10 @@ declare module 'mongoose' { export type JSONSerialized = SubdocsToPOJOs< FlattenMaps< - ObjectIdToString< - DateToString + BufferToJSON< + ObjectIdToString< + DateToString + > > > >;