Set and Get Metadata
Set Metadata
To define metadata on a class or its elements, use meta(). It accepts the following arguments:
key: name of metadata identifier. Can also be a path (seeset).value: arbitrary data. Can be a primitive value, an object, or a function.
To obtain metadata, use the getMeta() method. You can also use getAllMeta(), if you wish to obtain all available metadata for a target class.
import { meta } from '@aedart/support/meta';
@meta('service_alias', 'locationSearcher')
class Service
{
@meta('name', 'Name of service') name;
@meta('fetch.desc', 'Fetches resource via a gateway')
@meta('fetch.dependencies', [ 'my-gateway' ])
async fetch(gateway)
{
// ...implementation not shown...
}
}
Get Metadata
Use getMeta() or getAllMeta() to retrieve metadata.
import { getMeta, getAllMeta } from '@aedart/support/meta';
const service = new Service();
const desc = getMeta(Service, 'fetch.desc');
const dependencies = getMeta(Service, 'fetch.dependencies');
// Or, obtain all metadata
const allMeta = getAllMeta(Service);
Metadata Availability
Depending on the kind of element that is decorated, metadata might only become available for reading, after a new class instance has been instantiated. This is true for the following elements:
methodgettersetterfieldaccessor
Static Elements
If an element is declared as static, then it's metadata becomes available as soon as the class has been defined.
Default Value
The getMeta() method also offers a defaultValue argument, which is returned, in case that a metadata value does not exist for a given identifier.
const description = getMeta(Service, 'fetch.desc', 'N/A');
Callback
If you need to create more advanced metadata, you can specify a callback as the first argument for the meta() decorator method. When using a callback you gain access to the target that is being decorated, as well as the decorator context. The callback MUST return an object that contains a key and a value property.
import { meta } from '@aedart/support/meta';
class Service {
@meta((target, context) => {
return {
key: context.name,
value: '...'
}
})
delegateTo(gateway) {
// ...not shown...
}
}
Although the above example is a bit cumbersome to read, it shows a simple way to defined metadata for a method, which utilises the decorator context. If you wish, you can use this approach to create your own specialised meta decorators. Doing so can also improve the readability of your class. Consider the following example:
import { meta } from '@aedart/support/meta';
function delegateMeta() {
return meta((target, context) => {
return {
key: context.name,
value: '...'
}
});
}
class Service {
@delegateMeta()
delegateTo(gateway) {
// ...not shown...
}
}