@latelyjs/fetch-event-source
TypeScript icon, indicating that this package has built-in type declarations

0.0.4 • Public • Published

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();
    }
});

Readme

Keywords

Package Sidebar

Install

npm i @latelyjs/fetch-event-source

Weekly Downloads

3

Version

0.0.4

License

ISC

Unpacked Size

10.4 kB

Total Files

6

Last publish

Collaborators

  • laterly