tulios / mappersmith

is a lightweight rest client for node.js and the browser
https://www.npmjs.com/package/mappersmith
MIT License
334 stars 72 forks source link

Server-sent events client implementation #372

Open MykhailoMatiiasevychKlarna opened 1 year ago

MykhailoMatiiasevychKlarna commented 1 year ago

Server-sent events client implementation

Purpose

I want to bump with the community and understand if this feature would be interesting and useful in scope of mappersmith.

Docs

https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events

Use case

Even though the technology is well known and supported by browsers it seems to be rarely used in backend-2-backend communication. With the boom of chatGPT this become a case as it is supporting streaming using Server-sent events: https://platform.openai.com/docs/api-reference/chat/create

Suggested implementation

Currently payload is available as a text when the request is completed. My implementation suggestion would be to pass eventEmitter as a parameter to resource method and emit events from inside mappersmith on every new chunk of data.

import { EventEmitter } from 'node:events';
const events = new EventEmitter();

events.on('data', (data) => {
  console.log(data);
})

client.Resource.method({ eventEmitter: events })
klippx commented 1 year ago

I think it looks very interesting and sounds like a fun project 👍
Since gateways are configurable I guess ideally it should be implemented in both HTTP and Fetch gateways, even though HTTP is the default it is not uncommon to override it to Fetch for node:

import forge, { configs } from 'mappersmith';
import fetchGateway from 'mappersmith/gateway/fetch';
import fetch from 'node-fetch';

configs.gateway = fetchGateway;
configs.fetch = fetch;
const client = forge({ ... })