UNPKG

@das3mical/adonis-mercure

Version:

A simple AdonisJS provider to interact with Mercure hub

53 lines (52 loc) 1.81 kB
export class FakeMercure { #sent = []; #tokens = []; async generate(payload) { this.#tokens.push(payload); return 'fake-token'; } async generateSubscribeToken(topics) { return this.generate({ subscribe: topics }); } async send(topics, data = {}, isPrivateOrOptions = false) { const topicList = Array.isArray(topics) ? topics : [topics]; const options = typeof isPrivateOrOptions === 'boolean' ? { private: isPrivateOrOptions } : isPrivateOrOptions; this.#sent.push({ topics: topicList, data, options }); return new Response('1', { status: 200 }); } async ping() { return true; } assertSent(topic, data) { const match = this.#sent.find((msg) => { if (!msg.topics.includes(topic)) return false; if (!data) return true; return JSON.stringify(msg.data) === JSON.stringify(data); }); if (!match) { const found = this.#sent.map((m) => m.topics.join(', ')).join('; ') || 'nothing'; throw new Error(`Expected a message on topic "${topic}" but found: [${found}]`); } } assertNotSent(topic) { const match = this.#sent.find((msg) => msg.topics.includes(topic)); if (match) { throw new Error(`Expected no message on topic "${topic}" but one was found`); } } assertNothingSent() { if (this.#sent.length > 0) { const topics = this.#sent.map((m) => m.topics.join(', ')).join('; '); throw new Error(`Expected nothing to be sent but found messages on: [${topics}]`); } } getSent() { return [...this.#sent]; } clear() { this.#sent = []; this.#tokens = []; } }