mirror of
https://github.com/zoriya/Kyoo.git
synced 2026-05-20 22:32:30 -04:00
Handle filter parsing with typebox
This commit is contained in:
+5
-1
@@ -2,9 +2,13 @@ import Elysia from "elysia";
|
||||
import type { KError } from "./models/error";
|
||||
|
||||
export const base = new Elysia({ name: "base" })
|
||||
.onError(({code, error}) => {
|
||||
.onError(({ code, error }) => {
|
||||
if (code === "VALIDATION") {
|
||||
const details = JSON.parse(error.message);
|
||||
if (details.code === "KError") {
|
||||
delete details.code;
|
||||
return details;
|
||||
}
|
||||
return {
|
||||
status: error.status,
|
||||
message: `Validation error on ${details.on}.`,
|
||||
|
||||
@@ -1,15 +1,19 @@
|
||||
import { and, desc, eq, sql } from "drizzle-orm";
|
||||
import { Elysia, t } from "elysia";
|
||||
import { KError } from "~/models/error";
|
||||
import { Genre, isUuid, processLanguages } from "~/models/utils";
|
||||
import { comment, RemovePrefix } from "~/utils";
|
||||
import {
|
||||
type FilterDef,
|
||||
Genre,
|
||||
isUuid,
|
||||
processLanguages,
|
||||
} from "~/models/utils";
|
||||
import { comment, type RemovePrefix } from "~/utils";
|
||||
import { db } from "../db";
|
||||
import { shows, showTranslations } from "../db/schema/shows";
|
||||
import { getColumns } from "../db/schema/utils";
|
||||
import { bubble } from "../models/examples";
|
||||
import { Movie, MovieStatus, MovieTranslation } from "../models/movie";
|
||||
import { Page } from "~/models/utils/page";
|
||||
import { type Filter, parseFilters } from "~/models/utils/filters-sql";
|
||||
import { Filter, type Page } from "~/models/utils";
|
||||
|
||||
// drizzle is bugged and doesn't allow js arrays to be used in raw sql.
|
||||
export function sqlarr(array: unknown[]) {
|
||||
@@ -38,7 +42,7 @@ const getTranslationQuery = (languages: string[]) => {
|
||||
|
||||
const { pk: _, kind, startAir, endAir, ...moviesCol } = getColumns(shows);
|
||||
|
||||
const movieFilters: Filter = {
|
||||
const movieFilters: FilterDef = {
|
||||
genres: {
|
||||
column: shows.genres,
|
||||
type: "enum",
|
||||
@@ -160,7 +164,6 @@ export const movies = new Elysia({ prefix: "/movies", tags: ["movies"] })
|
||||
if (key === "airDate") return { key: "startAir" as const, desc };
|
||||
return { key, desc };
|
||||
});
|
||||
const filters = parseFilters(filter, movieFilters);
|
||||
|
||||
// TODO: Add sql indexes on order keys
|
||||
|
||||
@@ -173,7 +176,7 @@ export const movies = new Elysia({ prefix: "/movies", tags: ["movies"] })
|
||||
})
|
||||
.from(shows)
|
||||
.innerJoin(transQ, eq(shows.pk, transQ.pk))
|
||||
.where(filters)
|
||||
.where(filter)
|
||||
.orderBy(
|
||||
...order.map((x) => (x.desc ? desc(shows[x.key]) : shows[x.key])),
|
||||
shows.pk,
|
||||
@@ -202,18 +205,7 @@ export const movies = new Elysia({ prefix: "/movies", tags: ["movies"] })
|
||||
// TODO: support explode: true (allow sort=slug,-createdAt). needs a pr to elysia
|
||||
{ explode: false, default: ["slug"] },
|
||||
),
|
||||
filter: t.Optional(
|
||||
t.String({
|
||||
description: comment`
|
||||
Filters to apply to the query.
|
||||
This is based on [odata's filter specification](https://docs.oasis-open.org/odata/odata/v4.01/odata-v4.01-part1-protocol.html#sec_SystemQueryOptionfilter).
|
||||
|
||||
Filters available: ${Object.keys(movieFilters).join(", ")}
|
||||
`,
|
||||
example:
|
||||
"(rating gt 75 and genres has action) or status eq planned",
|
||||
}),
|
||||
),
|
||||
filter: t.Optional(Filter({ def: movieFilters })),
|
||||
limit: t.Integer({
|
||||
minimum: 1,
|
||||
maximum: 250,
|
||||
|
||||
@@ -6,3 +6,9 @@ export const KError = t.Object({
|
||||
details: t.Optional(t.Any()),
|
||||
});
|
||||
export type KError = typeof KError.static;
|
||||
|
||||
export class KErrorT extends Error {
|
||||
constructor(message: string, details?: any) {
|
||||
super(JSON.stringify({ code: "KError", status: 422, message, details }));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
import type { Column } from "drizzle-orm";
|
||||
import { t } from "elysia";
|
||||
import { comment } from "~/utils";
|
||||
import { expression } from "./parser";
|
||||
import { toDrizzle } from "./to-sql";
|
||||
import { KErrorT } from "~/models/error";
|
||||
|
||||
export type FilterDef = {
|
||||
[key: string]:
|
||||
| {
|
||||
column: Column;
|
||||
type: "int" | "float" | "date" | "string";
|
||||
isArray?: boolean;
|
||||
}
|
||||
| { column: Column; type: "enum"; values: string[]; isArray?: boolean };
|
||||
};
|
||||
|
||||
export const Filter = ({
|
||||
def,
|
||||
description = "Filters to apply to the query.",
|
||||
}: { def: FilterDef; description?: string }) =>
|
||||
t
|
||||
.Transform(
|
||||
t.String({
|
||||
description: comment`
|
||||
${description}
|
||||
This is based on [odata's filter specification](https://docs.oasis-open.org/odata/odata/v4.01/odata-v4.01-part1-protocol.html#sec_SystemQueryOptionfilter).
|
||||
|
||||
Filters available: ${Object.keys(def).join(", ")}
|
||||
`,
|
||||
example: "(rating gt 75 and genres has action) or status eq planned",
|
||||
}),
|
||||
)
|
||||
.Decode((filter) => {
|
||||
return parseFilters(filter, def);
|
||||
})
|
||||
.Encode(() => {
|
||||
throw new Error("Can't encode filters");
|
||||
});
|
||||
|
||||
export const parseFilters = (filter: string | undefined, config: FilterDef) => {
|
||||
if (!filter) return undefined;
|
||||
const ret = expression.parse(filter);
|
||||
if (!ret.isOk) {
|
||||
throw new KErrorT(`Invalid filter: ${filter}.`, ret);
|
||||
}
|
||||
|
||||
return toDrizzle(ret.value, config);
|
||||
};
|
||||
@@ -1,6 +1,5 @@
|
||||
import {
|
||||
and,
|
||||
type Column,
|
||||
eq,
|
||||
gt,
|
||||
gte,
|
||||
@@ -13,29 +12,9 @@ import {
|
||||
sql,
|
||||
} from "drizzle-orm";
|
||||
import { comment } from "~/utils";
|
||||
import type { KError } from "../error";
|
||||
import { type Expression, expression, type Operator } from "./filters";
|
||||
|
||||
export type Filter = {
|
||||
[key: string]:
|
||||
| {
|
||||
column: Column;
|
||||
type: "int" | "float" | "date" | "string";
|
||||
isArray?: boolean;
|
||||
}
|
||||
| { column: Column; type: "enum"; values: string[]; isArray?: boolean };
|
||||
};
|
||||
|
||||
export const parseFilters = (filter: string | undefined, config: Filter) => {
|
||||
if (!filter) return undefined;
|
||||
const ret = expression.parse(filter);
|
||||
if (!ret.isOk) {
|
||||
throw new Error("todo");
|
||||
// return { status: 422, message: `Invalid filter: ${filter}.`, details: ret }
|
||||
}
|
||||
|
||||
return toDrizzle(ret.value, config);
|
||||
};
|
||||
import type { FilterDef } from "./index";
|
||||
import type { Expression, Operator } from "./parser";
|
||||
import { KErrorT } from "~/models/error";
|
||||
|
||||
const opMap: Record<Operator, typeof eq> = {
|
||||
eq: eq,
|
||||
@@ -47,58 +26,54 @@ const opMap: Record<Operator, typeof eq> = {
|
||||
has: eq,
|
||||
};
|
||||
|
||||
const toDrizzle = (expr: Expression, config: Filter): SQL | KError => {
|
||||
export const toDrizzle = (expr: Expression, config: FilterDef): SQL => {
|
||||
switch (expr.type) {
|
||||
case "op": {
|
||||
const where = `${expr.property} ${expr.operator} ${expr.value}`;
|
||||
const where = `${expr.property} ${expr.operator} ${expr.value.value}`;
|
||||
const prop = config[expr.property];
|
||||
|
||||
if (!prop) {
|
||||
return {
|
||||
status: 422,
|
||||
message: comment`
|
||||
throw new KErrorT(
|
||||
comment`
|
||||
Invalid property: ${expr.property}.
|
||||
Expected one of ${Object.keys(config).join(", ")}.
|
||||
`,
|
||||
details: { in: where },
|
||||
};
|
||||
{ in: where },
|
||||
);
|
||||
}
|
||||
|
||||
if (prop.type !== expr.value.type) {
|
||||
return {
|
||||
status: 422,
|
||||
message: comment`
|
||||
throw new KErrorT(
|
||||
comment`
|
||||
Invalid value for property ${expr.property}.
|
||||
Got ${expr.value.type} but expected ${prop.type}.
|
||||
`,
|
||||
details: { in: where },
|
||||
};
|
||||
{ in: where },
|
||||
);
|
||||
}
|
||||
if (
|
||||
prop.type === "enum" &&
|
||||
(expr.value.type === "enum" || expr.value.type === "string") &&
|
||||
!prop.values.includes(expr.value.value)
|
||||
) {
|
||||
return {
|
||||
status: 422,
|
||||
message: comment`
|
||||
throw new KErrorT(
|
||||
comment`
|
||||
Invalid value ${expr.value.value} for property ${expr.property}.
|
||||
Expected one of ${prop.values.join(", ")} but got ${expr.value.value}.
|
||||
`,
|
||||
details: { in: where },
|
||||
};
|
||||
{ in: where },
|
||||
);
|
||||
}
|
||||
|
||||
if (prop.isArray) {
|
||||
if (expr.operator !== "has" && expr.operator !== "eq") {
|
||||
return {
|
||||
status: 422,
|
||||
message: comment`
|
||||
throw new KErrorT(
|
||||
comment`
|
||||
Property ${expr.property} is an array but you wanted to use the
|
||||
operator ${expr.operator}. Only "has" is supported ("eq" is also aliased to "has")
|
||||
`,
|
||||
details: { in: where },
|
||||
};
|
||||
{ in: where },
|
||||
);
|
||||
}
|
||||
return sql`${expr.value.value} = any(${prop.column})`;
|
||||
}
|
||||
@@ -107,20 +82,15 @@ const toDrizzle = (expr: Expression, config: Filter): SQL | KError => {
|
||||
case "and": {
|
||||
const lhs = toDrizzle(expr.lhs, config);
|
||||
const rhs = toDrizzle(expr.rhs, config);
|
||||
if ("status" in lhs) return lhs;
|
||||
if ("status" in rhs) return rhs;
|
||||
return and(lhs, rhs)!;
|
||||
}
|
||||
case "or": {
|
||||
const lhs = toDrizzle(expr.lhs, config);
|
||||
const rhs = toDrizzle(expr.rhs, config);
|
||||
if ("status" in lhs) return lhs;
|
||||
if ("status" in rhs) return rhs;
|
||||
return or(lhs, rhs)!;
|
||||
}
|
||||
case "not": {
|
||||
const lhs = toDrizzle(expr.expression, config);
|
||||
if ("status" in lhs) return lhs;
|
||||
return not(lhs);
|
||||
}
|
||||
default:
|
||||
@@ -3,3 +3,5 @@ export * from "./genres";
|
||||
export * from "./image";
|
||||
export * from "./language";
|
||||
export * from "./resource";
|
||||
export * from "./filters";
|
||||
export * from "./page";
|
||||
|
||||
+3
-1
@@ -1,6 +1,8 @@
|
||||
// remove indent in multi-line comments
|
||||
export const comment = (str: TemplateStringsArray, ...values: any[]) =>
|
||||
str.reduce((acc, str, i) => `${acc}${str}${values[i]}`).replace(/^[^\S\n]+/gm, "");
|
||||
str
|
||||
.reduce((acc, str, i) => `${acc}${values[i - 1]}${str}`)
|
||||
.replace(/(^[^\S\n]+|\s+$|^\s+)/gm, "");
|
||||
|
||||
export type RemovePrefix<
|
||||
T extends string,
|
||||
|
||||
Reference in New Issue
Block a user