UNPKG

@kenniy/godeye-data-contracts

Version:

Enterprise-grade base repository architecture for GOD-EYE microservices with zero overhead and maximum code reuse

409 lines (408 loc) 14.1 kB
/** * Repository Types - Enterprise-Grade Type Safety * * Comprehensive type definitions for the base repository architecture * Supports both TypeORM (PostgreSQL) and Mongoose (MongoDB) patterns */ import { IPaginatedResult, IBulkOperation, IBulkResult } from "./response.types"; /** * Supported ORM types in GOD-EYE ecosystem */ export declare enum ORMType { TYPEORM = "typeorm", MONGOOSE = "mongoose" } /** * Database sort directions * Unified across both ORMs */ export declare enum SortDirection { ASC = "ASC", DESC = "DESC", ASCENDING = 1, DESCENDING = -1 } /** * Search strategies for intelligent field searching * Backend repositories use these to determine how to match search terms */ export declare enum SearchStrategy { EXACT = "exact",// kenniy = kenniy (perfect match) FUZZY = "fuzzy",// kenniy ≈ Kenny, Kennedy (typo tolerance) CONTAINS = "contains",// kenniy in "kenniy@email.com" (substring match) STARTS_WITH = "startsWith",// kenniy in "kenniy123" (prefix match) ENDS_WITH = "endsWith",// kenniy in "mikekenniy" (suffix match) SOUNDEX = "soundex",// kenniy sounds like Kenny (phonetic match) SKIP = "skip" } /** * Backend WHERE configuration for repository methods * Separates backend control from frontend requests */ export interface IWhereConfig { /** Backend-controlled WHERE conditions (always applied) */ conditions?: any; /** Backend-defined search field configurations */ searchConfig?: ISearchFieldConfig[]; /** Dynamic conditions based on search context */ dynamicConditions?: (criteria: ICriteria<any>) => any; } /** * Search field configuration for intelligent searching * Repositories use this to configure how each field should be searched */ export interface ISearchFieldConfig { /** Single field name to search in */ field?: string; /** Multiple fields with same configuration */ fields?: string[]; /** Flag for database array fields */ isArray?: boolean; /** Available search strategies for this field/fields */ strategies: SearchStrategy[]; /** Default strategy to use for this field/fields */ defaultStrategy: SearchStrategy; /** Priority/relevance weight (higher = more important) */ priority: number; /** Weight multiplier for relevance scoring (optional) */ weight?: number; } /** * Enhanced search criteria with intelligent strategy selection */ export interface ISearchCriteria { /** Search term from frontend */ term: string; /** Backend-determined field configurations (not from frontend) */ fieldConfigs?: ISearchFieldConfig[]; /** Backend-determined global strategy override */ globalStrategy?: SearchStrategy; } /** * Query operation types for monitoring and logging */ export declare enum QueryOperation { FIND_ONE = "findOne", FIND = "find", FIND_WITH_PAGINATION = "findWithPagination", CREATE = "create", CREATE_MANY = "createMany", UPDATE_BY_ID = "updateById", UPDATE_MANY = "updateMany", DELETE_BY_ID = "deleteById", DELETE_MANY = "deleteMany", COUNT = "count", AGGREGATE = "aggregate", TEXT_SEARCH = "textSearch", RAW_QUERY = "rawQuery", TRANSACTION = "transaction" } /** * Repository error classification * Enterprise standard error categorization */ export declare enum RepositoryErrorType { VALIDATION_ERROR = "VALIDATION_ERROR", DUPLICATE_ERROR = "DUPLICATE_ERROR", NOT_FOUND_ERROR = "NOT_FOUND_ERROR", CONNECTION_ERROR = "CONNECTION_ERROR", TIMEOUT_ERROR = "TIMEOUT_ERROR", TRANSACTION_ERROR = "TRANSACTION_ERROR", PERMISSION_ERROR = "PERMISSION_ERROR", QUERY_ERROR = "QUERY_ERROR", NETWORK_ERROR = "NETWORK_ERROR", RESOURCE_EXHAUSTED = "RESOURCE_EXHAUSTED" } /** * Entity status constants * Common across all GOD-EYE entities */ export declare enum EntityStatus { ACTIVE = "active", INACTIVE = "inactive", DELETED = "deleted", PENDING = "pending", ARCHIVED = "archived" } /** * Verification status for GOD-EYE business entities */ export declare enum VerificationStatus { PENDING = "pending", VERIFIED = "verified", REJECTED = "rejected", UNDER_REVIEW = "under_review", SUSPENDED = "suspended" } /** * Default pagination settings * Enterprise-recommended defaults for enterprise applications */ export declare const PAGINATION_CONSTANTS: { readonly DEFAULT_PAGE: 1; readonly DEFAULT_LIMIT: 20; readonly MAX_LIMIT: 1000; readonly MIN_LIMIT: 1; }; /** * Performance monitoring thresholds (milliseconds) * Enterprise-grade performance standards */ export declare const PERFORMANCE_THRESHOLDS: { readonly FAST_QUERY: 10; readonly ACCEPTABLE_QUERY: 50; readonly SLOW_QUERY: 100; readonly CRITICAL_QUERY: 500; readonly TIMEOUT_QUERY: 30000; }; /** * Default repository configuration * Production-ready defaults for GOD-EYE services */ export declare const DEFAULT_REPOSITORY_CONFIG: { readonly DEFAULT_LIMIT: 20; readonly MAX_LIMIT: 1000; readonly ENABLE_QUERY_LOGGING: true; readonly SLOW_QUERY_THRESHOLD: 100; readonly ENABLE_PERFORMANCE_MONITORING: true; readonly ENABLE_CACHING: false; readonly CACHE_TIMEOUT: 300; readonly CONNECTION_TIMEOUT: 30000; readonly MAX_RETRY_ATTEMPTS: 3; readonly RETRY_DELAY: 1000; }; /** * GOD-EYE specific entity field names * Standardized field naming across all services */ export declare const ENTITY_FIELDS: { readonly ID: "id"; readonly CREATED_AT: "createdAt"; readonly UPDATED_AT: "updatedAt"; readonly DELETED_AT: "deletedAt"; readonly CREATED_BY: "createdBy"; readonly UPDATED_BY: "updatedBy"; readonly STATUS: "status"; readonly VERIFICATION_STATUS: "verificationStatus"; readonly USER_ID: "userId"; readonly EMAIL: "email"; readonly PHONE: "phone"; }; /** * ORM-agnostic query criteria interface * The 'include' field auto-converts to 'relations' for TypeORM or 'populate' for Mongoose */ export interface ICriteria<T> { /** Query conditions - works like SQL WHERE for both ORMs */ where?: Partial<T> | Record<string, any>; /** Load related data - auto-converts to relations/populate internally */ include?: string[] | string; /** Relations to load (TypeORM) - alias for include */ relations?: string[]; /** Fields to select/project */ select?: string[]; /** Sort order */ sort?: Record<string, "ASC" | "DESC" | 1 | -1>; /** Maximum number of results */ limit?: number; /** Number of results to skip */ offset?: number; /** Page number (1-based) for pagination */ page?: number; /** Intelligent search configuration */ search?: ISearchCriteria; } /** * Unified repository interface with whereConfig pattern for intelligent search * Matches the complete-max-usage.md example exactly */ export interface IRepository<T> { find<R = T>(whereConfig: IWhereConfig, queryDto: any): Promise<R[]>; findOne<R = T>(whereConfig: IWhereConfig, queryDto: any): Promise<R | null>; findById<R = T>(id: string | number, whereConfig: IWhereConfig, queryDto?: any): Promise<R | null>; findWithPagination<R = T>(whereConfig: IWhereConfig, queryDto: any): Promise<IPaginatedResult<R>>; create(data: Partial<T>): Promise<T>; createMany(data: Partial<T>[]): Promise<T[]>; updateById<R = T>(id: string | number, data: Partial<T>): Promise<R | null>; updateMany(criteria: ICriteria<T>, data: Partial<T>): Promise<{ modifiedCount: number; }>; deleteById(id: string | number): Promise<boolean>; deleteMany(criteria: ICriteria<T>): Promise<{ deletedCount: number; }>; count(criteria: ICriteria<T>): Promise<number>; exists(criteria: ICriteria<T>): Promise<boolean>; bulkOperations<R = T>(operations: IBulkOperation<T>[]): Promise<IBulkResult<R>>; findOneAndUpdate<R = T>(criteria: ICriteria<T>, data: Partial<T>, options?: { populate?: string[]; }): Promise<R | null>; existsByFilters(criteria: ICriteria<T>): Promise<boolean>; aggregate<R = any>(pipeline: any[]): Promise<R[]>; aggregateCount(pipeline: any[]): Promise<number>; aggregateWithPagination<R = any>(pipeline: any[], options: { page: number; limit: number; }): Promise<IPaginatedResult<R>>; aggregationBuilder(): IAggregationBuilder<T>; aggregateGroup<R = any>(options: { groupBy: Record<string, any>; operations?: { count?: boolean; sum?: string[]; avg?: string[]; min?: string[]; max?: string[]; }; match?: Partial<T>; sort?: Record<string, 1 | -1>; limit?: number; }): Promise<R[]>; aggregateLookup<R = any>(options: { from: string; localField: string; foreignField: string; as: string; pipeline?: any[]; match?: Partial<T>; sort?: Record<string, 1 | -1>; limit?: number; }): Promise<R[]>; aggregateTimeSeries<R = any>(options: { dateField: string; granularity: "hour" | "day" | "week" | "month" | "year"; timezone?: string; match?: Partial<T>; startDate?: Date; endDate?: Date; operations?: { count?: boolean; sum?: string[]; avg?: string[]; }; }): Promise<R[]>; distinct<R = any>(field: string, filters?: Partial<T>): Promise<R[]>; withTransaction<R = any>(callback: (transaction: ITransaction) => Promise<R>): Promise<R>; beginTransaction(): Promise<ITransaction>; } /** * Repository configuration for ORM detection and setup */ export interface IRepositoryConfig { /** ORM type - auto-detected from connection */ orm_type?: "typeorm" | "mongoose"; /** Default pagination limit */ default_limit?: number; /** Maximum pagination limit */ max_limit?: number; /** Enable soft deletes */ soft_delete?: boolean; /** Default sort field */ default_sort?: string; /** Auto-populate fields (always include these relations) */ auto_populate?: string[]; } /** * Search configuration for text search operations */ export interface ISearchConfig { /** Fields to search in */ fields: string[]; /** Search term */ term: string; /** Search mode */ mode?: "contains" | "startsWith" | "endsWith" | "exact"; /** Case sensitive search */ case_sensitive?: boolean; } /** * Aggregation Builder Interface (EMRO-inspired fluent API) * Fluent interface for building aggregation pipelines across both ORMs */ export interface IAggregationBuilder<T = any> { match(filters: Record<string, any>): IAggregationBuilder<T>; group(groupBy: Record<string, any>): IAggregationBuilder<T>; sort(sort: Record<string, 1 | -1>): IAggregationBuilder<T>; limit(limit: number): IAggregationBuilder<T>; skip(skip: number): IAggregationBuilder<T>; project(fields: Record<string, any>): IAggregationBuilder<T>; lookup(options: { from: string; localField: string; foreignField: string; as: string; pipeline?: any[]; }): IAggregationBuilder<T>; unwind(path: string, options?: { preserveNullAndEmptyArrays?: boolean; includeArrayIndex?: string; }): IAggregationBuilder<T>; addFields(fields: Record<string, any>): IAggregationBuilder<T>; facet(facets: Record<string, any[]>): IAggregationBuilder<T>; exec<R = any>(): Promise<R[]>; count(): Promise<number>; paginate<R = any>(page: number, limit: number): Promise<IPaginatedResult<R>>; getPipeline(): any[]; } /** * Transaction Interface (ORM-agnostic) * Unified transaction management for both TypeORM and Mongoose */ export interface ITransaction { /** Check if transaction is active */ isActive(): boolean; /** Commit the transaction */ commit(): Promise<void>; /** Rollback the transaction */ rollback(): Promise<void>; /** Get the underlying transaction object (ORM-specific) */ getTransaction(): any; /** Create repository instance bound to this transaction */ getRepository<T>(entity: any): ITransactionRepository<T>; } /** * Transaction-bound Repository Interface * Repository operations within a transaction context */ export interface ITransactionRepository<T> { find<R = T>(criteria: ICriteria<T>): Promise<R[]>; findOne<R = T>(criteria: ICriteria<T>): Promise<R | null>; create(data: Partial<T>): Promise<T>; update(criteria: ICriteria<T>, data: Partial<T>): Promise<T>; delete(criteria: ICriteria<T>): Promise<boolean>; count(criteria: ICriteria<T>): Promise<number>; createMany(data: Partial<T>[]): Promise<T[]>; updateMany(criteria: ICriteria<T>, data: Partial<T>): Promise<{ modifiedCount: number; }>; deleteMany(criteria: ICriteria<T>): Promise<{ deletedCount: number; }>; findWithPagination<R = T>(criteria: ICriteria<T>): Promise<IPaginatedResult<R>>; bulkOperations<R = T>(operations: IBulkOperation<T>[]): Promise<IBulkResult<R>>; aggregate<R = any>(pipeline: any[]): Promise<R[]>; aggregateCount(pipeline: any[]): Promise<number>; distinct<R = any>(field: string, filters?: Partial<T>): Promise<R[]>; } /** * Transaction Options */ export interface ITransactionOptions { /** Transaction isolation level (database-specific) */ isolation?: "READ_UNCOMMITTED" | "READ_COMMITTED" | "REPEATABLE_READ" | "SERIALIZABLE"; /** Transaction timeout in milliseconds */ timeout?: number; /** Auto-retry failed transactions */ retry?: { attempts: number; delay: number; }; /** Read preference for MongoDB (Mongoose only) */ readPreference?: "primary" | "secondary" | "primaryPreferred" | "secondaryPreferred" | "nearest"; /** Write concern for MongoDB (Mongoose only) */ writeConcern?: { w?: number | string; j?: boolean; wtimeout?: number; }; }