Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
import { BrowserRouter } from 'react-router-dom';
import { ApolloProvider } from 'react-apollo';
import { ApolloClient } from 'apollo-client';
import { ApolloLink } from 'apollo-link';
import { onError } from 'apollo-link-error';
import { HttpLink } from 'apollo-link-http';
import WsLink from 'apollo-link-ws';
import Cache from 'apollo-cache-inmemory';
import App from './components/App';
const errorLink = onError(({ graphqlErrors, networkError }) => {
// could also be sent to an error logger
console.error('Apollo Errors caught!', { graphqlErrors, networkError });
});
const authLink = new ApolloLink((operation, forward) => {
const token = localStorage.getItem('AUTH_TOKEN');
operation.setContext(() => ({
headers: {
authorization: token ? `JWT ${token}` : null,
},
}));
return forward(operation);
});
const hasSubscriptionOperation = operation =>
operation.query.definitions.reduce(
(result, definition) => result || definition.operation === 'subscription',
false
);
import { withClientState } from 'apollo-link-state'
import { ApolloLink } from 'apollo-link'
import { BrowserRouter } from 'react-router-dom'
import registerServiceWorker from './registerServiceWorker'
import initialState from './apollo/initialState'
// Here you create the HttpLink that will connect your ApolloClient
// instance with the GraphQL API; your GraphQL server will be running
// on http://localhost:3000.
const httpLink = new HttpLink({ uri: 'http://localhost:3000/graphql' })
// Add the authorization to the headers
const JWTMiddleware = new ApolloLink((operation, forward) => {
operation.setContext({
headers: {
Authorization: localStorage.getItem('Authorization') || null,
}
})
return forward(operation)
})
// This is the same cache you pass into new ApolloClient
const cache = new InMemoryCache()
// Create state Link
const stateLink = withClientState({
cache,
resolvers: {
Mutation: {
setCurrentUser: (_, { id, token, username, picture }, { cache }) => {
import { ApolloClient } from 'apollo-client';
// import { HttpLink } from 'apollo-link-http';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { ApolloLink } from 'apollo-link';
import { createUploadLink } from 'apollo-upload-client'
const httpLink = createUploadLink({uri:'http://localhost:3000/graphql'})
const authMiddleware = new ApolloLink((operation, forward) => {
operation.setContext({
headers: {
"x-token": localStorage.getItem('token') || null,
}
});
return forward(operation);
})
const authAfterware = new ApolloLink((operation, forward) => {
return forward(operation).map(response => {
const context = operation.getContext();
const { response: { headers } } = context;
if (headers) {
const token = headers.get("x-token");
const persistedReducer = persistReducer(persistConfig, mainReducer)
const finalCreateStore = applyMiddleware(...middlewares)(createStore);
const store = finalCreateStore(persistedReducer);
let persistor = persistStore(store)
// APOLLO
// HttpLink
const httpLink = new HttpLink({
uri: process.env.HTTP_BACKEND_URL,
fetch: fetch
});
const middlewareLink = new ApolloLink((operation, forward) => {
const token = localStorage.getItem(process.env.AUTH_TOKEN);
operation.setContext({
headers: {
Authorization: token ? `Bearer ${token}` : ""
}
});
return forward(operation);
});
const httpLinkAuth = middlewareLink.concat(httpLink);
const errorLink = onError(({ graphQLErrors, networkError }) => {
if (graphQLErrors)
graphQLErrors.map(({ message, locations, path }) =>
constructor(props) {
super(props);
const httpLink = new HttpLink({
uri: process.env.REACT_APP_GRAPHQL_ENDPOINT,
});
// const cache = new InMemoryCache({ dataIdFromObject: o => o.id });
const cache = new InMemoryCache();
const middlewareLink = new ApolloLink((operation, forward) => {
// get the authentication token from props if it exists
// return the headers to the context so httpLink can read them
const { headers = {} } = operation.getContext();
operation.setContext({
headers: {
Authorization: `Bearer ${props.getToken()}`,
...headers,
},
});
return forward(operation);
});
// authenticated httplink
const httpLinkAuth = middlewareLink.concat(httpLink);
const errorLink = onError(({ graphQLErrors, networkError }) => {
it('runs resolvers for missing client queries with server data', done => {
const query = gql`
query Mixed {
foo @client {
bar
}
bar {
baz
}
}
`;
const sample = new ApolloLink(() =>
Observable.of({ data: { bar: { baz: true } } }),
);
const client = withClientState({ resolvers });
execute(client.concat(sample), { query }).subscribe(({ data }) => {
try {
expect(data).toEqual({ foo: { bar: true }, bar: { baz: true } });
} catch (error) {
done.fail(error);
}
done();
}, done.fail);
});
export const mockApolloClient = params => {
const mockedSchema = mockSchema(params);
const schemaLink = new ApolloLink(operation => {
return new Observable(observer => {
graphql(
mockedSchema,
print(operation.query),
operation.getContext,
operation.variables
).then(result => {
observer.next(result);
observer.complete();
});
});
});
const mockedClient = new ApolloClient({
link: params.controller
? controllerLink(params.controller).concat(schemaLink)
export function onError(errorHandler: ErrorHandler): ApolloLink {
return new ApolloLink((operation, forward) => {
return new Observable(observer => {
let sub;
let retriedSub;
let retriedResult;
try {
sub = forward(operation).subscribe({
next: result => {
if (result.errors) {
retriedResult = errorHandler({
graphQLErrors: result.errors,
response: result,
operation,
forward,
});
export const complexObjectLink = (credentials) => {
return new ApolloLink((operation, forward) => {
return new Observable(observer => {
let handle;
const { operation: operationType } = getOperationDefinition(operation.query);
const isMutation = operationType === 'mutation';
const objectsToUpload = isMutation ? findInObject(operation.variables) : {};
let uploadPromise = Promise.resolve(operation);
if (Object.keys(objectsToUpload).length) {
const uploadCredentials = typeof credentials === 'function' ? credentials.call() : credentials;
uploadPromise = Promise.resolve(uploadCredentials)
.then(credentials => {
const uploadPromises = Object.entries(objectsToUpload).map(([_, fileField]) => upload(fileField, { credentials }));
function createMoleculerLink(opts: ServiceOptions): ApolloLink {
return new ApolloLink(
operation =>
new Observable(observer => {
const { credentials, fetcherOptions } = operation.getContext();
const { operationName, extensions, variables, query } = operation;
const { broker, service } = opts;
broker.call(`${service}.graphql`, {
credentials,
query: print(query),
variables,
extensions,
operationName
})
.then(result => {
observer.next(result);
observer.complete();