capnp-ts
capnp-ts copied to clipboard
Feature Request: Hooks for annotations when compiling ts/js or turn them into Decorators?
So that extra logic may be implemented when annotations are provided in the schema.
annotation foo(struct, enum) :Text;
struct ClassName $foo("bar") {
id @0 :UInt32;
}
The possible targets for an annotation are: file, struct, field, union, group, enum, enumerant, interface, method, parameter, annotation, const. You may also specify * to cover them all.
The annotation value may also be in other types not just simple text/int can take multiple parameters.
For classes and properties annotations could be turned into Decorators. https://github.com/jayphelps/core-decorators https://www.typescriptlang.org/docs/handbook/decorators.html
Useful to do things such as;
- hiding or blanking out properties before sending a message elsewhere
- generate a method that copies values to a struct appropriate to send to front end users
- implementing acls
- add custom methods & properties
- wrapping methods or adding getters/setters to properties.
- deprecate?
Decorators outside of the core-decorators or standard ones, would probably have to know how to import/require the appropriate decorator.
Option 1: Possibly an environment variable to list modules to load for processing annotations.
An event emitter for each thing could be fired listing all of the annotations.
Option 2: Export the annotations on each thing as a property, then when the scripts are required/imported it would be the responsibility of the loading code to iterate over them and make any modifications to the javascript objects as needed in runtime.
Could be stored on the _capnp.
Could result in output such as.
ClassName.annotations = {
"foo": "bar"
}
const { ClassName } = require('ClassName.capnp.js');
for (let [annotation, value] of Object.entries(ClassName.annotations)) {
if (annotation === 'foo') {
// Add something custom to do something with the annotation and its value.
ClassName.prototype.doFoo = function doFoo() {
console.log(value)
}
}
}
And later call something like
var c = new ClassName();
c.doFoo();
Outputting the annotations would allow wrapping any generated methods as needed or adding new methods at runtime.
Decorators or storing the annotations in exported code is a useful feature. Although it should probably be an optional thing.
What would be an appropriate implementation?