Skip to content

Commit

Permalink
types: handle buffers in JSONSerialized and fix issue with DocumentAr…
Browse files Browse the repository at this point in the history
…rays
  • Loading branch information
vkarpov15 committed Oct 23, 2024
1 parent ff24d86 commit 50b2670
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 6 deletions.
8 changes: 5 additions & 3 deletions test/types/schema.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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);
}
20 changes: 17 additions & 3 deletions types/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -718,6 +718,18 @@ declare module 'mongoose' {
: BufferToBinary<T[K]>;
} : T;

export type BufferToJSON<T> = T extends TreatAsPrimitives ? T : T extends Record<string, any> ? {
[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<infer ItemType>
? Types.DocumentArray<BufferToBinary<ItemType>>
: T[K] extends Types.Subdocument<unknown, unknown, infer SubdocType>
? HydratedSingleSubdocument<SubdocType>
: BufferToBinary<T[K]>;
} : T;

export type ObjectIdToString<T> = T extends TreatAsPrimitives ? T : T extends Record<string, any> ? {
[K in keyof T]: T[K] extends mongodb.ObjectId
? string
Expand Down Expand Up @@ -748,16 +760,18 @@ declare module 'mongoose' {
: T[K] extends (NativeDate | null | undefined)
? string | null | undefined
: T[K] extends Types.DocumentArray<infer ItemType>
? ItemType
? ItemType[]
: T[K] extends Types.Subdocument<unknown, unknown, infer SubdocType>
? SubdocType
: SubdocsToPOJOs<T[K]>;
} : T;

export type JSONSerialized<T> = SubdocsToPOJOs<
FlattenMaps<
ObjectIdToString<
DateToString<T>
BufferToJSON<
ObjectIdToString<
DateToString<T>
>
>
>
>;
Expand Down

0 comments on commit 50b2670

Please sign in to comment.