All files / src/classes/annotation Meta.ts

96.29% Statements 26/27
95.65% Branches 22/23
100% Functions 7/7
96.29% Lines 26/27

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          1x 1x         16x       18x             82x       82x       53x 1x     52x 2x   50x               1x     49x     1x 4x 4x       4x         8x 8x 1x   7x 7x 47x 47x 1x     6x                          
import 'reflect-metadata';
 
import type { ObjectLike } from './lib/props';
import type { ColumnProps, EntityProps } from './lib/types';
 
const columnKey = Symbol('column');
const entityKey = Symbol('entity');
 
function getEntityMeta<T extends ObjectLike>(
  target: T,
): EntityProps | undefined {
  return Reflect.getMetadata(entityKey, target.constructor.prototype);
}
 
function Column(props: ColumnProps): PropertyDecorator {
  return Reflect.metadata(columnKey, props);
}
 
function getColumnMeta<T>(
  target: T,
  propertyKey: keyof T,
): ColumnProps | undefined {
  Iif (typeof propertyKey === 'number') {
    throw new Error('no numeric objkey is allowed');
  }
 
  return Reflect.getMetadata(columnKey, target as object, propertyKey);
}
 
function validateColumnMeta(props?: ColumnProps): boolean {
  if (!props) {
    return false;
  }
 
  if (props.canBeNull && props.primaryKey) {
    return false;
  }
  if (
    props.foreignKey &&
    (!props.dataType ||
      props.dataType === 'float' ||
      props.dataType === 'double' ||
      props.dataType === 'blob' ||
      props.dataType === 'boolean')
  ) {
    return false;
  }
 
  return true;
}
 
const Entity = (name: string, version = 0): ClassDecorator => {
  return (target) => {
    const metadata = {
      name,
      version,
    };
    Reflect.defineMetadata(entityKey, metadata, target.prototype);
  };
};
 
function validateEntity<T extends ObjectLike>(target: T): boolean {
  const meta = getEntityMeta(target);
  if (!meta) {
    return false;
  }
  const keys = Object.keys(target) as (keyof T)[];
  for (const key of keys) {
    const cMeta = getColumnMeta(target, key);
    if (cMeta && !validateColumnMeta(cMeta)) {
      return false;
    }
  }
  return true;
}
 
export {
  Entity,
  getEntityMeta,
  validateEntity,
  Column,
  getColumnMeta,
  validateColumnMeta,
  columnKey,
  entityKey,
};