UNPKG

@das3mical/adonis-mercure

Version:

A simple AdonisJS provider to interact with Mercure hub

49 lines (48 loc) 1.58 kB
import jws from 'jws'; import got from 'got'; export class Mercure { #config; constructor(config) { this.#config = config; } generate(payload) { return new Promise((resolve, reject) => { jws .createSign({ payload: { mercure: payload }, secret: this.#config.jwt.secret, header: { alg: this.#config.jwt.alg }, }) .on('error', reject) .on('done', resolve); }); } async send(topics, data = {}, isPrivate = false) { topics = Array.isArray(topics) ? topics : [topics]; const form = new URLSearchParams(); topics.forEach((topic) => form.append('topic', topic)); form.append('data', JSON.stringify(data)); if (isPrivate) { form.append('private', 'on'); } try { const response = await got.post(this.#config.endpoint, { headers: { 'Authorization': `Bearer ${this.#config.adminToken}`, 'Content-Type': 'application/x-www-form-urlencoded', }, body: form.toString(), }); return response; } catch (error) { if (error.response) { console.error('Error response:', error.response.body); console.error('Status code:', error.response.statusCode); } else { console.error('Error message:', error.message); } } } }