Skip to content

Commit

Permalink
Generate Static Name Property (#82)
Browse files Browse the repository at this point in the history
* Object.define name property for all classes to match entity name

* Add changelog entry
  • Loading branch information
daogrady authored Oct 10, 2023
1 parent 2116e42 commit 7fb36f5
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 5 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
13 changes: 8 additions & 5 deletions lib/visitor.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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
Expand All @@ -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('')
}

Expand Down

0 comments on commit 7fb36f5

Please sign in to comment.