0.0.4 • Published 5 months ago

@latelyjs/fetch-event-source v0.0.4

Weekly downloads
-
License
ISC
Repository
github
Last release
5 months ago

Fetch Event Source

基于fetch 获取流式数据

Install

npm install @latelyjs/fetch-event-source

Usage

import { fetchEventSource } from '@latelyjs/fetch-event-source';

await fetchEventSource('/api/sse', {
    onmessage(msg) {
        console.log(msg.data);
    }
});

Example

import { fetchEventSource, EventStreamContentType} from '@latelyjs/fetch-event-source';

const controller = new AbortController();

const finish = () => {
    console.log('finish') 
};

const getHeaders = () => {
  const headers: Record<string, string> = {
    "Content-Type": "application/json",
    "x-requested-with": "XMLHttpRequest",
  };
  const authHeader = "Authorization";

  const token = ""; //token

  headers[authHeader] = `${token}`;
}

const requestPayload = {};

fetchEventSource('/api/sse', 
    {
        method: "POST",
        body: JSON.stringify(requestPayload),
        signal: controller.signal,
        headers: getHeaders(),
    },
   {
    async onopen(response) {
       if (
            !response.ok ||
            !response.headers
                .get("content-type")
                ?.startsWith(EventStreamContentType) ||
              response.status !== 200
        ) {
              finish();
        }
    },
    onmessage(msg) {
        // msg
        console.log(msg.data);
    },
    onclose() {
        //Abort
    },
    onerror(error) {
        //error
    },
    onfinily(){
        //end
        finish();
    }
});
0.0.4

5 months ago

0.0.3

5 months ago

0.0.2

5 months ago

0.0.1

5 months ago