UNPKG

tspace-mysql

Version:

Tspace MySQL is a promise-based ORM for Node.js, designed with modern TypeScript and providing type safety for schema databases.

677 lines (676 loc) 20.2 kB
import "reflect-metadata"; import { Model } from "./Model"; import { Blueprint } from "./Blueprint"; import type { TRelationOptionsDecorator } from "../types/decorator"; import type { TPattern, TValidateSchemaDecorator } from "../types"; type RelationOptions = TRelationOptionsDecorator; export declare const REFLECT_META: { RELATIONS: { hasOne: string; hasMany: string; belongsTo: string; belongsToMany: string; }; SCHEMA: string; VALIDATE_SCHEMA: string; TABLE: string; UUID: { enabled: string; column: string; }; OBSERVER: string; TIMESTAMP: { enabled: string; columns: string; }; SOFT_DELETE: { enabled: string; columns: string; }; PATTERN: string; HOOKS: string; TRANSFORM: string; BEFORE: { INSERT: string; UPDATE: string; REMOVE: string; }; AFTER: { INSERT: string; UPDATE: string; REMOVE: string; }; }; /** * Decorator to mark a class with a database table name. * * Attaches the given table name to the class using Reflect metadata. * This can be retrieved later to map the class to the corresponding database table. * * @param {string} name - The name of the database table. * @returns {ClassDecorator} A class decorator that sets the table name metadata. * * @example * ```ts * @Table('users') * class User extends Model {} * ``` */ export declare const Table: (name: string) => ClassDecorator; /** * Decorator to automatically generate a singular table name from a class name. * * Converts the class name from PascalCase to snake_case, then converts it to singular form. * The resulting table name is stored as metadata on the class. * * @returns {ClassDecorator} A class decorator that sets the singular table name metadata. * * @example * ```ts * @TableSingular() * class Users extends Model {} * ``` */ export declare const TableSingular: () => ClassDecorator; /** * Decorator to automatically generate a plural table name from a class name. * * Converts the class name from PascalCase to snake_case, then converts it to plural form. * The resulting table name is stored as metadata on the class. * * @returns {ClassDecorator} A class decorator that sets the plural table name metadata. * * @example * ```ts * @TablePlural() * class User extends Model {} * * ``` */ export declare const TablePlural: () => ClassDecorator; /** * Decorator to enable automatic UUID generation for a model. * * Stores metadata indicating UUID usage and optional column name. * * @param {string} [column] - Optional column name to store the UUID. * @returns {ClassDecorator} A class decorator that enables UUID metadata. * * @example * ```ts * @UUID('id') * class User extends Model {} * ``` */ export declare const UUID: (column?: string) => ClassDecorator; /** * Decorator to enable automatic timestamps on a model. * * Stores metadata indicating that `createdAt` and `updatedAt` columns should be handled. * * @param {{ createdAt: string; updatedAt: string }} [columns] - Optional custom column names for timestamps. * @returns {ClassDecorator} A class decorator that enables timestamp metadata. * * @example * ```ts * @Timestamp({ createdAt: 'created_at', updatedAt: 'updated_at' }) * class User extends Model {} * ``` */ export declare const Timestamp: (columns?: { createdAt: string; updatedAt: string; }) => ClassDecorator; /** * Decorator to enable soft deletion on a model. * * Stores metadata indicating soft delete usage and optional column name. * * @param {string} [column] - Optional column name to track soft deletion. * @returns {ClassDecorator} A class decorator that enables soft delete metadata. * * @example * ```ts * @SoftDelete('deleted_at') * class User extends Model {} * ``` */ export declare const SoftDelete: (column?: string) => ClassDecorator; /** * Decorator to set the naming pattern for a model. * * Can be `camelCase` or `snake_case`. * * @param {"camelCase" | "snake_case"} pattern - The naming convention to use. * @returns {ClassDecorator} A class decorator that sets the naming pattern metadata. * * @example * ```ts * @Pattern('snake_case') * class User extends Model {} * ``` */ export declare const Pattern: (pattern: TPattern) => ClassDecorator; /** * Decorator to set the model naming pattern to camelCase. * * @returns {ClassDecorator} A class decorator that sets camelCase naming metadata. * * @example * ```ts * @CamelCase() * class User extends Model {} * ``` */ export declare const CamelCase: () => ClassDecorator; /** * Decorator to set the model naming pattern to snake_case. * * @returns {ClassDecorator} A class decorator that sets snake_case naming metadata. * * @example * ```ts * @SnakeCase() * class User extends Model {} * ``` */ export declare const SnakeCase: () => ClassDecorator; /** * Decorator to define a database column for a model property. * * Accepts a `Blueprint` function that defines the column type, constraints, and other attributes. * The resulting column schema is stored as metadata on the target class. * * @param {() => Blueprint} blueprint - A function returning a `Blueprint` instance describing the column. * @returns {Function} A property decorator that registers the column schema. * * @throws {Error} If the property name cannot be determined. * * @example * ```ts * class User extends Model { * * @Column(() => Blueprint.int().notNull().primary().autoIncrement()) * public id!: number; * * @Column(() => Blueprint.varchar(50).null()) * public uuid!: string; * } * * ``` */ export declare const Column: (blueprint: () => Blueprint) => Function; /** * A decorator factory that registers custom `to` and `from` transform functions * for a property. Useful for serialization/deserialization logic (e.g. ORM, DTO). * * @param {Object} options - Transform options. * @param {(value: unknown) => any | Promise<any>} options.to - Function executed when transforming *to* app -> database. * @param {(value: unknown) => any | Promise<any>} options.from - Function executed when transforming *from* database -> app. * @returns {Function} A property decorator that stores transform metadata. * * @throws {Error} If the property name cannot be determined. * * @example * ```ts * class User { * @Transform({ * to: (v) => JSON.stringify(v), * from: (v) => JSON.parse(v), * }) * profile; * } * ``` */ export declare const Transform: ({ to, from }: { to: (value: unknown) => any | Promise<any>; from: (value: unknown) => any | Promise<any>; }) => Function; /** * Decorator to attach validation rules to a model property. * * Accepts a `TValidateSchemaDecorator` object describing the validation rules * (e.g., type, required, length, regex match, uniqueness, or custom validation function). * The validation schema is stored as metadata on the target class. * * @param {TValidateSchemaDecorator} validate - An object defining validation rules for the property. * @returns {Function} A decorator that registers the validation schema. * * @example * ```ts * class User extends Model { * * @Column(() => Blueprint.int().notNull().primary().autoIncrement()) * public id!: number; * * @Column(() => Blueprint.varchar(50).null()) * public uuid!: string; * * @Column(() => Blueprint.varchar(50).null()) * @Validate({ * type: String, * require: true, * length: 50, * match: /^[a-zA-Z0-9._]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/, * unique: true, * fn: async (email: string) => { * const exists = await new User().where('email',email).exists(); * if(exists) return `This column "${email}" is dupicate`; * return null; * } * }) * public email!: string; * } * * ``` */ export declare const Validate: (validate: TValidateSchemaDecorator) => Function; /** * Decorator to define a HasOne relationship on a model property. * * @param {RelationOptions} options - Options describing the relation. * @returns {Function} A decorator that registers the HasOne relationship. * * @example * ```ts * class Profile extends Model {} * * class User extends Model { * @HasOne({ model: Profile }) * public profile!: Profile; * } * * ``` */ export declare const HasOne: (fn: (() => new () => Model) | RelationOptions) => Function; /** * Decorator to define a HasMany relationship on a model property. * * @param {RelationOptions} options - Options describing the relation. * @returns {Function} A decorator that registers the HasMany relationship. * * @example * ```ts * class Post extends Model {} * * class User extends Model { * @HasMany({ model: Post }) * public posts!: Post[]; * } * * ``` */ export declare const HasMany: (fn: (() => new () => Model) | RelationOptions) => Function; /** * Decorator to define a BelongsTo relationship on a model property. * * @param {RelationOptions} options - Options describing the relation. * @returns {Function} A decorator that registers the BelongsTo relationship. * * @example * ```ts * class User extends Model {} * * class Post extends Model { * @BelongsTo({ model: User }) * public author!: User; * } * * ``` */ export declare const BelongsTo: (fn: (() => new () => Model) | RelationOptions) => Function; /** * Decorator to define a BelongsToMany (many-to-many) relationship on a model property. * * @param {RelationOptions} options - Options describing the relation. * @returns {Function} A decorator that registers the BelongsToMany relationship. * * @example * ```ts * class Role extends Model {} * * class User extends Model { * @BelongsToMany({ model: Role, pivotTable: 'user_roles' }) * public roles!: Role[]; * } * * ``` */ export declare const BelongsToMany: (fn: (() => new () => Model) | RelationOptions) => Function; /** * Decorator to attach an observer class to a model. * * The observer class should have `selected`, `created`, `updated`, and `deleted` methods. * * @param {new () => { selected: Function; created: Function; updated: Function; deleted: Function }} observer - Observer class constructor. * @returns {ClassDecorator} A class decorator that sets the model observer. * * @example * ```ts * class UserObserver { * selected() {} * created() {} * updated() {} * deleted() {} * } * * @Observer(UserObserver) * class User extends Model {} * ``` */ export declare const Observer: (observer: new () => { selected: Function; created: Function; updated: Function; deleted: Function; }) => ClassDecorator; /** * Decorator that registers a method as a generic lifecycle hook. * Unlike specific hooks such as `@BeforeInsert` or `@AfterUpdate`, * this decorator is **multi-purpose** and collects all tagged methods * into a single metadata registry (`REFLECT_META.HOOKS`). * * These hook methods can later be invoked by the ORM/engine at any stage * depending on your custom logic. * * @returns {Function} A method decorator. * * @throws {Error} If applied to a non-method class member. * * @example * ```ts * class User { * @Hooks() * logAction() { * console.log("A lifecycle action happened"); * } * } * ``` * * @example * // Later, your ORM engine could do: * const hooks = Reflect.getMetadata(REFLECT_META.HOOKS, userInstance) || []; * for (const hook of hooks) hook.call(userInstance); */ export declare const Hooks: () => Function; /** * Decorator that registers a method to be executed **before an insert operation**. * Works similarly to TypeORM's `@BeforeInsert`. * * The decorated method will be stored in metadata and executed later by the ORM engine. * * @returns {Function} A method decorator. * * @throws {Error} If applied to a non-function member. * * @example * ```ts * class User { * @BeforeInsert() * setCreatedAt() { * this.createdAt = new Date(); * } * } * ``` */ export declare const BeforeInsert: () => Function; /** * Decorator that registers a method to be executed **before an update operation**. * * @returns {Function} A method decorator. * * @throws {Error} If applied to a non-function member. * * @example * ```ts * class User { * @BeforeUpdate() * updateTimestamp() { * this.updatedAt = new Date(); * } * } * ``` */ export declare const BeforeUpdate: () => Function; /** * Decorator that registers a method to be executed **before a remove/delete operation**. * * @returns {Function} A method decorator. * * @throws {Error} If applied to a non-function member. * * @example * ```ts * class User { * @BeforeRemove() * handleBeforeDelete() { * console.log("User will be deleted"); * } * } * ``` */ export declare const BeforeRemove: () => Function; /** * Decorator that registers a method to be executed **after an insert operation**. * * @returns {Function} A method decorator. * * @throws {Error} If applied to a non-function member. * * @example * ```ts * class User { * @AfterInsert() * notifyCreated() { * console.log("User inserted"); * } * } * ``` */ export declare const AfterInsert: () => Function; /** * Decorator that registers a method to be executed **after an update operation**. * * @returns {Function} A method decorator. * * @throws {Error} If applied to a non-function member. * * @example * ```ts * class User { * @AfterUpdate() * logUpdate() { * console.log("User updated"); * } * } * ``` */ export declare const AfterUpdate: () => Function; /** * Decorator that registers a method to be executed **after a remove/delete operation**. * * @returns {Function} A method decorator. * * @throws {Error} If applied to a non-function member. * * @example * ```ts * class User { * @AfterRemove() * logDeletion() { * console.log("User removed"); * } * } * ``` */ export declare const AfterRemove: () => Function; /** * Collection of decorators used for defining * database models, columns, relations, hooks, and validation. * * @namespace D */ export declare const D: { Table: (name: string) => ClassDecorator; TableSingular: () => ClassDecorator; TablePlural: () => ClassDecorator; UUID: (column?: string) => ClassDecorator; /** * Decorator to enable automatic timestamps on a model. * * Stores metadata indicating that `createdAt` and `updatedAt` columns should be handled. * * @param {{ createdAt: string; updatedAt: string }} [columns] - Optional custom column names for timestamps. * @returns {ClassDecorator} A class decorator that enables timestamp metadata. * * @example * ```ts * @Timestamp({ createdAt: 'created_at', updatedAt: 'updated_at' }) * class User extends Model {} * ``` */ SoftDelete: (column?: string) => ClassDecorator; Timestamp: (columns?: { createdAt: string; updatedAt: string; }) => ClassDecorator; Pattern: (pattern: TPattern) => ClassDecorator; CamelCase: () => ClassDecorator; SnakeCase: () => ClassDecorator; /** * Decorator to define a database column for a model property. * * Accepts a `Blueprint` function that defines the column type, constraints, and other attributes. * The resulting column schema is stored as metadata on the target class. * * @param {() => Blueprint} blueprint - A function returning a `Blueprint` instance describing the column. * @returns {Function} A property decorator that registers the column schema. * * @throws {Error} If the property name cannot be determined. * * @example * ```ts * class User extends Model { * * @Column(() => Blueprint.int().notNull().primary().autoIncrement()) * public id!: number; * * @Column(() => Blueprint.varchar(50).null()) * public uuid!: string; * } * * ``` */ Column: (blueprint: () => Blueprint) => Function; /** * Decorator to attach validation rules to a model property. * * Accepts a `TValidateSchemaDecorator` object describing the validation rules * (e.g., type, required, length, regex match, uniqueness, or custom validation function). * The validation schema is stored as metadata on the target class. * * @param {TValidateSchemaDecorator} validate - An object defining validation rules for the property. * @returns {Function} A decorator that registers the validation schema. * * @example * ```ts * class User extends Model { * * @Column(() => Blueprint.int().notNull().primary().autoIncrement()) * public id!: number; * * @Column(() => Blueprint.varchar(50).null()) * public uuid!: string; * * @Column(() => Blueprint.varchar(50).null()) * @Validate({ * type: String, * require: true, * length: 50, * match: /^[a-zA-Z0-9._]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/, * unique: true, * fn: async (email: string) => { * const exists = await new User().where('email',email).exists(); * if(exists) return `This column "${email}" is dupicate`; * return null; * } * }) * public email!: string; * } * * ``` */ Validate: (validate: TValidateSchemaDecorator) => Function; HasOne: (fn: (() => new () => Model) | RelationOptions) => Function; HasMany: (fn: (() => new () => Model) | RelationOptions) => Function; BelongsTo: (fn: (() => new () => Model) | RelationOptions) => Function; BelongsToMany: (fn: (() => new () => Model) | RelationOptions) => Function; /** * A decorator factory that registers custom `to` and `from` transform functions * for a property. Useful for serialization/deserialization logic (e.g. ORM, DTO). * * @param {Object} options - Transform options. * @param {(value: unknown) => any | Promise<any>} options.to - Function executed when transforming *to* app -> database. * @param {(value: unknown) => any | Promise<any>} options.from - Function executed when transforming *from* database -> app. * @returns {Function} A property decorator that stores transform metadata. * * @throws {Error} If the property name cannot be determined. * * @example * ```ts * class User { * @Transform({ * to: (v) => JSON.stringify(v), * from: (v) => JSON.parse(v), * }) * profile; * } * ``` */ Transform: ({ to, from }: { to: (value: unknown) => any | Promise<any>; from: (value: unknown) => any | Promise<any>; }) => Function; /** * Decorator that registers a method as a generic lifecycle hook. * Unlike specific hooks such as `@BeforeInsert` or `@AfterUpdate`, * this decorator is **multi-purpose** and collects all tagged methods * into a single metadata registry (`REFLECT_META.HOOKS`). * * These hook methods can later be invoked by the ORM/engine at any stage * depending on your custom logic. * * @returns {Function} A method decorator. * * @throws {Error} If applied to a non-method class member. * * @example * ```ts * class User { * @Hooks() * logAction() { * console.log("A lifecycle action happened"); * } * } * ``` * * @example * // Later, your ORM engine could do: * const hooks = Reflect.getMetadata(REFLECT_META.HOOKS, userInstance) || []; * for (const hook of hooks) hook.call(userInstance); */ Hooks: () => Function; Observer: (observer: new () => { selected: Function; created: Function; updated: Function; deleted: Function; }) => ClassDecorator; BeforeInsert: () => Function; BeforeUpdate: () => Function; BeforeRemove: () => Function; AfterInsert: () => Function; AfterUpdate: () => Function; AfterRemove: () => Function; }; export {};