Skip to content

Instantly share code, notes, and snippets.

@jbaxleyiii
Last active April 3, 2016 16:17
Show Gist options
  • Save jbaxleyiii/e899fe74842b7488657617e43c9a30fe to your computer and use it in GitHub Desktop.
Save jbaxleyiii/e899fe74842b7488657617e43c9a30fe to your computer and use it in GitHub Desktop.
Middleware for the apollo client's network interface
import { ApolloClient } from "apollo-client"
import { createNetworkInterface } from "apollo-client/lib/src/networkInterface"
// Middleware functions can perform the following tasks:
//
// - Execute any code.
// - Make changes to the request and request option objects.
// - Call the next middleware function in the stack.
//
// modeled after express 4.0
const heighliner = createNetworkInterface('http://localhost:8888/');
interface MiddlewareRequest {
request: Request;
options: RequestInit;
}
// option 1, generic middleware that can modify the options of the request
const tokenMiddleware = (request: MiddlewareRequest, next: function): void => {
// this would be called on each request and has the option to modify the headers
// this doesn't return a value, but rather modifies the request inline.
// that feels gross but I don't know of another way to do next() unless you pass
// the request into next? which also seems odd
};
// option 2, authorization sugaring of option 1 that only modifies the headers
// and defaults to setting an 'Authorization' header.
heighliner.authorize('token': string, /* optional key name for token : string*/);
heighliner.removeAuthorization(/* probably just a null value here? */);
// the middleware would be on the networkInterface itself
// should this be an array? or allow for multiple arugments to be passed as args
// e.g. `use(middleware1, middleware2, etc)
heighliner.use(tokenMiddleware);
const apolloClient = new ApolloClient({
networkInterface: heighliner,
apolloStore: apolloStore
});
// if the default networkInterface is used, you can do soemthing like this
const client = new ApolloClient();
const { networkInterface } = client;
networkInterface.use(/* middleware */);
networkInterface.authorize('token', /* optional key name for token */);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment