|
| 1 | +import csv from 'csv-parser'; |
| 2 | +import fs from 'fs'; |
| 3 | +import { Credit, MediaItem } from '../models/index.js'; |
| 4 | +import { Loader } from './loader.js'; |
| 5 | + |
| 6 | +export class DylanLaffertysLoader implements Loader { |
| 7 | + getLoaderName(): string { |
| 8 | + return 'dylanlafferty'; |
| 9 | + } |
| 10 | + async loadData(): Promise<MediaItem[]> { |
| 11 | + const credits = await this.loadCredits(); //loads credits from the csv file |
| 12 | + const mediaItems = await this.loadMediaItems(); //loads media items from csv file |
| 13 | + |
| 14 | + //Creates a map where the key is a string and the value is MediaItem Object |
| 15 | + const mapIndex = new Map<string, MediaItem>(); |
| 16 | + |
| 17 | + //Loops through the CSV file and gets the id of the mediaItem that is specified. |
| 18 | + for (const mediaItem of mediaItems) { |
| 19 | + mapIndex.set(mediaItem.getId(), mediaItem); |
| 20 | + |
| 21 | + } |
| 22 | + |
| 23 | + for (const credit of credits) { |
| 24 | + const mediaItem = mapIndex.get(credit.getMediaItemId()); //Finds the media item by getting media ID |
| 25 | + if (mediaItem) { |
| 26 | + mediaItem.addCredit(credit); |
| 27 | + } |
| 28 | + } |
| 29 | + |
| 30 | + console.log( |
| 31 | + `Loaded ${credits.length} credits and ${mediaItems.length} media items`, |
| 32 | + ); |
| 33 | + //Returns a newly created array by converting the map values |
| 34 | + return Array.from(mapIndex.values()); |
| 35 | + } |
| 36 | + |
| 37 | + async loadMediaItems(): Promise<MediaItem[]> { |
| 38 | + const mediaItem = []; |
| 39 | + const readable = fs |
| 40 | + .createReadStream('data/media_items.csv', 'utf-8') |
| 41 | + .pipe(csv()); |
| 42 | + |
| 43 | + for await (const row of readable) { |
| 44 | + const { id, title, type, year } = row; |
| 45 | + mediaItem.push(new MediaItem(id, title, type, year, [])); |
| 46 | + } |
| 47 | + return mediaItem; |
| 48 | + } |
| 49 | + |
| 50 | + async loadCredits(): Promise<Credit[]> { |
| 51 | + const credits = []; |
| 52 | + const readable = fs |
| 53 | + .createReadStream('data/credits.csv', 'utf-8') |
| 54 | + .pipe(csv()); |
| 55 | + for await (const row of readable) { |
| 56 | + const { media_item_id, role, name } = row; |
| 57 | + credits.push(new Credit(media_item_id, name, role)); |
| 58 | + } |
| 59 | + return credits; |
| 60 | + } |
| 61 | +} |
| 62 | +//# sourceMappingURL=dylan_lafferty_loaders.js.map |
0 commit comments