Files
userbase/app/src/data/relations/RelationField.ts
T
shishantbiswas 282c9f6054
Run Tests / test (pull_request) Successful in 7m24s
fix: on delete
2026-09-27 17:57:45 +05:30

102 lines
3.1 KiB
TypeScript

import type { EntityManager } from "../entities";
import { Field, baseFieldConfigSchema } from "../fields";
import type { EntityRelation } from "./EntityRelation";
import type { EntityRelationAnchor } from "./EntityRelationAnchor";
import type { TFieldTSType } from "data/entities/EntityTypescript";
import { s } from "bknd/utils";
import { DEFAULT_RELATION_CASCADE, RelationCascades, type RelationCascade } from "./relation-types";
export const relationFieldConfigSchema = s.strictObject({
reference: s.string(),
target: s.string(), // @todo: potentially has to be an instance!
target_field: s.string({ default: "id" }).optional(),
target_field_type: s.string({ enum: ["text", "integer"], default: "integer" }).optional(),
on_delete: s.string({ enum: RelationCascades, default: DEFAULT_RELATION_CASCADE }).optional(),
...baseFieldConfigSchema.properties,
});
export type RelationFieldConfig = s.Static<typeof relationFieldConfigSchema>;
export type RelationFieldBaseConfig = {
label?: string;
on_delete?: RelationCascade;
};
export class RelationField extends Field<RelationFieldConfig> {
override readonly type = "relation";
protected getSchema() {
return relationFieldConfigSchema;
}
static create(
relation: EntityRelation,
target: EntityRelationAnchor,
config?: RelationFieldBaseConfig,
) {
const name = [
target.reference ?? target.entity.name,
target.entity.getPrimaryField().name,
].join("_");
return new RelationField(name, {
...config,
required: relation.required,
// the relation owns the referential action, the field only materializes it
on_delete: config?.on_delete ?? relation.config.on_delete,
reference: target.reference,
target: target.entity.name,
target_field: target.entity.getPrimaryField().name,
target_field_type: target.entity.getPrimaryField().fieldType,
});
}
reference() {
return this.config.reference;
}
onDelete(): RelationCascade | undefined {
return this.config.on_delete;
}
target() {
return this.config.target;
}
targetField(): string {
return this.config.target_field!;
}
override schema() {
return Object.freeze({
...super.schema()!,
type: this.config.target_field_type ?? "integer",
references: `${this.config.target}.${this.config.target_field}`,
onDelete: this.config.on_delete ?? DEFAULT_RELATION_CASCADE,
});
}
override transformRetrieve(value: any): any {
return value;
}
override async transformPersist(value: any, em: EntityManager<any>): Promise<any> {
throw new Error("RelationField: This function should not be called");
}
override toJsonSchema() {
return this.toSchemaWrapIfRequired(
s.number({
$ref: `${this.config?.target}#/properties/${this.config?.target_field}`,
}),
);
}
override toType(): TFieldTSType {
const type = this.config.target_field_type === "integer" ? "number" : "string";
return {
...super.toType(),
type,
};
}
}