import "reflect-metadata"; import { injectable } from "inversify"; import { getPayload } from "payload"; import type { SanitizedConfig } from "payload"; import type { IMediaRepository } from "../../application/repositories/media.repository.interface"; import type { Media } from "../../entities/models/media"; type PayloadMediaDoc = { id: string | number; alt?: string | null; url?: string | null; filename?: string | null; mimeType?: string | null; filesize?: number | null; width?: number | null; height?: number | null; }; function mapDoc(doc: PayloadMediaDoc): Media { return { id: String(doc.id), alt: doc.alt ?? "", url: doc.url ?? "", filename: doc.filename ?? "", mimeType: doc.mimeType ?? "", filesize: doc.filesize ?? 0, ...(doc.width != null && { width: doc.width }), ...(doc.height != null && { height: doc.height }), }; } @injectable() export class MediaRepository implements IMediaRepository { private config: SanitizedConfig; constructor(config: SanitizedConfig) { this.config = config; } async getMedia(id: string): Promise { const payload = await getPayload({ config: this.config }); try { const doc = await payload.findByID({ collection: "media", id, overrideAccess: true, }); return mapDoc(doc as PayloadMediaDoc); } catch { return undefined; } } async listMedia(opts?: { limit?: number; offset?: number }): Promise { const payload = await getPayload({ config: this.config }); const result = await payload.find({ collection: "media", limit: opts?.limit ?? 50, page: opts?.offset ? Math.floor(opts.offset / (opts.limit ?? 50)) + 1 : 1, overrideAccess: true, }); return result.docs.map((d) => mapDoc(d as PayloadMediaDoc)); } async deleteMedia(id: string): Promise { const payload = await getPayload({ config: this.config }); await payload.delete({ collection: "media", id, overrideAccess: true, }); } }