events-backend: add hub HTTP publish

Signed-off-by: Patrik Oldsberg <poldsberg@gmail.com>
This commit is contained in:
Patrik Oldsberg
2024-05-22 18:42:39 +02:00
parent ee52e38a04
commit ea4b912f93
2 changed files with 43 additions and 7 deletions
+23 -6
View File
@@ -95,12 +95,15 @@ backend.add(
);
const poll = async () => {
const res = await fetch(`${baseUrl}/hub/subscriptions/123`, {
headers: {
Authorization: `Bearer ${token}`,
'Content-Type': 'application/json',
const res = await fetch(
`${baseUrl}/hub/subscriptions/123/events`,
{
headers: {
Authorization: `Bearer ${token}`,
'Content-Type': 'application/json',
},
},
});
);
const data = res.status === 200 && (await res.json());
console.log(
@@ -109,9 +112,23 @@ backend.add(
);
poll();
};
poll();
setTimeout(() => {
console.log(`DEBUG: publishing!`);
fetch(`${baseUrl}/hub/events`, {
method: 'POST',
headers: {
Authorization: `Bearer ${token}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
topic: 'test',
payload: { herp: 'derp' },
}),
});
}, 500);
const ws = new WebSocket(`${baseUrl}/hub/connect`, {
headers: {
Authorization: `Bearer ${token}`,
@@ -399,8 +399,10 @@ export class EventHub {
router.use(express.json());
router.post('/events', hub.#handlePostEvents);
// Long-polling
router.get('/subscriptions/:id', hub.#handleGetSubscription);
router.get('/subscriptions/:id/events', hub.#handleGetSubscription);
router.put('/subscriptions/:id', hub.#handlePutSubscription);
return hub;
@@ -526,6 +528,23 @@ export class EventHub {
}
};
#handlePostEvents: Handler = async (req, res) => {
const credentials = await this.#httpAuth.credentials(req, {
allow: ['service'],
});
await this.#store.publish({
params: {
topic: req.body.topic,
eventPayload: req.body.payload,
},
subscriberIds: [],
});
this.#logger.info(`Published event to '${req.body.topic}'`, {
subject: credentials.principal.subject,
});
res.status(201).end();
};
#handleGetSubscription: Handler = async (req, res) => {
const credentials = await this.#httpAuth.credentials(req, {
allow: ['service'],