Skip to content

Instantly share code, notes, and snippets.

@akoenig
Last active March 3, 2018 20:02
Show Gist options
  • Save akoenig/caa543846f81765812ef8f996dd655ac to your computer and use it in GitHub Desktop.
Save akoenig/caa543846f81765812ef8f996dd655ac to your computer and use it in GitHub Desktop.
Medium: M2M in GraphQL context (Factory function for creating the binding)
import { readFile } from "fs";
import { join as joinPath } from "path";
import { promisify } from "util";
import fetch from "node-fetch";
import { makeRemoteExecutableSchema } from "graphql-tools";
import { createHttpLink } from "apollo-link-http";
import { Binding as TelemetryBinding } from "./telemetry";
/**
* Factory function for instantiating the Telemetry binding.
*
* @param endpoint {string} The endpoint of the Telemetry API
* @returns {Binding}
*
*/
const createTelemetryBinding = async (
endpoint: string
): Promise<TelemetryBinding> => {
// 1. Read the type defs from our downloaded remote schema.
const readTypeDefs = promisify(readFile);
const typeDefsPath = joinPath(__dirname, "telemetry.graphql");
const typeDefs = await readTypeDefs(typeDefsPath, {
encoding: "utf8"
});
// 2. Create a HTTP link. This component is responsible for
// perfoming the actual HTTP communication. We use `node-fetch`
// as the underlying transport mechanism.
const link = createHttpLink({ uri: endpoint, fetch });
// 3. Combine the type definitions with the HTTP link
// and make the schema "executable".
const schema = makeRemoteExecutableSchema({
schema: typeDefs,
link
});
// 4. Instantiate the generated binding by passing
// the executable remote schema.
return new TelemetryBinding({
schema
});
};
export { createTelemetryBinding };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment