All files / src/entity EntityDefinition.ts

96.15% Statements 100/104
91.92% Branches 205/223
92.85% Functions 13/14
96.07% Lines 98/102

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          1x                 1x   1x 1x                             1x             28x     28x 28x     28x 28x 28x 20x         2x       24x   24x                     31x         106x 47x           47x 6x     41x       59x 3x             56x 56x 56x   56x 29x     56x 11x   11x 3x   3x         8x           8x 8x   8x         45x   45x 75x 75x 75x 75x 75x   75x             75x     75x     122x 122x   122x   4x 4x 4x 4x 13x   4x     122x 75x           47x   6x 1x         5x   5x           41x 13x           28x             75x   75x 75x 2x         75x       75x             75x 4x 71x 2x 69x 2x   67x     75x         75x 1x     75x       10x     75x     45x         45x 37x     45x 37x     45x 29x     45x           31x       31x       56x       45x       150x      
/*
 * © Copyright 2022 HP Development Company, L.P.
 * SPDX-License-Identifier: MIT
 */
 
import {
	ClassReflection,
	ClassType,
	DecoratorId,
	Maybe,
	PropertyReflection,
	reflect,
	TypeValue
} from '@davinci/reflector';
import deepMerge from 'deepmerge';
import { EntityDefinitionJSONSchema, EntityOptions, EntityPropReflection, JSONSchema } from './types';
import { isPlainObject, omit } from '../lib/object-utils';
import { transformEntityDefinitionSchema } from './json/transformEntityDefinitionSchema';
 
interface EntityDefinitionOptions {
	name?: string;
	type?: TypeValue;
	jsonSchema?: JSONSchema;
	// eslint-disable-next-line no-use-before-define
	entityDefinitionsMapCache?: Map<TypeValue, EntityDefinition>;
	reflect?: boolean;
}
 
/**
 * The EntityDefinition class serves as a base class that provides a wrapper for "complex" entities and their properties.
 * In this context, "complex" refers to schemas that are represented by classes.
 */
export class EntityDefinition {
	private name?: string;
	private readonly type: TypeValue | undefined;
	private entityDefinitionJsonSchema?: EntityDefinitionJSONSchema;
	private entityDefinitionsMapCache: Map<TypeValue, EntityDefinition>;
 
	constructor(options: EntityDefinitionOptions) {
		Iif (!options.type && !options.jsonSchema) {
			throw new Error('type or entityDefinitionJsonSchema must be passed');
		}
		Eif (options.type) {
			this.type = options.type;
		}
 
		this.name = options.name ?? (this.type as ClassType)?.name;
		this.entityDefinitionsMapCache = options.entityDefinitionsMapCache ?? new Map<TypeValue, EntityDefinition>();
		if (options.reflect !== false) {
			this.entityDefinitionJsonSchema = this.reflect();
		}
	}
 
	public getName() {
		return this.name;
	}
 
	public getEntityDefinitionJsonSchema() {
		this.entityDefinitionJsonSchema = this.entityDefinitionJsonSchema ?? this.reflect();
 
		return this.entityDefinitionJsonSchema;
	}
 
	public getType() {
		return this.type;
	}
 
	/**
	 * This method traverses the class and generates the EntityDefinitionJSONSchema
	 */
	private reflect(): EntityDefinitionJSONSchema {
		const makeSchema = (
			typeOrClass: TypeValue | StringConstructor | NumberConstructor | BooleanConstructor | Date,
			key?: string
		): Partial<JSONSchema> | null => {
			// it's a primitive type, simple case
			if (typeOrClass === String || typeOrClass === Number || typeOrClass === Boolean || typeOrClass === Date) {
				const type = typeOrClass as
					| StringConstructor
					| NumberConstructor
					| BooleanConstructor
					| DateConstructor;
 
				if (typeOrClass === Date) {
					return { type: 'string', format: 'date-time' };
				}
 
				return { type: type.name.toLowerCase() };
			}
 
			// it's an array => recursively call makeSchema on the first array element
			if (Array.isArray(typeOrClass)) {
				return {
					type: 'array',
					items: makeSchema(typeOrClass[0], key)
				};
			}
 
			// it's a class => reflect and recursively call makeSchema on the properties
			Eif (typeof typeOrClass === 'function') {
				const reflection = reflect(typeOrClass as ClassType);
				const entityDecorator = this.findEntityDecorator(reflection);
 
				if (entityDecorator && this.type === typeOrClass) {
					this.name = entityDecorator.options?.name ?? this.name;
				}
 
				if (entityDecorator && this.type !== typeOrClass) {
					const theClass = <TypeValue>typeOrClass;
 
					if (this.entityDefinitionsMapCache?.has(theClass)) {
						const entityDefinition = this.entityDefinitionsMapCache?.get(theClass);
 
						return {
							_$ref: entityDefinition
						};
					}
 
					const entityDefinition = new EntityDefinition({
						type: theClass,
						entityDefinitionsMapCache: this.entityDefinitionsMapCache,
						reflect: false
					});
					// eslint-disable-next-line no-unused-expressions
					this.entityDefinitionsMapCache?.set(theClass, entityDefinition);
					entityDefinition.reflect();
 
					return {
						_$ref: entityDefinition
					};
				}
 
				const entityProps = this.filterEntityPropDecorators(reflection);
				const { properties, required } =
					entityProps?.reduce<Partial<Pick<JSONSchema, 'properties' | 'required'>> | null>((acc, prop) => {
						const accumulator = acc ?? { properties: {}, required: [] };
						const entityPropDecorator = this.findEntityPropDecorator(prop);
						const lazyType = entityPropDecorator.options?.typeFactory?.();
						const explicitType = lazyType ?? entityPropDecorator.options?.type;
						const type = explicitType ?? prop.type;
 
						const isArray = Array.isArray(type);
 
						// traverse the json of the json schema that is explicitly passed in the decorator
						// This is useful to traverse and reflect complex classes nested in json schema keywords (like anyOf, allOf, oneOf)
						// e.g.
						// @entity.prop({ anyOf: [MyClassOne, MyClassTwo]  })
						const omitProps =
							typeof entityPropDecorator?.options?.required === 'boolean'
								? ['type', 'typeFactory', 'required']
								: ['type', 'typeFactory'];
						const extractedJsonSchema = transformEntityDefinitionSchema(
							omit(entityPropDecorator?.options ?? {}, omitProps),
							args => {
								let additionalSchemaProps: Partial<JSONSchema> = {};
								let hasAdditionalSchemaProps = false;
 
								if (args.schema.enum && typeof args.schema.enum === 'object') {
									const enmType =
										args.schema.type === 'number' || type.name === 'Number' ? 'number' : 'string';
									additionalSchemaProps = {};
									additionalSchemaProps.type = enmType;
									additionalSchemaProps.enum = Object.values(args.schema.enum).filter(
										v => typeof v === enmType || (v === null && args.schema.nullable)
									) as Array<string | number>;
									hasAdditionalSchemaProps = true;
								}
 
								if (args.pointerPath === '') {
									return {
										path: '',
										value: omit({ ...args.schema, ...additionalSchemaProps }, ['properties'])
									};
								}
 
								if (typeof args.schema === 'function') {
									// this check allow to support recursive schemas, specified in oneOf, allOf or anyOf keywords
									if (args.schema === this.type) {
										return {
											path: args.pointerPath,
											value: { _$ref: this }
										};
									}
									const value = makeSchema(args.schema);
 
									return {
										path: args.pointerPath,
										value
									};
								}
 
								if (hasAdditionalSchemaProps || args.parentKeyword === 'properties') {
									return {
										path: args.pointerPath,
										value: { ...args.schema, ...additionalSchemaProps }
									};
								}
 
								return null;
							}
						) as EntityDefinitionJSONSchema['properties'][string];
 
						// passing false or null as the type value, will disable the automatic
						// detection of the type
						// e.g. e.g. @entity.prop({ type: false })
						const hasFalseOrNullType = explicitType === false || explicitType === null;
 
						let isRecursiveType = false;
						if ((isArray && type[0] === this.type) || type === this.type) {
							isRecursiveType = true;
						}
 
						// the type is 'explicit', when is explicitly passed as parameter to the @entity.prop decorator
						// e.g. @entity.prop({ type: String })
						const hasExplicitType = !hasFalseOrNullType && typeof explicitType !== 'undefined';
 
						// a constant type is a standard JSON schema type, like 'string', 'number', etc
						const hasConstType =
							!hasFalseOrNullType &&
							hasExplicitType &&
							!Array.isArray(explicitType) &&
							typeof entityPropDecorator.options?.type !== 'function' &&
							!lazyType;
 
						let generatedJsonSchema;
						if (hasFalseOrNullType) {
							generatedJsonSchema = {};
						} else if (isRecursiveType) {
							generatedJsonSchema = isArray ? { type: 'array', items: { _$ref: this } } : { _$ref: this };
						} else if (hasConstType) {
							generatedJsonSchema = { type: entityPropDecorator.options?.type };
						} else {
							generatedJsonSchema = makeSchema(type, prop.name);
						}
 
						accumulator.properties[prop.name] = deepMerge(extractedJsonSchema, generatedJsonSchema ?? {}, {
							isMergeableObject: isPlainObject
						});
 
						// this allows specifying custom formats, especially useful for when the type is Date
						if (accumulator.properties[prop.name].type === 'string' && extractedJsonSchema.format) {
							accumulator.properties[prop.name].format = extractedJsonSchema.format;
						}
 
						if (
							entityPropDecorator.options?.required &&
							typeof entityPropDecorator.options?.required === 'boolean'
						) {
							accumulator.required.push(prop.name);
						}
 
						return accumulator;
					}, null) ?? {};
 
				const jsonSchema: Partial<JSONSchema> = {
					title: entityDecorator?.options?.name ?? key ?? typeOrClass.name,
					type: 'object'
				};
 
				if (properties) {
					jsonSchema.properties = properties;
				}
 
				if (required) {
					jsonSchema.required = required;
				}
 
				if (entityDecorator) {
					jsonSchema.$id = jsonSchema.title;
				}
 
				return jsonSchema;
			}
 
			return null;
		};
 
		Iif (!this.type) {
			throw new Error('type not set');
		}
 
		return makeSchema(this.type) as EntityDefinitionJSONSchema;
	}
 
	private findEntityDecorator(reflection: ClassReflection): Maybe<{ [DecoratorId]: string; options: EntityOptions }> {
		return reflection.decorators?.find(d => d[DecoratorId] === 'entity');
	}
 
	private filterEntityPropDecorators(reflection: ClassReflection): PropertyReflection[] {
		return reflection.properties?.filter(this.findEntityPropDecorator);
	}
 
	private findEntityPropDecorator(reflection: PropertyReflection): EntityPropReflection {
		return reflection.decorators?.find(d => d[DecoratorId] === 'entity.prop');
	}
}