All files / src/persistence Adapter.ts

87.83% Statements 130/148
56.52% Branches 26/46
97.29% Functions 36/37
87.14% Lines 122/140

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 4939x                           9x                     9x 9x       9x 9x 9x   9x   9x 273x 273x           227x                                     9x                 9x                 1386x 1386x       1312x       30x           7x       8x 8x 8x   8x       8x 8x     8x 8x 8x             1x       1x       1096x                               202x               8x     9x                   202x         202x                         191x 191x 191x 191x   1100x 1096x 1096x   1096x 1096x       191x                       191x                           949x 949x 949x   949x   949x 949x 949x 5585x 4636x 4636x     949x                         949x                       949x                               4x   4x 4x 4x 4x 116x                             3x 3x 3x 3x                               1x   1x 1x 1x 1x 1x                             1x 1x 1x 1x                   9x 6x 1x       6x 6x     6x 1x 1x 1x                     9x 6x       6x 6x                     3x       3x 3x     3x                             3x       12x       273x             276x 227x     49x           12x         1x 1x   1x       6510x       3x 3x   3x   3x   10x       10x 5x 5x       5x 2x   2x       2x     10x 3x            
import {
  BaseError,
  DBKeys,
  InternalError,
  NotFoundError,
  Context,
  OperationKeys,
  RepositoryFlags,
  DefaultRepositoryFlags,
  Contextual,
  BulkCrudOperationKeys,
  modelToTransient,
} from "@decaf-ts/db-decorators";
import { type Observer } from "../interfaces/Observer";
import {
  type Constructor,
  Decoration,
  DefaultFlavour,
  Model,
  ModelConstructor,
  ModelRegistry,
} from "@decaf-ts/decorator-validation";
import { SequenceOptions } from "../interfaces/SequenceOptions";
import { RawExecutor } from "../interfaces/RawExecutor";
import { Observable } from "../interfaces/Observable";
import { PersistenceKeys } from "./constants";
import { Repository } from "../repository/Repository";
import { Sequence } from "./Sequence";
import { ErrorParser } from "../interfaces";
import { Statement } from "../query/Statement";
import { Logger, Logging } from "@decaf-ts/logging";
import { final } from "../utils";
import { Dispatch } from "./Dispatch";
import { type EventIds, type ObserverFilter } from "./types";
import { ObserverHandler } from "./ObserverHandler";
 
Decoration.setFlavourResolver((obj: object) => {
  try {
    return (
      Adapter.flavourOf(Model.isModel(obj) ? obj.constructor : (obj as any)) ||
      DefaultFlavour
    );
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
  } catch (e: unknown) {
    return DefaultFlavour;
  }
});
 
/**
 * @summary Abstract Decaf-ts Persistence Adapter Class
 * @description Offers the base implementation for all Adapter Classes
 * and manages them various registered {@link Adapter}s
 *
 * @typedef Y the underlying persistence object type or the required config to set it up
 * @typedef Q The query object the adapter uses
 *
 * @param {Y} native the underlying persistence object
 * @param {string} flavour the under witch the persistence adapter should be stored
 *
 * @class Adapter
 * @implements RawExecutor
 * @implements Observable
 */
export abstract class Adapter<
    Y,
    Q,
    F extends RepositoryFlags,
    C extends Context<F>,
  >
  implements RawExecutor<Q>, Contextual<F, C>, Observable, Observer, ErrorParser
{
  private static _current: Adapter<any, any, any, any>;
  private static _cache: Record<string, Adapter<any, any, any, any>> = {};
 
  private logger!: Logger;
 
  protected dispatch?: Dispatch<Y>;
 
  protected readonly observerHandler?: ObserverHandler;
 
  protected get log() {
    if (!this.logger) this.logger = Logging.for(this as any);
    return this.logger;
  }
 
  get native() {
    return this._native;
  }
 
  get alias() {
    return this._alias || this.flavour;
  }
 
  repository<M extends Model>(): Constructor<
    Repository<M, Q, Adapter<Y, Q, F, C>, F, C>
  > {
    return Repository;
  }
 
  protected constructor(
    private readonly _native: Y,
    readonly flavour: string,
    private readonly _alias?: string
  ) {
    Iif (this.flavour in Adapter._cache)
      throw new InternalError(
        `${this.alias} persistence adapter ${this._alias ? `(${this.flavour}) ` : ""} already registered`
      );
    Adapter._cache[this.alias] = this;
    this.log.info(
      `Created ${this.alias} persistence adapter ${this._alias ? `(${this.flavour}) ` : ""} persistence adapter`
    );
    if (!Adapter._current) {
      this.log.verbose(`Defined ${this.alias} persistence adapter as current`);
      Adapter._current = this;
    }
  }
 
  abstract Statement<M extends Model>(): Statement<Q, M, any>;
 
  protected Dispatch(): Dispatch<Y> {
    return new Dispatch();
  }
 
  protected ObserverHandler() {
    return new ObserverHandler();
  }
 
  protected isReserved(attr: string) {
    return !attr;
  }
 
  abstract parseError(err: Error): BaseError;
 
  abstract initialize(...args: any[]): Promise<void>;
 
  abstract Sequence(options: SequenceOptions): Promise<Sequence>;
 
  protected flags<M extends Model>(
    operation: OperationKeys,
    model: Constructor<M>,
    flags: Partial<F>,
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    ...args: any[]
  ): F {
    return Object.assign({}, DefaultRepositoryFlags, flags, {
      affectedTables: Repository.table(model),
      writeOperation: operation !== OperationKeys.READ,
      timestamp: new Date(),
      operation: operation,
    }) as F;
  }
 
  protected Context: Constructor<C> = Context<F> as any;
 
  @final()
  async context<M extends Model>(
    operation:
      | OperationKeys.CREATE
      | OperationKeys.READ
      | OperationKeys.UPDATE
      | OperationKeys.DELETE,
    overrides: Partial<F>,
    model: Constructor<M>,
    ...args: any[]
  ): Promise<C> {
    this.log
      .for(this.context)
      .debug(
        `Creating new context for ${operation} operation on ${model.name} model with flags: ${JSON.stringify(overrides)}`
      );
    return new this.Context(
      this.flags(operation, model, overrides, ...args)
    ) as unknown as C;
  }
 
  prepare<M extends Model>(
    model: M,
    pk: keyof M
  ): {
    record: Record<string, any>;
    id: string;
    transient?: Record<string, any>;
  } {
    const log = this.log.for(this.prepare);
    log.silly(`Preparing model ${model.constructor.name} before persisting`);
    const split = modelToTransient(model);
    const result = Object.entries(split.model).reduce(
      (accum: Record<string, any>, [key, val]) => {
        if (typeof val === "undefined") return accum;
        const mappedProp = Repository.column(model, key);
        Iif (this.isReserved(mappedProp))
          throw new InternalError(`Property name ${mappedProp} is reserved`);
        accum[mappedProp] = val;
        return accum;
      },
      {}
    );
    Iif ((model as any)[PersistenceKeys.METADATA]) {
      log.silly(
        `Passing along persistence metadata for ${(model as any)[PersistenceKeys.METADATA]}`
      );
      Object.defineProperty(result, PersistenceKeys.METADATA, {
        enumerable: false,
        writable: false,
        configurable: true,
        value: (model as any)[PersistenceKeys.METADATA],
      });
    }
 
    return {
      record: result,
      id: model[pk] as string,
      transient: split.transient,
    };
  }
 
  revert<M extends Model>(
    obj: Record<string, any>,
    clazz: string | Constructor<M>,
    pk: keyof M,
    id: string | number | bigint,
    transient?: Record<string, any>
  ): M {
    const log = this.log.for(this.revert);
    const ob: Record<string, any> = {};
    ob[pk as string] = id;
    const m = (
      typeof clazz === "string" ? Model.build(ob, clazz) : new clazz(ob)
    ) as M;
    log.silly(`Rebuilding model ${m.constructor.name} id ${id}`);
    const metadata = obj[PersistenceKeys.METADATA];
    const result = Object.keys(m).reduce((accum: M, key) => {
      if (key === pk) return accum;
      (accum as Record<string, any>)[key] = obj[Repository.column(accum, key)];
      return accum;
    }, m);
 
    Iif (transient) {
      log.verbose(
        `re-adding transient properties: ${Object.keys(transient).join(", ")}`
      );
      Object.entries(transient).forEach(([key, val]) => {
        Iif (key in result)
          throw new InternalError(
            `Transient property ${key} already exists on model ${m.constructor.name}. should be impossible`
          );
        result[key as keyof M] = val;
      });
    }
 
    Iif (metadata) {
      log.silly(
        `Passing along ${this.flavour} persistence metadata for ${m.constructor.name} id ${id}: ${metadata}`
      );
      Object.defineProperty(result, PersistenceKeys.METADATA, {
        enumerable: false,
        configurable: false,
        writable: false,
        value: metadata,
      });
    }
 
    return result;
  }
 
  abstract create(
    tableName: string,
    id: string | number,
    model: Record<string, any>,
    ...args: any[]
  ): Promise<Record<string, any>>;
 
  async createAll(
    tableName: string,
    id: (string | number)[],
    model: Record<string, any>[],
    ...args: any[]
  ): Promise<Record<string, any>[]> {
    Iif (id.length !== model.length)
      throw new InternalError("Ids and models must have the same length");
    const log = this.log.for(this.createAll);
    log.verbose(`Creating ${id.length} entries ${tableName} table`);
    log.debug(`pks: ${id}`);
    return Promise.all(
      id.map((i, count) => this.create(tableName, i, model[count], ...args))
    );
  }
 
  abstract read(
    tableName: string,
    id: string | number | bigint,
    ...args: any[]
  ): Promise<Record<string, any>>;
 
  async readAll(
    tableName: string,
    id: (string | number | bigint)[],
    ...args: any[]
  ): Promise<Record<string, any>[]> {
    const log = this.log.for(this.readAll);
    log.verbose(`Reading ${id.length} entries ${tableName} table`);
    log.debug(`pks: ${id}`);
    return Promise.all(id.map((i) => this.read(tableName, i, ...args)));
  }
 
  abstract update(
    tableName: string,
    id: string | number,
    model: Record<string, any>,
    ...args: any[]
  ): Promise<Record<string, any>>;
 
  async updateAll(
    tableName: string,
    id: string[] | number[],
    model: Record<string, any>[],
    ...args: any[]
  ): Promise<Record<string, any>[]> {
    Iif (id.length !== model.length)
      throw new InternalError("Ids and models must have the same length");
    const log = this.log.for(this.updateAll);
    log.verbose(`Updating ${id.length} entries ${tableName} table`);
    log.debug(`pks: ${id}`);
    return Promise.all(
      id.map((i, count) => this.update(tableName, i, model[count], ...args))
    );
  }
 
  abstract delete(
    tableName: string,
    id: string | number | bigint,
    ...args: any[]
  ): Promise<Record<string, any>>;
 
  async deleteAll(
    tableName: string,
    id: (string | number | bigint)[],
    ...args: any[]
  ): Promise<Record<string, any>[]> {
    const log = this.log.for(this.createAll);
    log.verbose(`Deleting ${id.length} entries ${tableName} table`);
    log.debug(`pks: ${id}`);
    return Promise.all(id.map((i) => this.delete(tableName, i, ...args)));
  }
 
  abstract raw<R>(rawInput: Q, ...args: any[]): Promise<R>;
 
  /**
   *
   * @see {Observable#observe}
   */
  @final()
  observe(observer: Observer, filter?: ObserverFilter): void {
    if (!this.observerHandler)
      Object.defineProperty(this, "observerHandler", {
        value: this.ObserverHandler(),
        writable: false,
      });
    this.observerHandler!.observe(observer, filter);
    this.log
      .for(this.observe)
      .verbose(`Registering new observer ${observer.toString()}`);
    if (!this.dispatch) {
      this.log.for(this.observe).info(`Creating dispatch for ${this.alias}`);
      this.dispatch = this.Dispatch();
      this.dispatch.observe(this);
    }
  }
 
  /**
   * @summary Unregisters an {@link Observer}
   * @param {Observer} observer
   *
   * @see {Observable#unObserve}
   */
  @final()
  unObserve(observer: Observer): void {
    Iif (!this.observerHandler)
      throw new InternalError(
        "ObserverHandler not initialized. Did you register any observables?"
      );
    this.observerHandler.unObserve(observer);
    this.log
      .for(this.unObserve)
      .verbose(`Observer ${observer.toString()} removed`);
  }
 
  async updateObservers(
    table: string,
    event: OperationKeys | BulkCrudOperationKeys | string,
    id: EventIds,
    ...args: any[]
  ): Promise<void> {
    Iif (!this.observerHandler)
      throw new InternalError(
        "ObserverHandler not initialized. Did you register any observables?"
      );
    const log = this.log.for(this.updateObservers);
    log.verbose(
      `Updating ${this.observerHandler.count()} observers for adapter ${this.alias}`
    );
    await this.observerHandler.updateObservers(
      this.log,
      table,
      event,
      id,
      ...args
    );
  }
 
  async refresh(
    table: string,
    event: OperationKeys | BulkCrudOperationKeys | string,
    id: EventIds,
    ...args: any[]
  ) {
    return this.updateObservers(table, event, id, ...args);
  }
 
  toString() {
    return `${this.flavour} persistence Adapter`;
  }
 
  static flavourOf<M extends Model>(model: Constructor<M>): string {
    return (
      Reflect.getMetadata(this.key(PersistenceKeys.ADAPTER), model) ||
      this.current.flavour
    );
  }
 
  static get current() {
    if (!Adapter._current)
      throw new InternalError(
        `No persistence flavour set. Please initialize your adapter`
      );
    return Adapter._current;
  }
 
  static get<Y, Q, C extends Context<F>, F extends RepositoryFlags>(
    flavour: any
  ): Adapter<Y, Q, F, C> | undefined {
    if (flavour in this._cache) return this._cache[flavour];
    throw new InternalError(`No Adapter registered under ${flavour}.`);
  }
 
  static setCurrent(flavour: string) {
    const adapter = Adapter.get(flavour);
    Iif (!adapter)
      throw new NotFoundError(`No persistence flavour ${flavour} registered`);
    this._current = adapter;
  }
 
  static key(key: string) {
    return Repository.key(key);
  }
 
  static models<M extends Model>(flavour: string) {
    try {
      const registry = (Model as any).getRegistry() as ModelRegistry<any>;
      const cache = (
        registry as unknown as { cache: Record<string, ModelConstructor<any>> }
      ).cache;
      const managedModels: ModelConstructor<any>[] = Object.values(cache)
        .map((m: ModelConstructor<M>) => {
          let f = Reflect.getMetadata(
            Adapter.key(PersistenceKeys.ADAPTER),
            m as ModelConstructor<any>
          );
          if (f && f === flavour) return m;
          if (!f) {
            const repo = Reflect.getMetadata(
              Repository.key(DBKeys.REPOSITORY),
              m as ModelConstructor<any>
            );
            if (!repo) return;
            const repository = Repository.forModel(m);
 
            f = Reflect.getMetadata(
              Adapter.key(PersistenceKeys.ADAPTER),
              repository
            );
            return f;
          }
        })
        .filter((m) => !!m);
      return managedModels;
    } catch (e: any) {
      throw new InternalError(e);
    }
  }
}