Skip to content

Commit e462b1d

Browse files
authored
Merge branch 'code-differently:main' into main
2 parents a4546f5 + 4df942b commit e462b1d

File tree

2 files changed

+62
-3
lines changed

2 files changed

+62
-3
lines changed
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
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 BenjaminScottLoader implements Loader {
7+
getLoaderName(): string {
8+
return 'benjaminscott';
9+
}
10+
11+
async loadData(): Promise<MediaItem[]> {
12+
const credits = await this.loadCredits();
13+
const mediaItems = await this.loadMediaItems();
14+
15+
const creditsByMediaId = new Map<string, Credit[]>();
16+
for (const credit of credits) {
17+
const mediaItemId = credit.getMediaItemId();
18+
const mediaCredits = creditsByMediaId.get(mediaItemId) || [];
19+
mediaCredits.push(credit);
20+
creditsByMediaId.set(mediaItemId, mediaCredits);
21+
}
22+
23+
for (const mediaItem of mediaItems) {
24+
const itemCredits = creditsByMediaId.get(mediaItem.getId()) || [];
25+
for (const credit of itemCredits) {
26+
mediaItem.addCredit(credit);
27+
}
28+
}
29+
30+
console.log(
31+
`Loaded ${credits.length} credits and ${mediaItems.length} media items`,
32+
);
33+
34+
return [...mediaItems.values()];
35+
}
36+
37+
async loadMediaItems(): Promise<MediaItem[]> {
38+
const mediaItems = [];
39+
const readable = fs
40+
.createReadStream('data/media_items.csv', 'utf-8')
41+
.pipe(csv());
42+
for await (const row of readable) {
43+
const { id, type, title, year } = row;
44+
mediaItems.push(new MediaItem(id, title, type, parseInt(year, 10), []));
45+
}
46+
return mediaItems;
47+
}
48+
49+
async loadCredits(): Promise<Credit[]> {
50+
const credits = [];
51+
const readable = fs
52+
.createReadStream('data/credits.csv', 'utf-8')
53+
.pipe(csv());
54+
for await (const row of readable) {
55+
const { media_item_id, role, name } = row;
56+
credits.push(new Credit(media_item_id, name, role));
57+
}
58+
return credits;
59+
}
60+
}

lesson_10/libraries/src/loaders/loaders.module.ts

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,10 @@
11
import { Module } from '@nestjs/common';
22
import { AnthonyMaysLoader } from './anthony_mays_loader.js';
3+
import { BenjaminScottLoader } from './benjamin_scott_loader.js';
34

45
export const Loaders = Symbol.for('Loaders');
56

6-
const LOADER_PROVIDERS = [
7-
AnthonyMaysLoader,
8-
];
7+
const LOADER_PROVIDERS = [AnthonyMaysLoader, BenjaminScottLoader];
98

109
@Module({
1110
providers: [

0 commit comments

Comments
 (0)