Giter VIP home page Giter VIP logo

ddp-apollo's Introduction

DDP-Apollo

DDP-Apollo leverages the power of DDP for GraphQL queries and subscriptions. Meteor developers do not need an HTTP server or extra websocket connection, because DDP offers all we need and has been well tested over time.

  • DDP-Apollo is one of the easiest ways to get GraphQL running for Meteor developers
  • Works with the Meteor accounts packages out of the box, giving a userId in your resolvers
  • Method calls and collection hooks will have this.userId when called within your resolvers
  • Doesn’t require an HTTP server to be setup, like with express, koa or hapi
  • Supports GraphQL Subscriptions out-of-the-box
  • Doesn’t require an extra websocket for GraphQL Subscriptions, because DDP already has a websocket
  • Already have a server setup? Use DDPSubscriptionLink stand-alone for just Subscriptions support. Read more

Because it's "just another Apollo Link":

  • It works with Apollo Dev Tools
  • It's easy to combine with other Apollo Links
  • It's front-end agnostic

Checkout this starter kit to see Meteor, Apollo, DDP and React all work together.

Note: DDP-Apollo works with all front-ends, not just React

Build Status Greenkeeper badge

Contents

Installation

meteor add swydo:ddp-apollo
meteor npm install --save graphql apollo-link apollo-client apollo-cache-inmemory

Client setup

This package gives you a DDPLink for your Apollo Client.

import ApolloClient from 'apollo-client';
import { DDPLink } from 'meteor/swydo:ddp-apollo';
// Choose any cache implementation, but we'll use InMemoryCache as an example
import { InMemoryCache } from 'apollo-cache-inmemory';

export const client = new ApolloClient ({
  link: new DDPLink(),
  cache: new InMemoryCache()
});

Options

  • connection: The DDP connection to use. Default Meteor.connection.
  • method: The name of the method. Default __graphql.
  • publication: The name of the publication. Default __graphql-subscriptions.
  • ddpRetry: Retry failed DDP method calls. Default true. Switch off and use apollo-link-retry for more control.
// Pass options to the DDPLink constructor
new DDPLink({
  connection: Meteor.connection
});

Server setup

The server will add a method that will be used by the DDP Apollo Link.

import { schema } from './path/to/your/executable/schema';
import { setup } from 'meteor/swydo:ddp-apollo';

setup({
  schema,
  ...otherOptions
});

Options

  • schema: The GraphQL schema. Default undefined. Required.
  • context: A custom context. Either an object or a function returning an object. Optional.
  • method: The name of the method. Default __graphql.
  • publication: The name of the publication. Default __graphql-subscriptions.

Custom context

To modify or overrule the default context, you can pass a context object or function to the setup:

// As an object:
const context = {
  foo: 'bar'
}

// As a function, returning an object:
const context = (currentContext) => ({ ...currentContext, foo: 'bar' });

// As an async function, returning a promise with an object
const context = async (currentContext) => ({ ...currentContext, foo: await doAsyncStuff() });

setup({
  schema,
  context,
});

GraphQL subscriptions

Subscription support is baked into this package. Simply add the subscriptions to your schema and resolvers and everything works.

# schema.graphql
type Query {
  name: String
}

type Subscription {
  message: String
}

Setting up PubSub

meteor npm install --save graphql-subscriptions
import { PubSub } from 'graphql-subscriptions';

// The pubsub mechanism of your choice, for instance:
// - PubSub from graphql-subscriptions (in-memory, so not recommended for production)
// - RedisPubSub from graphql-redis-subscriptions
// - MQTTPubSub from graphql-mqtt-subscriptions
const pubsub = new PubSub();

export const resolvers = {
  Query: {
    name: () => 'bar',
  },
  Subscription: {
    message: {
      subscribe: () => pubsub.asyncIterator('SOMETHING_CHANGED'),
    },
  },
};

// Later you can publish updates like this:
pubsub.publish('SOMETHING_CHANGED', { message: 'hello world' });

See graphql-subscriptions package for more setup details and other pubsub mechanisms. It also explains why the default PubSub isn't meant for production.

Using DDP only for subscriptions

If you already have an HTTP server setup and you are looking to support GraphQL Subscriptions in your Meteor application, you can use the DDPSubscriptionLink stand-alone.

import { ApolloClient } from 'apollo-client';
import { split } from "apollo-link";
import { HttpLink } from "apollo-link-http";
import { DDPSubscriptionLink, isSubscription } from 'meteor/swydo:ddp-apollo';
import { InMemoryCache } from 'apollo-cache-inmemory';

const httpLink = new HttpLink({ uri: "/graphql" });
const subscriptionLink = new DDPSubscriptionLink();

const link = split(
  isSubscription,
  subscriptionLink,
  httpLink,
);

export const client = new ApolloClient ({
  link,
  cache: new InMemoryCache()
});

Rate limiting GraphQL calls

Meteor supports rate limiting for DDP calls. This means you can rate limit DDP-Apollo as well!

meteor add ddp-rate-limiter
import { DDPRateLimiter } from 'meteor/ddp-rate-limiter';

// Define a rule that matches graphql method calls.
const graphQLMethodCalls = {
  type: 'method',
  name: '__graphql'
};

// Add the rule, allowing up to 5 messages every 1000 milliseconds.
DDPRateLimiter.addRule(graphQLMethodCalls, 5, 1000);

See DDP Rate Limit documentation.

HTTP support

There can be reasons to use HTTP instead of a Meteor method. There is support for it built in, but it requires a little different setup than the DDP version.

Installation

We'll need the HTTP link from Apollo and body-parser on top of the default dependencies:

meteor npm install apollo-link-http body-parser

Client setup

import ApolloClient from 'apollo-client';
// Use the MeteorLink instead of the DDPLink
// It uses HTTP for queries and Meteor subscriptions for GraphQL subscriptions
import { MeteorLink } from 'meteor/swydo:ddp-apollo';
import { InMemoryCache } from 'apollo-cache-inmemory';

export const client = new ApolloClient ({
  link: new MeteorLink(),
  cache: new InMemoryCache()
});

Server setup

import { schema } from './path/to/your/executable/schema';
import { setupHttpEndpoint, createGraphQLPublication } from 'meteor/swydo:ddp-apollo';

setupHttpEndpoint({
  schema,
  ...otherOptions,
});

// For subscription support (not required)
createGraphQLPublication({ schema });

Options

  • schema: The GraphQL schema. Default undefined. Required.
  • context: A custom context. Either an object or a function returning an object. Optional.
  • path: The name of the HTTP path. Default /graphql.
  • engine: An Engine instance, in case you want monitoring on your HTTP endpoint. Optional.
  • authMiddleware: Middleware to get a userId and set it on the request. Default meteorAuthMiddleware, using a login token.
  • jsonParser: Custom JSON parser. Loads body-parser from your node_modules by default and uses .json().

Sponsor

Swydo

Want to work with Meteor and GraphQL? Join the team!

ddp-apollo's People

Contributors

csillag avatar greenkeeper[bot] avatar jamiter avatar

Watchers

 avatar  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.