How to use apollo-client - 10 common examples

To help you get started, we’ve selected a few apollo-client examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github flow-typed / flow-typed / definitions / npm / apollo-client_v2.x.x / test_apollo-client_v2.x.x.js View on Github external
// @flow

import { ApolloClient, ApolloLink, ApolloCache } from "apollo-client";
import { describe, it } from "flow-typed-test";
import ApolloClientDefault from "apollo-client";

const link = new ApolloLink();
const cache = new ApolloCache();

describe("apollo-client", () => {
  describe("ApolloClient initialization", () => {
    it("passes when passed correct configuration", () => {
      new ApolloClient({
        link,
        cache
      });
    });

    it("query function passes", async () => {
      const client = new ApolloClient({
        link,
        cache
      });
      const result = await client.query({
github fusionjs / fusionjs / fusion-plugin-apollo / src / __tests__ / integration.node.js View on Github external
async function testApp(el, {typeDefs, resolvers}, enhanceApp) {
  const port = await getPort();
  const endpoint = `http://localhost:${port}/graphql`;
  const app = new App(el);
  const schema = makeExecutableSchema({typeDefs, resolvers});
  const client = new ApolloClient({
    cache: new InMemoryCache({
      addTypename: false,
    }).restore({}),
    link: new HttpLink({
      endpoint,
      fetch: async (url, options) => {
        // required since the url here is only the path
        const result = await fetch(endpoint, options);
        return result;
      },
    }),
  });
  app.enhance(RenderToken, ApolloRenderEnhancer);
  app.register(GraphQLSchemaToken, schema);
  app.register(ApolloClientToken, ApolloClientPlugin);
  if (enhanceApp) {
github MacKentoch / react-redux-graphql-apollo-bootstrap-webpack-starter / src / server / SSR / src / middleware / ssr.js View on Github external
export default async function serverRender(req, res) {
  const location = req.url;
  const apolloClient = new ApolloClient({
    ssrMode: true,
    link: new HttpLink({ uri, fetch }),
    cache: new InMemoryCache(),
  });
  const context = {};
  let store = configureStore();
  const sheet = new ServerStyleSheet();

  console.log('serverRendering');

  // just for demo, replace with a "usefull" async. action to feed your state
  try {
    const { info } = await fakeFetch();
    const currentTime = format(new Date());
    const currentState = store.getState();
github bkinsey808 / graphql-fullstack-seed / client / src / app / app-module / client.ts View on Github external
applyMiddleware(req, next) {
    if (!req.options.headers) {
      req.options.headers = {};  // Create the header object if needed.
    }
    const token = AuthService.getJwtToken();
    if (token) {
      req.options.headers['authorization'] = AuthService.getJwtToken();
      console.log('got token: ', token);
    } else {
      console.log('did not get token', console.log(localStorage.getItem('id_token')));
    }
    next();
  }
}]);

const client = new ApolloClient({ networkInterface });

export function getClient(): ApolloClient {
  return client;
}
github genie-team / graphql-genie / src / main.ts View on Github external
// 	_root: any,
	// 	_args: { [key: string]: any },
	// 	_context: any,
	// 	_info: GraphQLResolveInfo,
	// ): any => {
	// 	const selections = computeIncludes(_info.operation.selectionSet.selections[0], 'GraphQLDirective');
	// 	console.info('selections');
	// 	console.info(selections);
	// 	console.info(JSON.stringify(selections));
	// 	console.log(_root);
	// 	console.log(_args);
	// 	console.log(_context);
	// 	console.log(_info);
	// });
	// addResolvers('GraphQLDirective', resolversMap);
	const client = new ApolloClient({
		link: new SchemaLink({ schema: schema }),
		cache: new InMemoryCache(),
		connectToDevTools: true
	});
	client.initQueryManager();

const createPost = gql`
	mutation createPost($title: String!) {
		createPost(title: $title) {
			id
		}
	}
`;

const createUser = gql`
mutation createUser($name: String!) {
github ilyaskarim / apollo-graphql-chat / client / src / Apollo.js View on Github external
});

// using the ability to split links, you can send data to each link
// depending on what kind of operation is being sent
export const link = split(
  // split based on operation type
  ({ query }) => {
    const { kind, operation } = getMainDefinition(query);
    return kind === 'OperationDefinition' && operation === 'subscription';
  },
  wsLink,
  httpLink,
);

// Instantiate client
export const client = new ApolloClient({
  link,
  uri: GRAPHQL_URI,
  cache: new InMemoryCache()
})
github coralproject / talk / client / coral-framework / services / client.js View on Github external
// To debug queries add print(req.request.query) and import it from graphql/language/printer
        // console.log(print(req.request.query));
        next();
      },
    },
  ]);

  const networkInterfaceWithSubscriptions = addGraphQLSubscriptions(
    networkInterface,
    wsClient
  );

  const client = new ApolloClient({
    connectToDevTools: true,
    addTypename: true,
    fragmentMatcher: new IntrospectionFragmentMatcher({
      introspectionQueryResultData: introspectionData,
    }),
    dataIdFromObject: result => {
      if (result.id && result.__typename) {
        // eslint-disable-line no-underscore-dangle
        return `${result.__typename}_${result.id}`; // eslint-disable-line no-underscore-dangle
      }
      return null;
    },
    networkInterface: networkInterfaceWithSubscriptions,
  });

  client.resetWebsocket = () => {
    if (wsClient.client) {
      // Close socket connection which will also unregister subscriptions on the server-side.
      wsClient.close(true);
github tadasant / where-in-the-world / app / src / App.js View on Github external
}),
  new HttpLink({
    uri: graphqlUri,
  })
]);

const link = split(
  ({query}) => {
    const {kind, operation} = getMainDefinition(query);
    return kind === 'OperationDefinition' && operation === 'subscription';
  },
  wsLink,
  httpLink,
);

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

// adding fontawesome icons we'll use
library.add(faMapMarker);
library.add(faMapPin);
library.add(faMapMarkerAlt);


class App extends Component {
  render() {
    return (
github akeating / pespa / src / client / vue / src / api / client.js View on Github external
export default function newClient(opts) {
  // eslint-disable-next-line new-cap
  const link = new ApolloLink.split(
    operation => hasSubscription(operation.query),
    absintheSocketLink(opts),
    createHttpLink({uri: '/api/graphql'})
  );

  const client = new ApolloClient({
    link,
    cache: new InMemoryCache()
  });
  return client;
}
github tsoporan / fittrak / fittrak-client / src / main.js View on Github external
attempts: {
      max: MAX_RETRIES,
      retryIf: error => !!error
    }
  }),
  errorLink,
  new HttpLink({
    uri: API_URL,
    credentials: DEBUG ? "include" : "same-origin",
    headers: {
      "x-csrftoken": Cookies.get("csrftoken")
    }
  })
]);

const apolloClient = new ApolloClient({
  link,
  cache: new InMemoryCache(),
  connectToDevTools: !DEBUG
});

const apolloProvider = new VueApollo({
  defaultClient: apolloClient
});

Vue.use(VueApollo);

/* eslint-disable no-new */
new Vue({
  el: "#app",
  router,
  apolloProvider,