All files / src/ram RamAdapter.ts

87.09% Statements 81/93
52.17% Branches 12/23
90% Functions 18/20
89.41% Lines 76/85

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  8x 8x 8x 8x   8x 8x           8x                 8x 8x 8x   8x             8x       7x               202x         8x   8x         8x       2x                       191x 191x 191x                 949x 949x               158x 158x 158x       158x 158x 158x             175x 12x 163x 28x     135x               32x 32x   32x       32x 32x 32x             15x 15x   15x       15x 15x 15x 15x       15x 15x 15x 15x       15x 15x 15x 15x   15x   15x 590x               15x   15x   15x 15x   15x 3x 3x 18x 113x 113x         15x                 12x       39x       9x 9x 9x             9x                   8x  
import { RamFlags, RawRamQuery, RamStorage, RamRepository } from "./types";
import { RamStatement } from "./RamStatement";
import { RamContext } from "./RamContext";
import { Repository } from "../repository/Repository";
import { Adapter, PersistenceKeys, Sequence } from "../persistence";
import { SequenceOptions } from "../interfaces";
import { Lock } from "@decaf-ts/transactional-decorators";
import {
  Constructor,
  Decoration,
  Model,
  propMetadata,
} from "@decaf-ts/decorator-validation";
import {
  BaseError,
  ConflictError,
  findPrimaryKey,
  InternalError,
  NotFoundError,
  onCreate,
  OperationKeys,
} from "@decaf-ts/db-decorators";
import { RamSequence } from "./RamSequence";
import { createdByOnRamCreateUpdate } from "./handlers";
import { RamFlavour } from "./constants";
 
export class RamAdapter extends Adapter<
  RamStorage,
  RawRamQuery<any>,
  RamFlags,
  RamContext
> {
  constructor(alias?: string) {
    super(new Map<string, Map<string, any>>(), RamFlavour, alias);
  }
 
  override repository<M extends Model>(): Constructor<RamRepository<M>> {
    return super.repository<M>() as Constructor<RamRepository<M>>;
  }
 
  override flags<M extends Model>(
    operation: OperationKeys,
    model: Constructor<M>,
    flags: Partial<RamFlags>
  ): RamFlags {
    return Object.assign(super.flags(operation, model, flags), {
      UUID: crypto.randomUUID(),
    }) as RamFlags;
  }
 
  override Context = RamContext;
 
  private indexes: Record<
    string,
    Record<string | number, Record<string, any>>
  > = {};
 
  private lock = new Lock();
 
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  async initialize(...args: any[]): Promise<void> {
    return Promise.resolve(undefined);
  }
 
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  async index(...models: Record<string, any>[]): Promise<any> {
    return Promise.resolve(undefined);
  }
 
  override prepare<M extends Model>(
    model: M,
    pk: keyof M
  ): { record: Record<string, any>; id: string } {
    const prepared = super.prepare(model, pk);
    delete prepared.record[pk as string];
    return prepared;
  }
 
  override revert<M extends Model>(
    obj: Record<string, any>,
    clazz: string | Constructor<M>,
    pk: keyof M,
    id: string | number
  ): M {
    const res = super.revert(obj, clazz, pk, id);
    return res;
  }
 
  async create(
    tableName: string,
    id: string | number,
    model: Record<string, any>
  ): Promise<Record<string, any>> {
    await this.lock.acquire();
    if (!this.native.has(tableName)) this.native.set(tableName, new Map());
    Iif (this.native.get(tableName) && this.native.get(tableName)?.has(id))
      throw new ConflictError(
        `Record with id ${id} already exists in table ${tableName}`
      );
    this.native.get(tableName)?.set(id, model);
    this.lock.release();
    return model;
  }
 
  async read(
    tableName: string,
    id: string | number
  ): Promise<Record<string, any>> {
    if (!this.native.has(tableName))
      throw new NotFoundError(`Table ${tableName} not found`);
    if (!this.native.get(tableName)?.has(id))
      throw new NotFoundError(
        `Record with id ${id} not found in table ${tableName}`
      );
    return this.native.get(tableName)?.get(id);
  }
 
  async update(
    tableName: string,
    id: string | number,
    model: Record<string, any>
  ): Promise<Record<string, any>> {
    await this.lock.acquire();
    Iif (!this.native.has(tableName))
      throw new NotFoundError(`Table ${tableName} not found`);
    Iif (!this.native.get(tableName)?.has(id))
      throw new NotFoundError(
        `Record with id ${id} not found in table ${tableName}`
      );
    this.native.get(tableName)?.set(id, model);
    this.lock.release();
    return model;
  }
 
  async delete(
    tableName: string,
    id: string | number
  ): Promise<Record<string, any>> {
    await this.lock.acquire();
    Iif (!this.native.has(tableName))
      throw new NotFoundError(`Table ${tableName} not found`);
    Iif (!this.native.get(tableName)?.has(id))
      throw new NotFoundError(
        `Record with id ${id} not found in table ${tableName}`
      );
    const natived = this.native.get(tableName)?.get(id);
    this.native.get(tableName)?.delete(id);
    this.lock.release();
    return natived;
  }
 
  protected tableFor<M extends Model>(from: string | Constructor<M>) {
    Iif (typeof from === "string") from = Model.get(from) as Constructor<M>;
    const table = Repository.table(from);
    Iif (!this.native.has(table)) this.native.set(table, new Map());
    return this.native.get(table);
  }
 
  async raw<R>(rawInput: RawRamQuery<any>): Promise<R> {
    const { where, sort, limit, skip, from } = rawInput;
    let { select } = rawInput;
    const collection = this.tableFor(from);
    Iif (!collection)
      throw new InternalError(`Table ${from} not found in RamAdapter`);
    const { id, props } = findPrimaryKey(new from());
 
    let result: any[] = Array.from(collection.entries()).map(([pk, r]) =>
      this.revert(
        r,
        from,
        id as any,
        Sequence.parseValue(props.type as any, pk as string) as string
      )
    );
 
    result = where ? result.filter(where) : result;
 
    if (sort) result = result.sort(sort);
 
    if (skip) result = result.slice(skip);
    if (limit) result = result.slice(0, limit);
 
    if (select) {
      select = Array.isArray(select) ? select : [select];
      result = result.map((r) =>
        Object.entries(r).reduce((acc: Record<string, any>, [key, val]) => {
          if ((select as string[]).includes(key)) acc[key] = val;
          return acc;
        }, {})
      );
    }
 
    return result as unknown as R;
  }
 
  parseError<V extends BaseError>(err: Error): V {
    Iif (err instanceof BaseError) return err as V;
    return new InternalError(err) as V;
  }
 
  Statement<M extends Model>(): RamStatement<M, any> {
    return new RamStatement<M, any>(this as any);
  }
 
  async Sequence(options: SequenceOptions): Promise<Sequence> {
    return new RamSequence(options, this);
  }
 
  static decoration() {
    const createdByKey = Repository.key(PersistenceKeys.CREATED_BY);
    const updatedByKey = Repository.key(PersistenceKeys.UPDATED_BY);
    Decoration.flavouredAs(RamFlavour)
      .for(createdByKey)
      .define(
        onCreate(createdByOnRamCreateUpdate),
        propMetadata(createdByKey, {})
      )
      .apply();
    Decoration.flavouredAs(RamFlavour)
      .for(updatedByKey)
      .define(
        onCreate(createdByOnRamCreateUpdate),
        propMetadata(updatedByKey, {})
      )
      .apply();
  }
}
 
RamAdapter.decoration();