fix RepoQuery typings

This commit is contained in:
dswbx
2025-01-16 16:21:32 +01:00
parent 371184d232
commit c6cbd36231
11 changed files with 39 additions and 39 deletions

View File

@@ -7,7 +7,7 @@ import {
Type,
Value
} from "core/utils";
import { WhereBuilder } from "../entities";
import { WhereBuilder, type WhereQuery } from "../entities";
const NumberOrString = (options: SchemaOptions = {}) =>
Type.Transform(Type.Union([Type.Number(), Type.String()], options))
@@ -15,10 +15,8 @@ const NumberOrString = (options: SchemaOptions = {}) =>
.Encode(String);
const limit = NumberOrString({ default: 10 });
const offset = NumberOrString({ default: 0 });
// @todo: allow "id" and "-id"
const sort_default = { by: "id", dir: "asc" };
const sort = Type.Transform(
Type.Union(
@@ -28,20 +26,20 @@ const sort = Type.Transform(
}
)
)
.Decode((value) => {
.Decode((value): { by: string; dir: "asc" | "desc" } => {
if (typeof value === "string") {
if (/^-?[a-zA-Z_][a-zA-Z0-9_.]*$/.test(value)) {
const dir = value[0] === "-" ? "desc" : "asc";
return { by: dir === "desc" ? value.slice(1) : value, dir };
return { by: dir === "desc" ? value.slice(1) : value, dir } as any;
} else if (/^{.*}$/.test(value)) {
return JSON.parse(value);
return JSON.parse(value) as any;
}
return sort_default;
return sort_default as any;
}
return value;
return value as any;
})
.Encode(JSON.stringify);
.Encode((value) => value);
const stringArray = Type.Transform(
Type.Union([Type.String(), Type.Array(Type.String())], { default: [] })
@@ -65,25 +63,18 @@ export const whereSchema = Type.Transform(
})
.Encode(JSON.stringify);
export type ShallowRepoQuery = {
limit?: number;
offset?: number;
sort?: string | { by: string; dir: "asc" | "desc" };
select?: string[];
with?: string[] | Record<string, ShallowRepoQuery>;
join?: string[];
where?: any;
};
export type RepoWithSchema = Record<
string,
Omit<ShallowRepoQuery, "with"> & {
Omit<RepoQueryIn, "with"> & {
with?: unknown;
}
>;
export const withSchema = <TSelf extends TThis>(Self: TSelf) =>
Type.Transform(Type.Union([stringArray, Type.Record(Type.String(), Self)]))
.Decode((value) => {
let _value = value;
let _value = typeof value === "string" ? [value] : value;
if (Array.isArray(value)) {
if (!value.every((v) => typeof v === "string")) {
throw new Error("Invalid 'with' schema");
@@ -121,6 +112,14 @@ export const querySchema = Type.Recursive(
{ $id: "query-schema" }
);
export type RepoQueryIn = Static<typeof querySchema>;
export type RepoQueryIn = {
limit?: number;
offset?: number;
sort?: string | { by: string; dir: "asc" | "desc" };
select?: string[];
with?: string[] | Record<string, RepoQueryIn>;
join?: string[];
where?: WhereQuery;
};
export type RepoQuery = Required<StaticDecode<typeof querySchema>>;
export const defaultQuerySchema = Value.Default(querySchema, {}) as RepoQuery;