All files / src/model construction.ts

83.33% Statements 125/150
60.78% Branches 31/51
100% Functions 16/16
90.37% Lines 122/135

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 3869x             9x   9x           9x 9x     9x               12x 12x 12x   12x       12x 7x   5x 5x               9x                         10x 10x   10x 3x 3x 3x 3x 3x     7x 7x   7x 7x 7x 7x 7x     9x                         4x 4x 4x   4x               4x 4x 4x             4x     9x                         4x 4x 4x 4x   4x 1x   3x       4x                 9x                         6x 6x 6x 12x 1x     5x 5x 1x 1x 2x 2x   1x 1x     4x   4x   4x 8x 8x 8x     4x     9x                         2x 2x 2x               9x                         2x 2x 2x 2x 4x 2x       2x 2x       2x   2x       2x 4x 4x   2x     9x         84x     9x                   32x         32x     9x                         55x 43x 43x 43x                   43x 43x 52x 52x 52x     30x 30x 30x   52x   43x   43x           43x     9x                         9x       39x                 39x     39x         39x     39x 39x   39x       39x 39x     39x    
import {
  Constructor,
  Model,
  ModelConstructor,
  Validation,
  ValidationKeys,
} from "@decaf-ts/decorator-validation";
import { Repo, Repository } from "../repository/Repository";
import { RelationsMetadata } from "./types";
import {
  findPrimaryKey,
  InternalError,
  NotFoundError,
  RepositoryFlags,
} from "@decaf-ts/db-decorators";
import { PersistenceKeys } from "../persistence/constants";
import { Cascade } from "../repository/constants";
import { Context } from "@decaf-ts/db-decorators";
 
export async function createOrUpdate<
  M extends Model,
  F extends RepositoryFlags,
>(
  model: M,
  context: Context<F>,
  repository?: Repo<M, F, Context<F>>
): Promise<M> {
  if (!repository) {
    const constructor = Model.get(model.constructor.name);
    Iif (!constructor)
      throw new InternalError(`Could not find model ${model.constructor.name}`);
    repository = Repository.forModel<M, Repo<M>>(
      constructor as unknown as ModelConstructor<M>
    );
  }
  if (typeof model[repository.pk] === "undefined")
    return repository.create(model, context);
  else {
    try {
      return repository.update(model, context);
    } catch (e: any) {
      Iif (!(e instanceof NotFoundError)) throw e;
      return repository.create(model, context);
    }
  }
}
 
export async function oneToOneOnCreate<
  M extends Model,
  R extends Repo<M, F, C>,
  V extends RelationsMetadata,
  F extends RepositoryFlags,
  C extends Context<F>,
>(
  this: R,
  context: Context<F>,
  data: V,
  key: keyof M,
  model: M
): Promise<void> {
  const propertyValue: any = model[key];
  Iif (!propertyValue) return;
 
  if (typeof propertyValue !== "object") {
    const innerRepo = repositoryFromTypeMetadata(model, key);
    const read = await innerRepo.read(propertyValue);
    await cacheModelForPopulate(context, model, key, propertyValue, read);
    (model as any)[key] = propertyValue;
    return;
  }
 
  const constructor = Model.get(data.class);
  Iif (!constructor)
    throw new InternalError(`Could not find model ${data.class}`);
  const repo: Repo<any> = Repository.forModel(constructor);
  const created = await repo.create(propertyValue);
  const pk = findPrimaryKey(created).id;
  await cacheModelForPopulate(context, model, key, created[pk], created);
  (model as any)[key] = created[pk];
}
 
export async function oneToOneOnUpdate<
  M extends Model,
  R extends Repo<M, F, C>,
  V extends RelationsMetadata,
  F extends RepositoryFlags,
  C extends Context<F>,
>(
  this: R,
  context: Context<F>,
  data: V,
  key: keyof M,
  model: M
): Promise<void> {
  const propertyValue: any = model[key];
  Iif (!propertyValue) return;
  Iif (data.cascade.update !== Cascade.CASCADE) return;
 
  Iif (typeof propertyValue !== "object") {
    const innerRepo = repositoryFromTypeMetadata(model, key);
    const read = await innerRepo.read(propertyValue);
    await cacheModelForPopulate(context, model, key, propertyValue, read);
    (model as any)[key] = propertyValue;
    return;
  }
 
  const updated = await createOrUpdate(model[key] as M, context);
  const pk = findPrimaryKey(updated).id;
  await cacheModelForPopulate(
    context,
    model,
    key,
    updated[pk] as string,
    updated
  );
  model[key] = updated[pk];
}
 
export async function oneToOneOnDelete<
  M extends Model,
  R extends Repo<M, F, C>,
  V extends RelationsMetadata,
  F extends RepositoryFlags,
  C extends Context<F>,
>(
  this: R,
  context: Context<F>,
  data: V,
  key: keyof M,
  model: M
): Promise<void> {
  const propertyValue: any = model[key];
  Iif (!propertyValue) return;
  Iif (data.cascade.update !== Cascade.CASCADE) return;
  const innerRepo: Repo<M> = repositoryFromTypeMetadata(model, key);
  let deleted: M;
  if (!(propertyValue instanceof Model))
    deleted = await innerRepo.delete(model[key] as string, context);
  else
    deleted = await innerRepo.delete(
      (model[key] as M)[innerRepo.pk as keyof M] as string,
      context
    );
  await cacheModelForPopulate(
    context,
    model,
    key,
    deleted[innerRepo.pk] as string,
    deleted
  );
}
 
export async function oneToManyOnCreate<
  M extends Model,
  R extends Repo<M, F, C>,
  V extends RelationsMetadata,
  F extends RepositoryFlags,
  C extends Context<F>,
>(
  this: R,
  context: Context<F>,
  data: V,
  key: keyof M,
  model: M
): Promise<void> {
  const propertyValues: any = model[key];
  Iif (!propertyValues || !propertyValues.length) return;
  const arrayType = typeof propertyValues[0];
  if (!propertyValues.every((item: any) => typeof item === arrayType))
    throw new InternalError(
      `Invalid operation. All elements of property ${key as string} must match the same type.`
    );
  const uniqueValues = new Set([...propertyValues]);
  if (arrayType !== "object") {
    const repo = repositoryFromTypeMetadata(model, key);
    for (const id of uniqueValues) {
      const read = await repo.read(id);
      await cacheModelForPopulate(context, model, key, id, read);
    }
    (model as any)[key] = [...uniqueValues];
    return;
  }
 
  const pkName = findPrimaryKey(propertyValues[0]).id;
 
  const result: Set<string> = new Set();
 
  for (const m of propertyValues) {
    const record = await createOrUpdate(m, context);
    await cacheModelForPopulate(context, model, key, record[pkName], record);
    result.add(record[pkName]);
  }
 
  (model as any)[key] = [...result];
}
 
export async function oneToManyOnUpdate<
  M extends Model,
  R extends Repo<M, F, C>,
  V extends RelationsMetadata,
  F extends RepositoryFlags,
  C extends Context<F>,
>(
  this: R,
  context: Context<F>,
  data: V,
  key: keyof M,
  model: M
): Promise<void> {
  const { cascade } = data;
  Iif (cascade.update !== Cascade.CASCADE) return;
  return oneToManyOnCreate.apply(this as any, [
    context,
    data,
    key as keyof Model,
    model,
  ]);
}
 
export async function oneToManyOnDelete<
  M extends Model,
  R extends Repo<M, F, C>,
  V extends RelationsMetadata,
  F extends RepositoryFlags,
  C extends Context<F>,
>(
  this: R,
  context: Context<F>,
  data: V,
  key: keyof M,
  model: M
): Promise<void> {
  Iif (data.cascade.delete !== Cascade.CASCADE) return;
  const values = model[key] as any;
  Iif (!values || !values.length) return;
  const arrayType = typeof values[0];
  const areAllSameType = values.every((item: any) => typeof item === arrayType);
  Iif (!areAllSameType)
    throw new InternalError(
      `Invalid operation. All elements of property ${key as string} must match the same type.`
    );
  const isInstantiated = arrayType === "object";
  const repo = isInstantiated
    ? Repository.forModel(values[0])
    : repositoryFromTypeMetadata(model, key);
 
  const uniqueValues = new Set([
    ...(isInstantiated
      ? values.map((v: Record<string, any>) => v[repo.pk as string])
      : values),
  ]);
 
  for (const id of uniqueValues.values()) {
    const deleted = await repo.delete(id, context);
    await cacheModelForPopulate(context, model, key, id, deleted);
  }
  (model as any)[key] = [...uniqueValues];
}
 
export function getPopulateKey(
  tableName: string,
  fieldName: string,
  id: string | number
) {
  return [PersistenceKeys.POPULATE, tableName, fieldName, id].join(".");
}
 
export async function cacheModelForPopulate<
  M extends Model,
  F extends RepositoryFlags,
>(
  context: Context<F>,
  parentModel: M,
  propertyKey: keyof M | string,
  pkValue: string | number,
  cacheValue: any
) {
  const cacheKey = getPopulateKey(
    parentModel.constructor.name,
    propertyKey as string,
    pkValue
  );
  return context.accumulate({ [cacheKey]: cacheValue });
}
 
export async function populate<
  M extends Model,
  R extends Repo<M, F, C>,
  V extends RelationsMetadata,
  F extends RepositoryFlags,
  C extends Context<F>,
>(
  this: R,
  context: Context<F>,
  data: V,
  key: keyof M,
  model: M
): Promise<void> {
  if (!data.populate) return;
  const nested: any = model[key];
  const isArr = Array.isArray(nested);
  Iif (typeof nested === "undefined" || (isArr && nested.length === 0)) return;
 
  async function fetchPopulateValues(
    c: Context<F>,
    model: M,
    propName: string,
    propKeyValues: any[]
  ) {
    let cacheKey: string;
    let val: any;
    const results: M[] = [];
    for (const proKeyValue of propKeyValues) {
      cacheKey = getPopulateKey(model.constructor.name, propName, proKeyValue);
      try {
        val = await c.get(cacheKey as any);
        // eslint-disable-next-line @typescript-eslint/no-unused-vars
      } catch (e: any) {
        const repo = repositoryFromTypeMetadata(model, propName);
        Iif (!repo) throw new InternalError("Could not find repo");
        val = await repo.read(proKeyValue);
      }
      results.push(val);
    }
    return results;
  }
  const res = await fetchPopulateValues(
    context,
    model,
    key as string,
    isArr ? nested : [nested]
  );
  (model as any)[key] = isArr ? res : res[0];
}
 
const commomTypes = [
  "array",
  "string",
  "number",
  "boolean",
  "symbol",
  "function",
  "object",
  "undefined",
  "null",
  "bigint",
];
 
export function repositoryFromTypeMetadata<M extends Model>(
  model: any,
  propertyKey: string | keyof M
): Repo<M> {
  const types = Reflect.getMetadata(
    Validation.key(
      Array.isArray(model[propertyKey])
        ? ValidationKeys.LIST
        : ValidationKeys.TYPE
    ),
    model,
    propertyKey as string
  );
  const customTypes: any = Array.isArray(model[propertyKey])
    ? types.clazz
    : types.customTypes;
  Iif (!types || !customTypes)
    throw new InternalError(
      `Failed to find types decorators for property ${propertyKey as string}`
    );
 
  const allowedTypes: string[] = Array.isArray(customTypes)
    ? [...customTypes]
    : [customTypes];
  const constructorName = allowedTypes.find(
    (t) => !commomTypes.includes(`${t}`.toLowerCase())
  );
  Iif (!constructorName)
    throw new InternalError(
      `Property key ${propertyKey as string} does not have a valid constructor type`
    );
  const constructor: Constructor<M> | undefined = Model.get(constructorName);
  Iif (!constructor)
    throw new InternalError(`No registered model found for ${constructorName}`);
 
  return Repository.forModel(constructor);
}