Skip to content

Commit

Permalink
fix(watchlist): add validation for creation request
Browse files Browse the repository at this point in the history
  • Loading branch information
yalagin committed May 15, 2023
1 parent c08897b commit 03316c6
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 5 deletions.
17 changes: 13 additions & 4 deletions server/entity/Watchlist.ts
Expand Up @@ -15,6 +15,7 @@ import {
Unique,
UpdateDateColumn,
} from 'typeorm';
import type { ZodNumber, ZodOptional, ZodString } from 'zod';

export class DuplicateWatchlistRequestError extends Error {}
export class NotFoundError extends Error {
Expand Down Expand Up @@ -65,10 +66,18 @@ export class Watchlist implements WatchlistItem {
Object.assign(this, init);
}

public static async createWatchlist(
watchlistRequest: Watchlist,
user: User
): Promise<Watchlist> {
public static async createWatchlist({
watchlistRequest,
user,
}: {
watchlistRequest: {
mediaType: MediaType;
ratingKey?: ZodOptional<ZodString>['_output'];
title?: ZodOptional<ZodString>['_output'];
tmdbId: ZodNumber['_output'];
};
user: User;
}): Promise<Watchlist> {
const watchlistRepository = getRepository(this);
const mediaRepository = getRepository(Media);
const tmdb = new TheMovieDb();
Expand Down
9 changes: 9 additions & 0 deletions server/interfaces/api/watchlistCreate.ts
@@ -0,0 +1,9 @@
import { MediaType } from '@server/constants/media';
import { z } from 'zod';

export const watchlistCreate = z.object({
ratingKey: z.coerce.string().optional(),
tmdbId: z.coerce.number(),
mediaType: z.nativeEnum(MediaType),
title: z.coerce.string().optional(),
});
9 changes: 8 additions & 1 deletion server/routes/watchlist.ts
Expand Up @@ -7,6 +7,8 @@ import logger from '@server/logger';
import { Router } from 'express';
import { QueryFailedError } from 'typeorm';

import { watchlistCreate } from '@server/interfaces/api/watchlistCreate';

const watchlistRoutes = Router();

watchlistRoutes.post<never, Watchlist, Watchlist>(
Expand All @@ -19,7 +21,12 @@ watchlistRoutes.post<never, Watchlist, Watchlist>(
message: 'You must be logged in to add watchlist.',
});
}
const request = await Watchlist.createWatchlist(req.body, req.user);
const values = watchlistCreate.parse(req.body);

const request = await Watchlist.createWatchlist({
watchlistRequest: values,
user: req.user,
});
return res.status(201).json(request);
} catch (error) {
if (!(error instanceof Error)) {
Expand Down

0 comments on commit 03316c6

Please sign in to comment.