import type { Db } from "mongodb"; import z, { type ZodObject, type ZodType } from "zod"; /** * TODO ... */ export function takeOne(documents: TDocument[]): TDocument | undefined { return documents[0]; } /** * TODO ... */ export function makeDocumentParser(schema: TSchema): ModelParserFn { return ((value: unknown | unknown[]) => { if (Array.isArray(value)) { return value.map((value: unknown) => schema.parse(value)); } if (value === undefined || value === null) { return undefined; } return schema.parse(value); }) as ModelParserFn; } /** * TODO ... */ export function toParsedDocuments( schema: TSchema, ): (documents: unknown[]) => Promise[]> { return async function (documents: unknown[]) { const parsed = []; for (const document of documents) { parsed.push(await schema.parseAsync(document)); } return parsed; }; } /** * TODO ... */ export function toParsedDocument( schema: TSchema, ): (document?: unknown) => Promise | undefined> { return async function (document: unknown) { if (document === undefined || document === null) { return undefined; } return schema.parseAsync(document); }; } /** * Get a Set of collections that exists on a given mongo database instance. * * @param db - Mongo database to fetch collection list for. */ export async function getCollectionsSet(db: Db) { return db .listCollections() .toArray() .then((collections) => new Set(collections.map((c) => c.name))); } type ModelParserFn = { (value: unknown): z.infer | undefined; (value: unknown[]): z.infer[]; };