Skip to content

Commit

Permalink
🔥 Removed npm package log: using pnpm
Browse files Browse the repository at this point in the history
  • Loading branch information
pitzzahh authored Nov 26, 2023
1 parent 0024f84 commit cc9b10b
Show file tree
Hide file tree
Showing 8 changed files with 202 additions and 5,163 deletions.
4,972 changes: 0 additions & 4,972 deletions package-lock.json

This file was deleted.

4 changes: 2 additions & 2 deletions src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ describe('similarity-test', () => {
it(`check if ${firstString} is ${
expected ? 'similar' : 'not similar'
} to ${secondString}`, async () => {
const response = checkSimilarity(firstString, secondString);
const response = checkSimilarity(firstString, secondString, true);
expect(response).toBe(expected);
});
});
Expand All @@ -26,7 +26,7 @@ describe('similarity-test', () => {
it(`check if ${firstString} is ${
expected ? 'similar' : 'not similar'
} to ${secondString}`, async () => {
const response = checkSimilarity(firstString, secondString, false, 1);
const response = checkSimilarity(firstString, secondString);
expect(response).toBe(expected);
});
});
Expand Down
10 changes: 5 additions & 5 deletions src/lib/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import type { Document } from 'mongodb';
import { writable } from 'svelte/store';
import { distance } from 'fastest-levenshtein';

const dev = false;
const dev = true;

export const movieFormInfo = [
{
Expand Down Expand Up @@ -77,18 +77,18 @@ export const toPascalCase = (str: string): string => {
export const areStringsSimilar = (
a: string,
b: string,
genreCheck: boolean = false,
advance: boolean = false,
threshHold: number = 0.5
): boolean => {
const similarityThreshold = threshHold ? threshHold : 0.1;
if (genreCheck) {
if (advance) {
return distance(a.toLowerCase(), b.toLowerCase()) > similarityThreshold;
}
const cleanString = (str: string): string => str.replace(/[-\s]/g, '');
const result =
levenshteinDistance(cleanString(a.toLowerCase()), cleanString(b.toLowerCase())) <=
similarityThreshold;
console.log(`Comparing ${a} and ${b}: ${result}`);
console.log(`${a} and ${b} the same: ${result}`);
return result;
};

Expand Down Expand Up @@ -137,5 +137,5 @@ export const fetchMovies = async (): Promise<Movie[]> => {
};

export const host: string = dev
? 'https://didactic-succotash-jprqjx6465php756-5173.app.github.dev'
? 'https://stunning-happiness-wqvgrw69494c56-5173.app.github.dev'
: 'https://sveltekit-movie-watchlist.vercel.app';
179 changes: 110 additions & 69 deletions src/routes/api/movies/+server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,9 @@ export const POST: RequestHandler = async ({ request }) => {
const res: Movie | undefined = mappedMovies.find((movie: Movie) =>
areStringsSimilar(requestBody.title, movie.title)
);
console.log(`Movie that is found similar: ${JSON.stringify(res)}`);
console.log(
`${res === undefined ? `No similar movie found` : `Similar movie found: %{res}`}`
);
if (res) {
return new Response(
JSON.stringify({ errorMessage: `Movie ${data.title} already exists` }),
Expand Down Expand Up @@ -140,6 +142,7 @@ export const POST: RequestHandler = async ({ request }) => {
{
status: 400,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST'
}
Expand Down Expand Up @@ -206,6 +209,7 @@ export const DELETE: RequestHandler = async ({ request }) => {
return new Response(JSON.stringify({ errorMessage: 'No movie id specified' }), {
status: 404,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'DELETE'
}
Expand All @@ -219,6 +223,7 @@ export const DELETE: RequestHandler = async ({ request }) => {
{
status: 400,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'DELETE'
}
Expand Down Expand Up @@ -247,6 +252,7 @@ export const DELETE: RequestHandler = async ({ request }) => {
{
status: 400,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'DELETE'
}
Expand Down Expand Up @@ -274,6 +280,7 @@ export const DELETE: RequestHandler = async ({ request }) => {
return new Response(JSON.stringify({ errorMessage: error.message }), {
status: 500,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'DELETE'
}
Expand All @@ -289,6 +296,7 @@ export const DELETE: RequestHandler = async ({ request }) => {
{
status: 404,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'DELETE'
}
Expand All @@ -299,6 +307,7 @@ export const DELETE: RequestHandler = async ({ request }) => {
return new Response(JSON.stringify({ errorMessage: 'Cannot delete movie, invalid body' }), {
status: 404,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'DELETE'
}
Expand All @@ -311,87 +320,119 @@ export const PATCH: RequestHandler = async ({ request }) => {

const requestBody: Movie = await request.json();

const genres: GenreDTO[] = requestBody.genres.map((genre: string) => ({
name: genre
}));

console.log(`Genres DTO: ${JSON.stringify(genres)}`);
return getDocumentById(movies, requestBody._id).then((document: Document) =>
addGenres(genres)
.then(async (genresId: string[]) => {
const data: MovieDTO = {
title: requestBody.title,
genres: genresId,
year: Number(requestBody.year),
rating: Number(requestBody.rating),
watched: requestBody.watched
};
const filter = { _id: new ObjectId(requestBody._id) };

const update = {
$set: {
title: data.title,
genres: data.genres,
year: data.year,
rating: data.rating,
watched: data.watched
}
};
const oldMovie: Movie | undefined = mapFetchedMovieToType(document);
const result: UpdateResult<Movie> = await movies.updateOne(filter, update);
return await fetchDataFromMongoDB(movies, { title: requestBody.title }).then(
(movieDocuments: Document[]) => {
const mappedMovies: Movie[] = movieDocuments.map((doc: Document) =>
mapFetchedMovieToType(doc)
);

const isAcknowledged = result.acknowledged;
const modifiedCount = result.modifiedCount;
const isUpdated = modifiedCount === 1;
const isValid = isAcknowledged && isUpdated;
const res: Movie | undefined = mappedMovies.find(
(movie: Movie) =>
movie._id !== requestBody._id && areStringsSimilar(requestBody.title, movie.title)
);

if (!isValid) {
return new Response(
JSON.stringify({
errorMessage: `Request is ${
isAcknowledged ? 'acknowledged' : 'not acknowledged'
}, movie is ${isUpdated ? 'updated' : 'not updated'} `
}),
{
status: 400,
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'PATCH'
}
}
);
}
const message = areStringsSimilar(oldMovie?.title, data.title)
? 'Movie updated sucessfully'
: `Movie ${oldMovie?.title} updated to ${data.title}`;
if (res) {
return new Response(
JSON.stringify({
movie: data,
message
errorMessage: `Movie with title ${requestBody.title} already exists`
}),
{
status: 202,
status: 409,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'PATCH'
}
}
);
})
.catch((error: MongoServerError) => {
return new Response(
JSON.stringify({
errorMessage: `Failed to update movie ${requestBody.title}: ${error.message}`
}),
{
status: 400,
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'PATCH'
}

const genres: GenreDTO[] = requestBody.genres.map((genre: string) => ({
name: genre
}));

console.log(`Genres DTO: ${JSON.stringify(genres)}`);

return getDocumentById(movies, requestBody._id).then((document: Document) =>
addGenres(genres)
.then(async (genresId: string[]) => {
const data: MovieDTO = {
title: requestBody.title,
genres: genresId,
year: Number(requestBody.year),
rating: Number(requestBody.rating),
watched: requestBody.watched
};
const filter = { _id: new ObjectId(requestBody._id) };

const update = {
$set: {
title: data.title,
genres: data.genres,
year: data.year,
rating: data.rating,
watched: data.watched
}
};
const oldMovie: Movie | undefined = mapFetchedMovieToType(document);
const result: UpdateResult<Movie> = await movies.updateOne(filter, update);

const isAcknowledged = result.acknowledged;
const modifiedCount = result.modifiedCount;
const isUpdated = modifiedCount === 1;
const isValid = isAcknowledged && isUpdated;

if (!isValid) {
return new Response(
JSON.stringify({
errorMessage: `Request is ${
isAcknowledged ? 'acknowledged' : 'not acknowledged'
}, movie is ${isUpdated ? 'updated' : 'not updated'} `
}),
{
status: 400,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'PATCH'
}
}
);
}
}
);
})
const message = areStringsSimilar(oldMovie?.title, data.title)
? 'Movie updated sucessfully'
: `Movie ${oldMovie?.title} updated to ${data.title}`;
return new Response(
JSON.stringify({
movie: data,
message
}),
{
status: 202,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'PATCH'
}
}
);
})
.catch((error: MongoServerError) => {
return new Response(
JSON.stringify({
errorMessage: `Failed to update movie ${requestBody.title}: ${error.message}`
}),
{
status: 400,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'PATCH'
}
}
);
})
);
}
);
};
1 change: 1 addition & 0 deletions src/routes/movie/+page.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ export const actions: Actions = {
if (!form.valid) {
return fail(400, {
form,
valid: false,
movie: undefined
});
}
Expand Down
53 changes: 53 additions & 0 deletions src/service-worker.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
/// <reference types="@sveltejs/kit" />
import { build, files, version } from '$service-worker';

const CACHE = `cache-${version}`;

const ASSETS = [
...build,
...files
];

self.addEventListener('install', (event) => {
async function addFilesToCache() {
const cache = await caches.open(CACHE);
await cache.addAll(ASSETS);
}

event.waitUntil(addFilesToCache());
});

self.addEventListener('activate', (event) => {
async function deleteOldCaches() {
for (const key of await caches.keys()) {
if (key !== CACHE) await caches.delete(key);
}
}

event.waitUntil(deleteOldCaches());
});

self.addEventListener('fetch', (event) => {
async function respond() {
const url = new URL(event.request.url);
const cache = await caches.open(CACHE);

if (ASSETS.includes(url.pathname)) {
return cache.match(url.pathname);
}

try {
const response = await fetch(event.request);

if (response.status === 200) {
cache.put(event.request, response.clone());
}

return response;
} catch {
return cache.match(event.request);
}
}

event.respondWith(respond());
});
Loading

0 comments on commit cc9b10b

Please sign in to comment.