From 9a54266967a662cf46fb64fa34f67fff445f48e5 Mon Sep 17 00:00:00 2001 From: Zoe Roux Date: Sun, 12 Jan 2025 16:18:06 +0100 Subject: [PATCH] Add /movies/random route --- api/src/controllers/movies.ts | 37 ++++++++++++++++++++++++++++++++++- 1 file changed, 36 insertions(+), 1 deletion(-) diff --git a/api/src/controllers/movies.ts b/api/src/controllers/movies.ts index 34928261..13cc221c 100644 --- a/api/src/controllers/movies.ts +++ b/api/src/controllers/movies.ts @@ -1,5 +1,5 @@ import { and, eq, sql } from "drizzle-orm"; -import { Elysia, t } from "elysia"; +import { Elysia, redirect, t } from "elysia"; import { KError } from "~/models/error"; import { comment } from "~/utils"; import { db } from "../db"; @@ -154,6 +154,41 @@ export const movies = new Elysia({ prefix: "/movies", tags: ["movies"] }) }, }, ) + .get( + "random", + async ({ error, redirect }) => { + const [id] = await db + .select({ id: shows.id }) + .from(shows) + .where(eq(shows.kind, "movie")) + .orderBy(sql`random()`) + .limit(1); + if (!id) + return error(404, { + status: 404, + message: "No movies in the database", + }); + return redirect(`/movies/${id}`); + }, + { + detail: { + description: "Get a random movie", + }, + response: { + 302: t.Void({ + description: + "Redirected to the [/movies/id](#tag/movies/GET/movies/{id}) route.", + }), + 404: { + ...KError, + description: "No movie found with the given id or slug.", + examples: [ + { status: 404, message: "Movie not found", details: undefined }, + ], + }, + }, + }, + ) .get( "", async ({