From 7fb36f533486c099ff33f77989288050a597f779 Mon Sep 17 00:00:00 2001 From: Daniel O'Grady <103028279+daogrady@users.noreply.github.com> Date: Tue, 10 Oct 2023 13:56:00 +0200 Subject: [PATCH] Generate Static Name Property (#82) * Object.define name property for all classes to match entity name * Add changelog entry --- CHANGELOG.md | 1 + lib/visitor.js | 13 ++++++++----- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 92e48225..cf86cbc8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ The format is based on [Keep a Changelog](http://keepachangelog.com/). ### Added - Autoexposed entities in services are now also generated +- Each generated class now contains their original fully qualified name in a static `.name` property - Inline enums that are defined as literal type of properties are now supported as well (note: this feature is experimental. The location to which enums are generated might change in the future!) ### Fixed diff --git a/lib/visitor.js b/lib/visitor.js index 57e67129..2633382e 100644 --- a/lib/visitor.js +++ b/lib/visitor.js @@ -224,10 +224,12 @@ class Visitor { } #staticClassContents(clean, entity) { - return this.#isDraftEnabled(entity) ? [`static drafts: typeof ${clean}`] : [] + return this.#isDraftEnabled(entity) ? [`static drafts: typeof ${clean}`] : [] } #printEntity(name, entity) { + // static .name has to be defined more forcefully: https://github.com/microsoft/TypeScript/issues/442 + const overrideNameProperty = (clazz, content) => `Object.defineProperty(${clazz}, 'name', { value: '${content}' })` const clean = this.resolver.trimNamespace(name) const ns = this.resolver.resolveNamespace(name.split('.')) const file = this.getNamespaceFile(ns) @@ -252,10 +254,9 @@ class Visitor { file.addClass(plural, name) const parent = this.resolver.resolveParent(entity.name) - const buffer = - parent && parent.kind === 'entity' - ? file.getSubNamespace(this.resolver.trimNamespace(parent.name)) - : file.classes + const buffer = parent && parent.kind === 'entity' + ? file.getSubNamespace(this.resolver.trimNamespace(parent.name)) + : file.classes // we can't just use "singular" here, as it may have the subnamespace removed: // "Books.text" is just "text" in "singular". Within the inflected exports we need @@ -278,6 +279,8 @@ class Visitor { // plural can not be a type alias to $singular[] but needs to be a proper class instead, // so it can get passed as value to CQL functions. buffer.add(`export class ${plural} extends Array<${singular}> {${this.#staticClassContents(singular, entity).join('\n')}}`) + buffer.add(overrideNameProperty(singular, entity.name)) + buffer.add(overrideNameProperty(plural, entity.name)) buffer.add('') }