Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix stuff #6

Merged
merged 22 commits into from
Nov 21, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4,934 changes: 4,934 additions & 0 deletions package-lock.json

Large diffs are not rendered by default.

1 change: 0 additions & 1 deletion src/ambient.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ type MovieDTO = {
watched: boolean | false;
}


type Genre = {
_id: string;
name: string;
Expand Down
126 changes: 78 additions & 48 deletions src/db/collections.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,16 @@
import db from '$db/mongo';
import { areStringsSimilar, mapFetchedGenreToType, mapFetchedMovieToType } from '$lib';
import { type Collection, type FindCursor, type Document, type InsertManyResult, type InsertOneResult, ObjectId, type WithId } from 'mongodb';
import { error } from '@sveltejs/kit';
import {
type Collection,
type FindCursor,
type Document,
type InsertManyResult,
type InsertOneResult,
ObjectId,
type WithId,
MongoServerError
} from 'mongodb';

export const movies: Collection<MovieDTO> = db.collection<MovieDTO>('movies');
export const genres: Collection<GenreDTO> = db.collection<GenreDTO>('genres');
Expand All @@ -12,7 +22,8 @@ export const genres: Collection<GenreDTO> = db.collection<GenreDTO>('genres');
*/
export const addMovie = (movieData: MovieDTO): Promise<string> => {
return new Promise(async (resolve, reject) => {
return movies.insertOne(movieData)
return movies
.insertOne(movieData)
.then((res: InsertOneResult<Movie>) => {
if (res.acknowledged) {
resolve(JSON.stringify(res));
Expand All @@ -22,76 +33,95 @@ export const addMovie = (movieData: MovieDTO): Promise<string> => {
})
.catch((err) => {
reject(`Error adding movie: ${err}`);
})
});
});
};


/**
* Adds a new genres to the 'genres' collection.
* Adds new genres to the 'genres' collection.
* @param genresData - The genres to be added.
* @returns Promise<string[]> - Resolves with the ID of the added genres.
*/
export const addGenres = (genresData: GenreDTO[]): Promise<string[]> => {
return new Promise(async (resolve, reject) => {
let genreIds: string[] = [];
console.log(`Initial genres: ${JSON.stringify(genresData)}`)
try {
const genresDocument: Document[] = await fetchDataFromMongoDB(genres)
const mappedGenres: Genre[] = genresDocument.map((doc: Document) => mapFetchedGenreToType(doc))
return fetchDataFromMongoDB(genres)
.then(async (genresDocument: Document[]) => {
const mappedGenres: Genre[] = genresDocument.map((doc: Document) =>
mapFetchedGenreToType(doc)
);

console.log(`Mapped genres: ${JSON.stringify(mappedGenres)}`)
for (const gData of genresData) {
const foundGenre: Genre | undefined = mappedGenres.find(
async (g) => await areStringsSimilar(g.name, gData.name)
);
console.log(`Similar Genre: ${JSON.stringify(foundGenre)}`);

genresData.forEach(async (gData: GenreDTO) => {
console.log(`Reading genre: ${gData.name}`)
const foundGenre: Genre | undefined = mappedGenres.find((g) => {
const isTheSame: boolean = areStringsSimilar(gData.name, g.name)
console.info(`Is ${gData.name} same with ${g.name} : ${isTheSame}`)
return isTheSame
})
if (foundGenre) {
console.info(`Found genre: ${gData.name}, adding to genreList`)
genreIds = [...genreIds, foundGenre._id.toString()]
} else {
console.info(`New Genre: ${gData.name}, adding to collection`)
const genreToBeAdded: any = {
name: gData.name
if (foundGenre) {
genreIds = [...genreIds, foundGenre._id.toString()];
} else {
const genreToBeAdded: GenreDTO = {
name: gData.name
};

console.info(`New Genre: ${JSON.stringify(genreToBeAdded)}, adding to collection`);

const addingResult = await genres
.insertOne(genreToBeAdded)
.then((result: InsertOneResult<Genre>) => {
genreIds = [...genreIds, result.insertedId.toString()];
console.log(`Genre ${JSON.stringify(genreToBeAdded.name)} added to collection`);
})
.catch((err: MongoServerError) => {
console.error(`${err.message}`);
});
}
await genres.insertOne(genreToBeAdded)
.then((result) => {
genreIds = [...genreIds, result.insertedId.toString()]
})
}
console.log('Done adding genres to collection');
resolve(genreIds);
})
.catch((error: MongoServerError) => {
reject(error.message);
});

console.log('Done adding genres to collection')
resolve(genreIds);
} catch (error) {
reject(error)
}
});
};


export const updateMovieByid = async (id: string, movie: Movie): Promise<boolean> => {
return new Promise(async (resolve, reject) => {
const movieDocuments: Document[] = await fetchDataFromMongoDB(movies, { _id: new ObjectId(id) })
const mappedMovies: Movie[] = movieDocuments.map((doc: Document) => mapFetchedMovieToType(doc))
const res: Movie | undefined = mappedMovies.find((m) => m.title === movie.title)
const movieDocuments: Document[] = await fetchDataFromMongoDB(movies, {
_id: new ObjectId(id)
});
const mappedMovies: Movie[] = movieDocuments.map((doc: Document) => mapFetchedMovieToType(doc));
const res: Movie | undefined = mappedMovies.find((m) => m.title === movie.title);
});
}

};

export const fetchDataFromMongoDB = async (collection: any, options?: Record<string, any>): Promise<Document[]> => {
const cursor: FindCursor<Document[]> = collection.find(options);
return await cursor.toArray();
export const fetchDataFromMongoDB = async (
collection: any,
options?: Record<string, any>
): Promise<Document[]> => {
try {
const cursor: FindCursor<Document[]> = collection.find(options);
return await cursor.toArray();
} catch (err: any) {
throw error(err.code ? Number(err.code) : 500, `Error fetching data from MongoDB: ${error}`);
}
};

export const getDocumentById = async (collection: Collection<any>, id: string | undefined): Promise<Document> => {
// Modify getDocumentById method
export const getDocumentById = async (
collection: Collection<any>,
id: string | undefined
): Promise<Document> => {
return new Promise(async (resolve, reject) => {
if (id === undefined) {
reject('Cannot find document, id is undefined')
try {
const result: Document[] = await fetchDataFromMongoDB(collection, { _id: new ObjectId(id) });
if (result.length === 0) {
reject(`Document with id ${id} not found`);
}
resolve(result[0]);
} catch {
reject(`Document with id ${id} not found`);
}
resolve((await fetchDataFromMongoDB(collection, { _id: new ObjectId(id) }))[0])
});
}
};
5 changes: 3 additions & 2 deletions src/hooks.server.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import { startMongo } from '$db/mongo';
import { error } from '@sveltejs/kit';
import type { MongoServerError } from 'mongodb';

startMongo()
.then(() => {
console.log('Connected to MongoDB');
})
.catch((err: any) => {
throw error(500, `${err}`);
.catch((err: MongoServerError) => {
throw error(err.code ? Number(err.code) : 500, `${err.message}`);
});
30 changes: 18 additions & 12 deletions src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,31 +8,37 @@ describe('sum test', () => {
});

describe('similarity-test', () => {
it('check if ScienceFiction is similar to Science Fiction', () => {
it('check if ScienceFiction is similar to Science Fiction', async () => {
const firstString = 'ScienceFiction'
const secondString = 'Science Fiction'
expect(
areStringsSimilar(firstString, secondString)
).toBe(true);
const response = areStringsSimilar(firstString, secondString)
expect(response).toBe(true);
});
});

describe('similarity-test', () => {
it('check if Comedy is similar to RomaticComedy', () => {
it('check if Comedy is similar to RomaticComedy', async () => {
const firstString = 'ScienceFiction'
const secondString = 'Science Fiction'
expect(
areStringsSimilar(firstString, secondString)
).toBe(false);
const response = areStringsSimilar(firstString, secondString)
expect(response).toBe(false);
});
});

describe('similarity-test', () => {
it('check if ScienceFiction is similar to Science-Fiction', () => {
it('check if ScienceFiction is similar to Science-Fiction', async () => {
const firstString = 'ScienceFiction'
const secondString = 'Science-Fiction'
expect(
areStringsSimilar(firstString, secondString)
).toBe(true);
const response = areStringsSimilar(firstString, secondString)
expect(response).toBe(true);
});
});

describe('similarity-test', () => {
it('check if Great movie similar to Test Movie 5', async () => {
const firstString = ' Great Movie'
const secondString = 'Test Movie 5'
const response = areStringsSimilar(secondString, firstString)
expect(response).toBe(false);
});
});
8 changes: 5 additions & 3 deletions src/lib/components/MovieCard.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import { Button, buttonVariants } from '$lib/components/ui/button';
import { goto } from '$app/navigation';
import { toast } from 'svelte-sonner';
import { host, fetchMovies } from '$lib';
import { host, fetchMovies, store } from '$lib';
export let movie: Movie;

async function deleteMovie(): Promise<any> {
Expand Down Expand Up @@ -71,11 +71,13 @@
toast.promise(deleteMovie, {
loading: `Deleting ${movie.title}`,
success: (data) => {
fetchMovies();
store.update((state) => ({
...state,
movies: fetchMovies()
}));
return data.name;
},
error: (err) => {
fetchMovies();
return `${err}`;
}
});
Expand Down
Loading