diff --git a/lesson_10/libraries/src/loaders/chanel_hutt_loader.ts b/lesson_10/libraries/src/loaders/chanel_hutt_loader.ts new file mode 100644 index 000000000..9b21fb652 --- /dev/null +++ b/lesson_10/libraries/src/loaders/chanel_hutt_loader.ts @@ -0,0 +1,57 @@ +import csv from 'csv-parser'; +import fs from 'fs'; +import { Credit, MediaItem } from '../models/index.js'; +import { Loader } from './loader.js'; + +export class ChanelHuttLoader implements Loader { + getLoaderName(): string { + return 'chanelhutt'; + } + + async loadData(): Promise { + const credits = await this.loadCredits(); + const mediaItems = await this.loadMediaItems(); + // Create a Hashmap to where the key is a string(MediaItem ID) and the value is the MediaItem object. + const hashMapIndex = new Map(); + // Loops through the mediaItems and adds them to the map by their ID. + for (const mediaItem of mediaItems) { + hashMapIndex.set(mediaItem.getId(), mediaItem); + } + // Loops through the credits and adds them to the mediaItem by getting the mediaItem ID. + for (const credit of credits) { + const mediaItem = hashMapIndex.get(credit.getMediaItemId()); + if (mediaItem) { + mediaItem.addCredit(credit); + } + console.log( + `Loaded ${credits.length} credits and ${mediaItems.length} media items`, + ); + } + // Returns an array of the values from the hashmap. + return Array.from(hashMapIndex.values()); + } + + async loadMediaItems(): Promise { + const mediaItems = []; + const readable = fs + .createReadStream('data/media_items.csv', 'utf-8') + .pipe(csv()); + for await (const row of readable) { + const { id, title, type, year } = row; + mediaItems.push(new MediaItem(id, title, type, year, [])); + } + return mediaItems; + } + + async loadCredits(): Promise { + const credits = []; + const readable = fs + .createReadStream('data/credits.csv', 'utf-8') + .pipe(csv()); + for await (const row of readable) { + const { media_item_id, role, name } = row; + credits.push(new Credit(media_item_id, name, role)); + } + return credits; + } +} diff --git a/lesson_10/libraries/src/loaders/loaders.module.ts b/lesson_10/libraries/src/loaders/loaders.module.ts index 197004e5a..dc2efb0b1 100644 --- a/lesson_10/libraries/src/loaders/loaders.module.ts +++ b/lesson_10/libraries/src/loaders/loaders.module.ts @@ -1,15 +1,16 @@ import { Module } from '@nestjs/common'; import { AnthonyMaysLoader } from './anthony_mays_loader.js'; +import { ChanelHuttLoader } from './chanel_hutt_loader.js'; import { DylanLaffertysLoader } from './dylan_lafferty_loaders.js'; import { MercedesMathewsLoader } from './mercedes_mathews_loader.js'; import { MontezBLoader } from './montez_b_loaders.js'; - export const Loaders = Symbol.for('Loaders'); const LOADER_PROVIDERS = [ AnthonyMaysLoader, DylanLaffertysLoader, + ChanelHuttLoader, MercedesMathewsLoader, MontezBLoader ];