dxfrontier/cds-ts-dispatcher

[FEATURE] New `@OnEvent()` decorator

Closed this issue ยท 9 comments

Description

Let's say you are emitting custom event with srv.emit('OrderedBook', someData) and you'd like to add a handler for this event. Right now you have to subscribe to the event manually by writing code like the following:

@ServiceLogic()
class MyService {
  
  @Inject(SRV) 
  private readonly srv: Service;

  constructor() {
    this.srv.on('OrderedBook', data => this.onOrderedBook(data));
  }
  
  onOrderedBook(data: OrderedBookData) {
    // TODO: implement me
  }
}

It would be nice if there was a decorator like @OnEvent('OrderedBook') which would reduce the amount of boilerplate code you need to write to subscribe to custom events.

Suggested solution

@ServiceLogic()
class MyService {
  
  @OnEvent('OrderedBook')
  onOrderedBook(data: OrderedBookData) {
    // TODO: implement me
  }
}

Hi Thomas,

Great new feature, I am currently on vacation till 15th of January, after my return I will start working on this new decorator.

Happy new year,
Daniel

No worries, Daniel.
Have a great vacation and happy new year ๐Ÿ™‚

Thank you @dragolea
Looks good ๐Ÿ™‚

@dragolea on related note: would it be possible to use @OnEvent() to handle CAP special error event? Or should there be specialized @OnError() decorator?
cap-js/cds-types#9

I remember I tried to implement it at the beginning of this project but I was not able to find an overload for the .on error

Below we see all the overloads of the .on handler

  on<T extends Constructable>(eve: types.event, entity: T, handler: CRUDEventHandler.On<InstanceType<T>, InstanceType<T> | void | Error>): this
  on<F extends CdsFunction>(boundAction: F, service: string, handler: ActionEventHandler<F['__parameters'], void | Error | F['__returns']>): this
  on<F extends CdsFunction>(unboundAction: F, handler: ActionEventHandler<F['__parameters'], void | Error | F['__returns']>): this
  on(eve: types.event, entity: types.target, handler: OnEventHandler): this
  on(eve: types.event, handler: OnEventHandler): this

I remember I've tried to see if the last overload is working but something didn't. ( on(eve: types.event, handler: OnEventHandler): this)

I think you're referring to this error handler https://cap.cloud.sap/docs/node.js/core-services#srv-on-error

Were you able to find the overload in TS for this error handler?

It's coming soon to TS. The new types were just merged last week: cap-js/cds-types#9

@hakimio @dragolea: Lets open a new issue refererring to that PR. We'll get a release notification once its available.

@hakimio feel free to create a new issue for @OnError decorator
Thank you