• Stars
    star
    176
  • Rank 216,987 (Top 5 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 8 years ago
  • Updated over 5 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

[Deprecated] Subscription support for Relay Classic

Relay Subscriptions npm

Subscription support for Relay Classic.

PoC

Discord

Documentation

Guide

Installation

$ npm i -S react react-relay babel-relay-plugin
$ npm i -S relay-subscriptions

Network layer (API)

To use Relay Subscriptions, you need to provide a network layer with subscription support. This network layer needs to implement a sendSubscription method that takes a subscription request, calls the observer methods on the request when the subscription updates, and returns a disposable for tearing down the subscription.

A simple network layer that uses Socket.IO as the underlying transport looks like:

import Relay from 'react-relay/classic';
import io from 'socket.io-client';

export default class NetworkLayer extends Relay.DefaultNetworkLayer {
  constructor(...args) {
    super(...args);

    this.socket = io();
    this.requests = Object.create(null);

    this.socket.on('subscription update', ({ id, data, errors }) => {
      const request = this.requests[id];
      if (errors) {
        request.onError(errors);
      } else {
        request.onNext(data);
      }
    });
  }

  sendSubscription(request) {
    const id = request.getClientSubscriptionId();
    this.requests[id] = request;

    this.socket.emit('subscribe', {
      id,
      query: request.getQueryString(),
      variables: request.getVariables(),
    });

    return {
      dispose: () => {
        this.socket.emit('unsubscribe', id);
      },
    };
  }
}

For a full example, see the network layer in the TodoMVC example.

If your server uses GraphQL.js, graphql-relay-subscription provides helpers for implementing subscriptions. For a basic example, see the server and the schema in the TodoMVC example.

Environment (API)

Instead of using a standard Relay.Environment, use a RelaySubscriptions.Environment. This environment class adds subscription support to the standard Relay environment.

import RelaySubscriptions from 'relay-subscriptions';

import NetworkLayer from './NetworkLayer';

const environment = new RelaySubscriptions.Environment();
environment.injectNetworkLayer(new NetworkLayer());

Subscriptions (API)

Subclass the Subscription class to define subscriptions. This base class is similar to Relay.Mutation. A basic subscription looks like:

import Relay from 'react-relay/classic';
import { Subscription } from 'relay-subscriptions';

import Widget from '../components/Widget';

export default class WidgetSubscription extends Subscription {
  static fragments = {
    widget: () => Relay.QL`
      fragment on Widget {
        id
      }
    `,
  };

  getSubscription() {
    return Relay.QL`
      subscription {
        updateWidget(input: $input) {
          widget {
            ${Widget.getFragment('widget')}
          }
        }
      }
    `;
  }

  getConfigs() {
    return [{
      type: 'FIELDS_CHANGE',
      fieldIDs: {
        widget: this.props.widget.id,
      },
    }];
  }

  getVariables() {
    return {
      id: this.props.widget.id,
    };
  }
}

Due to an open issue (#12), for a RANGE_ADD subscription, you must manually request the __typename field on the edge in the payload.

For full examples, see the subscriptions in the TodoMVC example.

Containers (API)

For components with subscriptions, use RelaySubscriptions.createContainer instead of Relay.createContainer. Define your Relay fragments normally, including the fragments for any subscriptions you need, then define a subscriptions array of functions that create the desired subscriptions from the component's props.

import React from 'react';
import Relay from 'react-relay/classic';
import RelaySubscriptions from 'relay-subscriptions';

import WidgetSubscription from '../subscriptions/WidgetSubscription';

class Widget extends React.Component { /* ... */ }

export default RelaySubscriptions.createContainer(Widget, {
  fragments: {
    widget: () => Relay.QL`
      fragment on Widget {
        # ...
        ${WidgetSubscription.getFragment('widget')}
      }
    `,
  },

  subscriptions: [
    ({ widget }) => new WidgetSubscription({ widget }),
  ],
})

If you want to manually manage your subscription, the container also adds a subscribe method on props.relay, which takes a Subscription and an optional observer, and returns a disposable for tearing down the subscription.

TODO

  • Add tests (#1)
  • Automatically add __typename to query for RANGE_ADD subscriptions (#12)

Credits

Big thanks to @taion for cleaning up my mess, creating a really nice API and these amazing docs 🎉

More Repositories

1

react-router-relay

[Deprecated] Relay Classic integration for React Router
JavaScript
559
star
2

relay-hooks

Use Relay as React hooks
TypeScript
541
star
3

react-relay-network-modern

Relay Modern Network Layer with middlewares — cache, auth, retry, batch, logger, SSR
JavaScript
326
star
4

react-relay-network-layer

ReactRelayNetworkLayer with middlewares and query batching for Relay Classic.
JavaScript
276
star
5

found-relay

Relay integration for Found
JavaScript
276
star
6

relay-local-schema

Use Relay without a GraphQL server
JavaScript
253
star
7

relay-compiler-language-typescript

⛔️ Obsolete - A language plugin for Relay that adds TypeScript support, including emitting type definitions.
TypeScript
241
star
8

react-relay-network-modern-ssr

SSR middleware for react-relay-network-modern
JavaScript
67
star
9

Relay.swift

Relay for GraphQL, ported to Swift and SwiftUI
Swift
65
star
10

relay-compiler-webpack-plugin

Automatically run the Relay Compiler from Webpack
JavaScript
65
star
11

relay-query-lookup-renderer

Same as Relay Modern's QueryRenderer, but will check the store for data before fetching
JavaScript
52
star
12

fetch-multipart-graphql

Cross browser function to fetch and parse streaming multipart graphql responses
JavaScript
51
star
13

vscode-apollo-relay

Simple configuration of vscode-apollo for Relay projects.
TypeScript
49
star
14

react-relay-mutation

Higher-level React mutation API for Relay
TypeScript
40
star
15

relay-commit-mutation-promise

Promise wrapper for Relay Modern's commit mutation
JavaScript
27
star
16

typescript-relayjs-examples

RelayJS typescript examples
TypeScript
24
star
17

relay-connection-handler-plus

Relay connection handler with additional functionality
TypeScript
21
star
18

relay-context-provider

JavaScript
16
star
19

relay-graphql-js

Relay tooling based on graphql-js
TypeScript
15
star
20

tslint-plugin-relay

tslint plugin for relay-compiler-language-typescript tool
TypeScript
6
star