All files / src/classes CoreEntityWrapper.ts

95.58% Statements 65/68
85.18% Branches 23/27
100% Functions 19/19
95.52% Lines 64/67

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                                                                                  4x 4x 4x 4x 4x       222x         222x 2x       220x                         8x     8x   8x                           3x     3x 6x     3x                     11x 5x 5x       11x             11x 5x   11x       3x 3x 2x 4x 4x 1x       6x 3x             3x 5x 5x 3x     3x       486x                   11x                   19x             4x       4x       4x 4x 2x 2x   2x             4x 4x 2x   2x 2x       213x 213x       3x 5x   3x       3x       6x       4x 4x 4x 4x 28x   4x      
import CoreEntity from './CoreEntity';
import type {
  FindOrCreateResult,
  ICoreCache,
  ICoreEntityHandler,
  QInterface,
  QInterfaceSearch,
} from '../lib';
import {
  type ColumnPropMap,
  type ColumnProps,
  type EUpDateProperties,
  getColumnMeta,
} from './annotation';
import { EntityValidator } from '../utils';
import CMap from './CoreMap';
 
/**
 * A wrapper for CoreEntity operations providing a convenient API for CRUD
 * actions, bulk operations, and caching support. The wrapper is parameterized
 * by a concrete entity type {@link E} that extends {@link CoreEntity}.
 *
 * @template E - The entity type managed by this wrapper.
 */
export default class CoreEntityWrapper<E extends CoreEntity> {
  getIns: () => E;
 
  propMap: ColumnPropMap<E>;
 
  cache: ICoreCache | null;
 
  protected e_con: ICoreEntityHandler;
 
  protected className: string;
 
  constructor(
    con: ICoreEntityHandler,
    name: string,
    getIns: () => E,
    noCache = false,
  ) {
    this.e_con = con;
    this.className = name;
    this.getIns = getIns;
    this.propMap = this.genPropMap();
    this.cache = !noCache ? con.getCache() : null;
  }
 
  async createObject(args: E): Promise<E> {
    const { valid, invalidKey } = EntityValidator.validateObj(
      this.propMap,
      args,
      false,
    );
    if (!valid) {
      throw this.e_con.lError(
        `validation failed for ${this.className} create\nInvalid Fields:${invalidKey.join(',')}`,
      );
    }
    return this.e_con.createEntity<E>(
      {
        className: this.className,
        meta: this.propMap,
      },
      args,
    );
  }
 
  async updateObject(
    e_id: string,
    args: EUpDateProperties<E>,
  ): Promise<boolean> {
    Iif (!EntityValidator.validateObj(this.propMap, args, true)) {
      throw this.e_con.lError(`validation failed for ${this.className} update`);
    }
    await this.cache?.deleteE(this.className, e_id);
 
    return this.e_con.updateEntity<E>(
      {
        className: this.className,
        meta: this.propMap,
      },
      e_id,
      args,
    );
  }
 
  async updateObjectBulk(
    e_id: string[],
    args: EUpDateProperties<E>,
  ): Promise<boolean> {
    Iif (!EntityValidator.validateObj(this.propMap, args, true)) {
      throw this.e_con.lError(`validation failed for ${this.className} update`);
    }
    for (const id of e_id) {
      await this.cache?.deleteE(this.className, id);
    }
 
    return this.e_con.updateBulkEntity<E>(
      {
        className: this.className,
        meta: this.propMap,
      },
      e_id,
      args,
    );
  }
 
  async getObjById(id: string): Promise<E | null> {
    if (this.cache) {
      const has = await this.cache.getE<E>(this.className, id);
      Iif (has) {
        return has;
      }
    }
    const res = await this.e_con.getEntityById<E>(
      {
        className: this.className,
        meta: this.propMap,
      },
      id,
    );
    if (res && this.cache) {
      await this.cache.setE<E>(this.className, res);
    }
    return res;
  }
 
  async getObjByIdBulk(id: string[]): Promise<E[]> {
    const map = new CMap<string, E>();
    if (this.cache) {
      for (const i of id) {
        const has = await this.cache.getE<E>(this.className, i);
        if (has) {
          map.set(i, has);
        }
      }
    }
    const missing = id.filter((i) => !map.has(i));
    const res = await this.e_con.getEntityBulkById<E>(
      {
        className: this.className,
        meta: this.propMap,
      },
      missing,
    );
    for (const r of res) {
      map.set(r.e_id, r);
      if (this.cache) {
        await this.cache.setE<E>(this.className, r);
      }
    }
    return map.toValueArray();
  }
 
  async getObjList(query?: QInterface<E>): Promise<E[]> {
    return this.e_con.getEntityList<E>({
      config: {
        className: this.className,
        meta: this.propMap,
      },
      ...query,
    });
  }
 
  async findObj(search: QInterfaceSearch<E>): Promise<E | null> {
    return this.e_con.findEntity<E>(
      {
        className: this.className,
        meta: this.propMap,
      },
      search,
    );
  }
 
  async count(search?: QInterfaceSearch<E>): Promise<number> {
    return this.e_con.countEntity<E>(
      { className: this.className, meta: this.propMap },
      search,
    );
  }
 
  async exists(search: QInterfaceSearch<E>): Promise<boolean> {
    const result = await this.e_con.findEntity<E>(
      { className: this.className, meta: this.propMap },
      search,
    );
    return result !== null;
  }
 
  async upsert(search: QInterfaceSearch<E>, data: E): Promise<E> {
    const existing = await this.findObj(search);
    if (existing) {
      await this.updateObject(existing.e_id, data);
      return (await this.getObjById(existing.e_id))!;
    }
    return this.createObject(data);
  }
 
  async findOrCreate(
    search: QInterfaceSearch<E>,
    createData: E,
  ): Promise<FindOrCreateResult<E>> {
    const existing = await this.findObj(search);
    if (existing) {
      return { entity: existing, created: false };
    }
    const entity = await this.createObject(createData);
    return { entity, created: true };
  }
 
  async delete(e_id: string): Promise<boolean> {
    await this.cache?.deleteE(this.className, e_id);
    return this.e_con.deleteEntityById(this.className, e_id);
  }
 
  async deleteBulk(e_id: string[]): Promise<boolean> {
    for (const id of e_id) {
      await this.cache?.deleteE(this.className, id);
    }
    return this.e_con.deleteEntityBulkById(this.className, e_id);
  }
 
  async init(): Promise<boolean> {
    return this.e_con.initEntity(this.className, this.getIns());
  }
 
  getPropMap(): ColumnPropMap<E> {
    return this.propMap;
  }
 
  private genPropMap(): ColumnPropMap<E> {
    const map = new Map<keyof E, ColumnProps>();
    const ent: E = this.getIns();
    const keys = Object.keys(ent) as (keyof E)[];
    keys.forEach((key) => {
      map.set(key, getColumnMeta(ent, key) as ColumnProps);
    });
    return map;
  }
}