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

Backend subscriptions (for event driven apps) or API route hooks #212

Open
alexkreidler opened this issue Jul 1, 2023 · 1 comment
Open

Comments

@alexkreidler
Copy link

Is your feature request related to a problem? Please describe.
I'd like to add some additional backend logic that happens whenever a POST /api/myEntity or another operation on that entity is requested. It should be able to receive the body data and do some processing, likely asynchronously, while Remult persists the entity to the database.

Describe the solution you'd like
One option is like the Live Queries/subscriptions feature, where I register a myEntityRepo.subscribe(({items, applyChanges, changes}) => { // my logic }) handler. Likely using the changes field I can handle different events corresponding to various HTTP verbs.

Another option would be "hooks" for the regular CRUD API routes, like:

  @BackendMethod({ hook: true })
  static async insert(entity: Entity) {
    const entityRepo = remult.repo(Entity)

    await Promise.all([
      entityRepo.save(entity),
      async () => {
        kafka.send({entity})
      }
    ])

    //  or just
    await Promise.all([
      entityRepo.insert(entity),
      async () => {
        kafka.send({entity})
      }
    ])
  }

  // or

  static async beforeInsert(entity: Entity) {
    entity.name = entity.name.toUpperCase();
    return entity
  }

Describe alternatives you've considered
I looked at BackendMethods, but AFAICT I'd need to add duplicate API routes for every action I wanted to override, breaking the uniform HTTP and remult frontend library interfaces. I'd like to be able to override those routes to perform slightly different logic but still have the easy default action as an ideally one-line function call.

@yoni-rapoport
Copy link
Collaborator

yoni-rapoport commented Jul 2, 2023

Try using the Entity lifecycle hooks saving / saved of the options object sent to @Entity.

See example here:
https://github.com/remult/crm-demo/blob/master/src/Contacts/ContactNote.entity.ts#L11

And if you want to know if the Entity object being saved is new (an API POST request) use this:

saving: async e => {
   const isNew = getEntityRef(e).isNew()
}

(we're working on making this easier to do...)

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

No branches or pull requests

2 participants