Add first drizzle query with multi-language

This commit is contained in:
Zoe Roux 2024-11-01 21:49:00 +01:00
parent 4c7a02b443
commit 6327e911ad
No known key found for this signature in database
4 changed files with 66 additions and 4 deletions

View File

@ -1,4 +0,0 @@
import { Elysia } from "elysia";
export const EntriesController = new Elysia()
.get('/entries', () => "hello");

View File

@ -0,0 +1,58 @@
import { Elysia, t } from "elysia";
import { Movie } from "../models/movie";
import { db } from "../db";
import { shows, showTranslations } from "../db/schema/shows";
import { eq, and, sql, or, inArray } from "drizzle-orm";
const findMovie = db
.select()
.from(shows)
.innerJoin(
db
.selectDistinctOn([showTranslations.language])
.from(showTranslations)
.where(
or(
inArray(showTranslations.language, sql.placeholder("langs")),
eq(showTranslations.language, shows.originalLanguage),
),
)
.orderBy(
sql`array_position(${showTranslations.language}, ${sql.placeholder("langs")})`,
)
.as("t"),
eq(shows.pk, showTranslations.pk),
)
.where(
and(
eq(shows.kind, "movie"),
or(
eq(shows.id, sql.placeholder("id")),
eq(shows.slug, sql.placeholder("id")),
),
),
)
.orderBy()
.limit(1)
.prepare("findMovie");
export const movies = new Elysia({ prefix: "/movies" })
.model({
movie: Movie,
error: t.Object({}),
})
.guard({
params: t.Object({
id: t.String(),
}),
response: { 200: "movie", 404: "error" },
})
.get("/:id", async ({ params: { id }, error }) => {
const ret = await findMovie.execute({ id });
if (ret.length !== 1) return error(404, {});
return {
...ret[0].shows,
...ret[0].t,
airDate: ret[0].shows.startAir,
};
});

View File

@ -1,6 +1,12 @@
import * as entries from "./schema/entries";
import * as shows from "./schema/shows";
import { drizzle } from "drizzle-orm/node-postgres";
export const db = drizzle({
schema: {
...entries,
...shows,
},
connection: {
user: process.env.POSTGRES_USER ?? "kyoo",
password: process.env.POSTGRES_PASSWORD ?? "password",

View File

@ -2,12 +2,14 @@ import { Elysia } from "elysia";
import { swagger } from "@elysiajs/swagger";
import { db } from "./db";
import { migrate } from "drizzle-orm/node-postgres/migrator";
import { movies } from "./controllers/movies";
await migrate(db, { migrationsFolder: "" });
const app = new Elysia()
.use(swagger())
.get("/", () => "Hello Elysia")
.use(movies)
.listen(3000);
console.log(`Api running at ${app.server?.hostname}:${app.server?.port}`);