From 7f20ceb450e411d84519ff0c9d0bb0ef7dd48c59 Mon Sep 17 00:00:00 2001 From: Alin Eugen Deac Date: Thu, 15 Feb 2024 20:59:49 +0100 Subject: [PATCH] Refactor, use get all parents util function Also, removed edge case handling. In case that a property descriptor returns null, we simply skip it. --- .../getClassPropertyDescriptors.ts | 24 +++++++------------ 1 file changed, 8 insertions(+), 16 deletions(-) diff --git a/packages/support/src/reflections/getClassPropertyDescriptors.ts b/packages/support/src/reflections/getClassPropertyDescriptors.ts index 0d742f8d..fe7cb062 100644 --- a/packages/support/src/reflections/getClassPropertyDescriptors.ts +++ b/packages/support/src/reflections/getClassPropertyDescriptors.ts @@ -1,7 +1,7 @@ import type { ConstructorOrAbstractConstructor } from "@aedart/contracts"; -import { FUNCTION_PROTOTYPE } from "@aedart/contracts/support/reflections"; import { getClassPropertyDescriptor } from "./getClassPropertyDescriptor"; import { assertHasPrototypeProperty } from "./assertHasPrototypeProperty"; +import { getAllParentsOfClass } from "./getAllParentsOfClass"; /** * Returns all property descriptors that are defined target's prototype @@ -16,27 +16,18 @@ import { assertHasPrototypeProperty } from "./assertHasPrototypeProperty"; * @return {Record} Object with the property descriptors, or empty object of target has * properties defined. * - * @throws {TypeError} If target is not an object or has no prototype + * @throws {TypeError} If target is not an object or has no prototype property */ export function getClassPropertyDescriptors(target: ConstructorOrAbstractConstructor, recursive: boolean = false): Record { assertHasPrototypeProperty(target); // Define list of targets... - const targets = [target.prototype]; - - // If recursive flag is set, then all of target's parent classes must be obtained. - if (recursive) { - let parent = Reflect.getPrototypeOf(target.prototype); - - while(parent !== null && parent !== FUNCTION_PROTOTYPE) { - targets.push(parent); + let targets = [target.prototype]; - parent = Reflect.getPrototypeOf(parent); - } - - // Reverse the targets, such that the top-most property descriptors are returned. - targets.reverse(); + // Obtain target's parent classes, such that top-most descriptors can be returned, if needed. + if (recursive) { + targets = getAllParentsOfClass(target.prototype, true).reverse(); } const output: Record = Object.create(null); @@ -46,8 +37,9 @@ export function getClassPropertyDescriptors(target: ConstructorOrAbstractConstru const keys: PropertyKey[] = Reflect.ownKeys(t); for (const key: PropertyKey of keys) { const descriptor: PropertyDescriptor | undefined = getClassPropertyDescriptor(t.constructor, key); + + // If for some reason we are unable to obtain a descriptor, then skip it. if (descriptor === undefined) { - output[key] = undefined; continue; }