'How to call an event-handler after PUT/PATCHing data in json-server?

I have a json-server running in a small node.js project.

I can PATCH and PUT the existing data and will GET the updated values in return later. So far so good. But for some of these operations, I also need to broadcast an MQTT message with the updated object.

Of couse I could implement my own handlers all the way, like

server.put('/somepath', (req, res) => {
    data.something = req.body
    mqttClient.publish('somepath', JSON.stringify(data.something)
    res.status(200).send()
})

But I'd like to take advantage of the built in logic of the json-server that automatically mutates my data when doing POST/PATCH/PUT/DELETE requests and still be able to broadcast the new document over MQTT after the mutation is done.

Is that possible to do in a smarter generic way instead of implementing a request handler for each single endpoint?

Thanks in advance for any tips :)



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source