|
| 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 ChanelHuttLoader implements Loader { |
| 7 | + getLoaderName(): string { |
| 8 | + return 'chanelhutt'; |
| 9 | + } |
| 10 | + |
| 11 | + async loadData(): Promise<MediaItem[]> { |
| 12 | + const credits = await this.loadCredits(); |
| 13 | + const mediaItems = await this.loadMediaItems(); |
| 14 | + // Create a Hashmap to where the key is a string(MediaItem ID) and the value is the MediaItem object. |
| 15 | + const hashMapIndex = new Map<string, MediaItem>(); |
| 16 | + // Loops through the mediaItems and adds them to the map by their ID. |
| 17 | + for (const mediaItem of mediaItems) { |
| 18 | + hashMapIndex.set(mediaItem.getId(), mediaItem); |
| 19 | + } |
| 20 | + // Loops through the credits and adds them to the mediaItem by getting the mediaItem ID. |
| 21 | + for (const credit of credits) { |
| 22 | + const mediaItem = hashMapIndex.get(credit.getMediaItemId()); |
| 23 | + if (mediaItem) { |
| 24 | + mediaItem.addCredit(credit); |
| 25 | + } |
| 26 | + console.log( |
| 27 | + `Loaded ${credits.length} credits and ${mediaItems.length} media items`, |
| 28 | + ); |
| 29 | + } |
| 30 | + // Returns an array of the values from the hashmap. |
| 31 | + return Array.from(hashMapIndex.values()); |
| 32 | + } |
| 33 | + |
| 34 | + async loadMediaItems(): Promise<MediaItem[]> { |
| 35 | + const mediaItems = []; |
| 36 | + const readable = fs |
| 37 | + .createReadStream('data/media_items.csv', 'utf-8') |
| 38 | + .pipe(csv()); |
| 39 | + for await (const row of readable) { |
| 40 | + const { id, title, type, year } = row; |
| 41 | + mediaItems.push(new MediaItem(id, title, type, year, [])); |
| 42 | + } |
| 43 | + return mediaItems; |
| 44 | + } |
| 45 | + |
| 46 | + async loadCredits(): Promise<Credit[]> { |
| 47 | + const credits = []; |
| 48 | + const readable = fs |
| 49 | + .createReadStream('data/credits.csv', 'utf-8') |
| 50 | + .pipe(csv()); |
| 51 | + for await (const row of readable) { |
| 52 | + const { media_item_id, role, name } = row; |
| 53 | + credits.push(new Credit(media_item_id, name, role)); |
| 54 | + } |
| 55 | + return credits; |
| 56 | + } |
| 57 | +} |
0 commit comments