Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(nest): metadata decorator #37

Merged
merged 1 commit into from
Sep 27, 2024
Merged

feat(nest): metadata decorator #37

merged 1 commit into from
Sep 27, 2024

Conversation

CarsonF
Copy link
Member

@CarsonF CarsonF commented Sep 27, 2024

This abstracts the reflect-metadata library to provide strictly typed decorators with an easier to use API.

Simple marker tag

const Tag = createMetadataDecorator();

@Tag()
class Foo {}

Tag.get(Foo) // => true | undefined
// === true

Add data to be stored

const Tag = createMetadataDecorator({
  // This function declares the args that are exposed to the decorator
  // And the return type declares the stored value shape
  setter: (name: string, opts?: { age?: number }) => ({
    name,
    age: opts?.age,
  })
});

@Tag('Bob', { age: 50 })
class Foo {}

Tag.get(Foo) // => { name: string, age?: number } | undefined
// === { name: 'Bob', age: 50 }

Labels with merging

const Label = createMetadataDecorator({
  type: ['class'] // only allow for classes
  setter: (label: string) => [label],
  merge: ({ next, previous }) => [...previous ?? [], ...next],
});

@Label('A')
@Label('B')
class Foo {}

Label.get(Foo) // => string[] | undefined
// === ['B', 'A']

Copy link

@bryanjnelson bryanjnelson left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Those tests... 🤤

@CarsonF CarsonF merged commit c30a2f2 into master Sep 27, 2024
2 checks passed
@CarsonF CarsonF deleted the nest/metadata-decorator branch September 27, 2024 20:33
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants