mirror of
https://github.com/shishantbiswas/bknd.git
synced 2026-03-17 04:46:05 +00:00
feat: adding initial uuid support
This commit is contained in:
@@ -1,13 +1,17 @@
|
||||
import { config } from "core";
|
||||
import type { Static } from "core/utils";
|
||||
import { StringEnum, uuidv7, type Static } from "core/utils";
|
||||
import { Field, baseFieldConfigSchema } from "./Field";
|
||||
import * as tbbox from "@sinclair/typebox";
|
||||
import type { TFieldTSType } from "data/entities/EntityTypescript";
|
||||
const { Type } = tbbox;
|
||||
|
||||
export const primaryFieldTypes = ["integer", "uuid"] as const;
|
||||
export type TPrimaryFieldFormat = (typeof primaryFieldTypes)[number];
|
||||
|
||||
export const primaryFieldConfigSchema = Type.Composite([
|
||||
Type.Omit(baseFieldConfigSchema, ["required"]),
|
||||
Type.Object({
|
||||
format: Type.Optional(StringEnum(primaryFieldTypes, { default: "integer" })),
|
||||
required: Type.Optional(Type.Literal(false)),
|
||||
}),
|
||||
]);
|
||||
@@ -21,8 +25,8 @@ export class PrimaryField<Required extends true | false = false> extends Field<
|
||||
> {
|
||||
override readonly type = "primary";
|
||||
|
||||
constructor(name: string = config.data.default_primary_field) {
|
||||
super(name, { fillable: false, required: false });
|
||||
constructor(name: string = config.data.default_primary_field, cfg?: PrimaryFieldConfig) {
|
||||
super(name, { fillable: false, required: false, ...cfg });
|
||||
}
|
||||
|
||||
override isRequired(): boolean {
|
||||
@@ -30,18 +34,34 @@ export class PrimaryField<Required extends true | false = false> extends Field<
|
||||
}
|
||||
|
||||
protected getSchema() {
|
||||
return baseFieldConfigSchema;
|
||||
return primaryFieldConfigSchema;
|
||||
}
|
||||
|
||||
get format() {
|
||||
return this.config.format ?? "integer";
|
||||
}
|
||||
|
||||
get fieldType() {
|
||||
return this.format === "integer" ? "integer" : "text";
|
||||
}
|
||||
|
||||
override schema() {
|
||||
return Object.freeze({
|
||||
type: "integer",
|
||||
type: this.fieldType,
|
||||
name: this.name,
|
||||
primary: true,
|
||||
nullable: false,
|
||||
});
|
||||
}
|
||||
|
||||
getNewValue(): any {
|
||||
if (this.format === "uuid") {
|
||||
return uuidv7();
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
override async transformPersist(value: any): Promise<number> {
|
||||
throw new Error("PrimaryField: This function should not be called");
|
||||
}
|
||||
@@ -51,11 +71,12 @@ export class PrimaryField<Required extends true | false = false> extends Field<
|
||||
}
|
||||
|
||||
override toType(): TFieldTSType {
|
||||
const type = this.format === "integer" ? "number" : "string";
|
||||
return {
|
||||
...super.toType(),
|
||||
required: true,
|
||||
import: [{ package: "kysely", name: "Generated" }],
|
||||
type: "Generated<number>",
|
||||
type: `Generated<${type}>`,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user