'make it possible to register webhook to API
I'm fairly new to webhooks and need to make it possible to register a webhook to an API that I'm creating. I use schemas to create and store data. I want the webhook to emit an event whenever a new 'student' object is created from the schema. I want the user to able to send a webhook request to https://localhost:8080/api/webhook containing a hook-secret in the header and along with the URL, to which the emit event will be sent, in the body. If I create an object from, say a 'subscriber'-schema for each webhook, how should I go about emitting the event to all webhooks?
I'm writing in Vanilla JS. I'm using Express and Socket.io for the server. MongoDB as database.
Can I use res.io.emit() to do it? If so, how do I tell the function where to send the emit event?
This is how I currently register a subscriber/webhook:
export class WebHook {
authorize (req, res, next) {
if (req.headers['x-app-secret'] !== process.env.HOOK_SECRET) {
res.status(403).send('incorrect hook secret')
return
}
next()
}
async registerSubscriber (req, res, next) {
try {
// Creates a new subscriber object.
const subscriber = await Subscriber.insert(req.body, req.user).then(response => {
return response
})
res.status(200).end()
} catch (error) {
let err = error
err = createError(500)
err.innerException = error
next(error)
}
}
}
An this is the function for how a new student object is created, and where I want all the subscribers to be notified:
async create (req, res, next) {
try {
// Creates a new student object.
const student = await Student.insert(req.body).then(response => {
return response
})
// SOMETHING LIKE "res.io.emit()" SHOULD HAPPEN HERE:
res
.status(201)
.send('Accepted')
.json(student)
} catch (error) {
let err = error
err = createError(500)
err.innerException = error
next(error)
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
