diff --git a/.changeset/little-starfishes-whisper.md b/.changeset/little-starfishes-whisper.md new file mode 100644 index 0000000000..60a4b39c73 --- /dev/null +++ b/.changeset/little-starfishes-whisper.md @@ -0,0 +1,5 @@ +--- +'@backstage/catalog-model': minor +--- + +Added `stringifyEntityRef`, which always creates a string representation of an entity reference. Also deprecated `serializeEntityRef`, as `stringifyEntityRef` should be used instead. diff --git a/packages/catalog-model/src/entity/index.ts b/packages/catalog-model/src/entity/index.ts index e267c607e1..572df63557 100644 --- a/packages/catalog-model/src/entity/index.ts +++ b/packages/catalog-model/src/entity/index.ts @@ -34,6 +34,7 @@ export { parseEntityName, parseEntityRef, serializeEntityRef, + stringifyEntityRef, } from './ref'; export { entityHasChanges, diff --git a/packages/catalog-model/src/entity/ref.ts b/packages/catalog-model/src/entity/ref.ts index bf34962d01..09660811f0 100644 --- a/packages/catalog-model/src/entity/ref.ts +++ b/packages/catalog-model/src/entity/ref.ts @@ -172,6 +172,7 @@ export function parseEntityRef( * special/reserved characters, it outputs the string form, otherwise it * outputs the compound form. * + * @deprecated Use `stringifyEntityRef` instead * @param ref The reference to serialize * @returns The same reference on either string or compound form */ @@ -212,6 +213,37 @@ export function serializeEntityRef( return `${kind ? `${kind}:` : ''}${namespace ? `${namespace}/` : ''}${name}`; } +/** + * Takes an entity or entity name/reference, and returns the string form of an + * entity ref. + * + * This function creates a canonical and unique reference to the entity, converting + * all parts of the name to lowercase and inserts the default namespace if needed. + * It is typically not the best way to represent the entity reference to the user. + * + * @param ref The reference to serialize + * @returns The same reference on either string or compound form + */ +export function stringifyEntityRef( + ref: Entity | { kind: string; namespace?: string; name: string }, +): string { + let kind; + let namespace; + let name; + + if ('metadata' in ref) { + kind = ref.kind; + namespace = ref.metadata.namespace ?? ENTITY_DEFAULT_NAMESPACE; + name = ref.metadata.name; + } else { + kind = ref.kind; + namespace = ref.namespace ?? ENTITY_DEFAULT_NAMESPACE; + name = ref.name; + } + + return `${kind.toLowerCase()}:${namespace.toLowerCase()}/${name.toLowerCase()}`; +} + /** * Compares an entity to either a string reference or a compound reference. *