Code Monkey home page Code Monkey logo

sse-z's Introduction

SSE-Z

A slim, easy-to-use wrapper around SSE.

Installation

npm install sse-z

Usage

import { Subscription } from "sse-z";

const subscription = new Subscription({
  url: "http://localhost:8080/sse",
  searchParams: {
    foo: "bar",
  },
  onNext: (data: string) => {
    console.log(data);
  },
});

// stop the subscription
subscription.unsubscribe();

Types

class Subscription {
  eventSource: EventSource;

  constructor(options: SSESubscriptionOptions);

  unsubscribe(): void;
}

interface SubscriptionOptions {
  // Additional options to pass to the constructor of the underlying EventSource instance.
  eventSourceOptions?: {
    withCredentials?: boolean;
    [key: string]: any;
  };

  // Indicates the subscription should expect keep alive events to be sent by the server.
  // If an event is not received inside the provided interval, a reconnection attempt will be made.
  // The provided interval should be greater than the actual frequency at which the server sends
  // the events to allow for network latency.
  keepAlive?: {
    // Defaults to "keepAlive";
    eventType?: string;
    intervalMs: number;
  };

  // Called when the connection is terminated by calling unsubscribe.
  onComplete?: () => void;

  // Called when an error occurs. Note that this callback will be called each time the connection
  // is lost, so it should not be used to indicate a critical error occurred.
  onError?: (error: Error) => void;

  // Callback called whenever an event is pushed.
  onNext?: (data: string) => void;

  // Any URL query parameters to attach to the URL.
  searchParams?: {
    [key: string]: string;
  };

  // The URL of the endpoint to fetch requests from.
  url: string;
}

Integration with GraphQL Clients

Relay

import {
  Environment,
  Network,
  Observable,
  SubscribeFunction,
} from "relay-runtime";
import { Subscription } from "sse-z";

const subscribe: SubscribeFunction = (operation, variables) => {
  return Observable.create((sink) => {
    return new Subscription({
      url: 'http://localhost:8080/graphql',
      searchParams: {
        operationName: operation.name,
        query: operation.text,
        variables: JSON.stringify(variables),
      },
      eventSourceOptions: {
        // Ensure cookies are included with the request
        withCredentials: true,
      },
      onNext: (data) => {
        sink.next(JSON.parse(data));
      },
    });
  });
};

const environment = new Environment({
  ...
  network: Network.create(fetchQuery, subscribe),
});

Apollo Client

import { ApolloLink, Operation, FetchResult, Observable } from "@apollo/client";
import { print } from "graphql";
import { Subscription, SubscriptionOptions } from "sse-z";

class SSELink extends ApolloLink {
  options: SSESubscriptionOptions;

  constructor(options: SubscriptionOptions) {
    super();
    this.options = options;
  }

  public request({
    query,
    variables,
    operationName,
  }: Operation): Observable<FetchResult> {
    return new Observable((sink) => {
      const subscription = new Subscription({
        ...options,
        searchParams: {
          query: print(operation.query),
          variables: JSON.stringify(variables),
          operationName,
        },
        onNext: (data) => {
          sink.next(JSON.parse(data));
        },
      });

      return () => subscription.unsubscribe();
    });
  }
}

const link = new SSELink({
  url: "http://localhost:8080/graphql",
  eventSourceOptions: {
    // Ensure cookies are included with the request
    withCredentials: true,
  },
});

sse-z's People

Contributors

danielrearden avatar n1ru4l avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.