|
| 1 | +import { Collection, Db } from 'mongodb'; |
| 2 | +import { ReleaseDBScheme, SourceMapFileChunk } from '@hawk.so/types'; |
| 3 | +import DataLoaders from '../dataLoaders'; |
| 4 | + |
| 5 | +interface ReleaseWithFileDetails extends ReleaseDBScheme { |
| 6 | + fileDetails?: SourceMapFileChunk[]; |
| 7 | +} |
| 8 | + |
| 9 | +export default class ReleasesFactory { |
| 10 | + /** |
| 11 | + * Releases collection |
| 12 | + */ |
| 13 | + private collection: Collection<ReleaseDBScheme>; |
| 14 | + |
| 15 | + /** |
| 16 | + * DataLoader for releases |
| 17 | + */ |
| 18 | + private dataLoaders: DataLoaders; |
| 19 | + |
| 20 | + /** |
| 21 | + * Creates an instance of the releases factory |
| 22 | + * @param dbConnection - database connection |
| 23 | + * @param dataLoaders - DataLoaders instance for request batching |
| 24 | + */ |
| 25 | + constructor(dbConnection: Db, dataLoaders: DataLoaders) { |
| 26 | + this.collection = dbConnection.collection('releases'); |
| 27 | + this.dataLoaders = dataLoaders; |
| 28 | + } |
| 29 | + |
| 30 | + /** |
| 31 | + * Get releases by project identifier with file sizes |
| 32 | + * @param projectId - project identifier |
| 33 | + */ |
| 34 | + public async findManyByProjectId(projectId: string): Promise<ReleaseDBScheme[]> { |
| 35 | + try { |
| 36 | + const releases = await this.collection.aggregate<ReleaseWithFileDetails>([ |
| 37 | + { |
| 38 | + $match: { |
| 39 | + projectId: projectId, |
| 40 | + }, |
| 41 | + }, |
| 42 | + { |
| 43 | + $lookup: { |
| 44 | + from: 'releases.files', |
| 45 | + let: { fileIds: '$files._id' }, |
| 46 | + pipeline: [ |
| 47 | + { |
| 48 | + $match: { |
| 49 | + $expr: { |
| 50 | + $in: ['$_id', '$$fileIds'], |
| 51 | + }, |
| 52 | + }, |
| 53 | + }, |
| 54 | + { |
| 55 | + $project: { |
| 56 | + _id: 1, |
| 57 | + length: 1, |
| 58 | + chunkSize: 1, |
| 59 | + }, |
| 60 | + }, |
| 61 | + ], |
| 62 | + as: 'fileDetails', |
| 63 | + }, |
| 64 | + }, |
| 65 | + ]).toArray(); |
| 66 | + |
| 67 | + return releases.map(release => this.enrichReleaseWithFileSizes(release)); |
| 68 | + } catch (error) { |
| 69 | + console.error(`[ReleasesFactory] Error in findManyByProjectId:`, error); |
| 70 | + throw error; |
| 71 | + } |
| 72 | + } |
| 73 | + |
| 74 | + /** |
| 75 | + * Enriches release with file sizes from file details |
| 76 | + * @param release - release with file details |
| 77 | + * @returns enriched release |
| 78 | + */ |
| 79 | + private enrichReleaseWithFileSizes(release: ReleaseWithFileDetails): ReleaseDBScheme { |
| 80 | + const fileDetailsMap = new Map( |
| 81 | + release.fileDetails?.map(detail => [detail._id.toString(), detail.length]) || [] |
| 82 | + ); |
| 83 | + |
| 84 | + return { |
| 85 | + ...release, |
| 86 | + files: release.files?.map(file => ({ |
| 87 | + ...file, |
| 88 | + size: fileDetailsMap.get(file._id?.toString() || '') || 0, |
| 89 | + })), |
| 90 | + }; |
| 91 | + } |
| 92 | +} |
0 commit comments