Dive into secure and efficient coding practices with our curated list of the top 10 examples showcasing 'apollo-link-http' in functional components in JavaScript. Our advanced machine learning engine meticulously scans each line of code, cross-referencing millions of open source libraries to ensure your implementation is not just functional, but also robust and secure. Elevate your React applications to new heights by mastering the art of handling side effects, API calls, and asynchronous operations with confidence and precision.
if (error) {
const { message, locations, path } = error;
console.error(`[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`);
return;
}
console.error('[GraphQL error]: Received null error');
});
}
if (networkError) {
console.error(`[Network error]: ${networkError}`);
}
});
const httpLink = new HttpLink({
uri: getGraphqlUrl(),
fetch,
});
const link = ApolloLink.from([errorLink, authLink.concat(httpLink)]);
return new ApolloClient({
connectToDevTools: process.browser,
ssrMode: !process.browser, // Disables forceFetch on the server (so queries are only run once)
cache: cache.restore(initialState),
link,
});
}
const { GET_OPTIONS } = require("../shared/queries/Queries");
// handle errors whie fetching data in the server.
const errorLink = onError(({ networkError, graphQLErrors }) => {
if (graphQLErrors) {
graphQLErrors.map(({ message, locations, path }) =>
console.log(
`[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`,
),
);
}
if (networkError) console.log(`[Network error]: ${networkError}`);
});
const httpLink = createHttpLink({
uri: config.apiUrl,
fetch,
});
const link = ApolloLink.from([errorLink, httpLink]);
module.exports.init = app => {
app.get("*", (req, res, next) => {
if (req.url === "/graphql") return next();
// using the apolloclient we can fetch data from the backend
const client = new ApolloClient({
ssrMode: true,
link: link,
cache: new InMemoryCache(),
});
function createApolloClient(initialState = {}) {
// Check out https://github.com/zeit/next.js/pull/4611 if you want to use the AWSAppSyncClient
return new ApolloClient({
ssrMode: typeof window === 'undefined', // Disables forceFetch on the server (so queries are only run once)
link: new HttpLink({
uri: 'https://api.graph.cool/simple/v1/cixmkt2ul01q00122mksg82pn', // Server URL (must be absolute)
credentials: 'same-origin', // Additional fetch() options like `credentials` or `headers`
fetch,
}),
cache: new InMemoryCache().restore(initialState),
})
}
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import { ApolloClient } from 'apollo-client'
import { HttpLink } from 'apollo-link-http'
import { setContext } from 'apollo-link-context'
import { InMemoryCache } from 'apollo-cache-inmemory'
import VueApollo from 'vue-apollo'
import App from './App'
import router from './router'
Vue.config.productionTip = false
// install the vue-momnet plugin
Vue.use(require('vue-moment'))
const httpLink = new HttpLink({ uri: 'http://localhost:4000/' })
const httpLinkAuth = setContext((_, { headers }) => {
// get the authentication token from localstorage if it exists
const token = localStorage.getItem('USER_TOKEN')
// return the headers to the context so httpLink can read them
return {
headers: {
...headers,
Authorization: token ? `Bearer ${token}` : ''
}
}
})
// Create the apollo client
const apolloClient = new ApolloClient({
const token = localStorage.getItem('growth_auth_token')
const returnObject = {
headers: {
...headers
}
}
if (token) {
returnObject.headers['authentication'] = `{"growth_auth_token": "${token}"}`
}
// return the headers to the context so httpLink can read them
return returnObject
})
const httpLink = new HttpLink({ uri: `${growthServerAddress}/graphql`, fetch })
const schema = mergeSchemas({
schemas: [
makeRemoteExecutableSchema({
schema: growthSchema,
link: authLink.concat(httpLink)
}),
makeExecutableSchema({ typeDefs, resolvers })
]
})
export default schema
async function run() {
// Step 1: Create local version of the CRUD API
const link = new HttpLink({ uri: process.env.GRAPHQL_ENDPOINT, fetch })
const graphcoolSchema = makeRemoteExecutableSchema({
schema: await introspectSchema(link),
link,
})
// Step 2: Define schema for the new API
const extendTypeDefs = `
extend type Query {
viewer: Viewer!
}
type Viewer {
me: User
topPosts(limit: Int): [Post!]!
}
clientName: CLIENT_NAME,
clientVersion: CLIENT_VERSION
};
operation.setContext({
http: {
includeExtensions: true
}
});
return forward(operation);
});
// Terminating link to fetch data from server
// NOTE: Reads request headers from context
const networkLink = new HttpLink({
uri: GRAPHQL_ENDPOINT
});
const apolloClient = new ApolloClient({
cache,
link: ApolloLink.from([
errorLink,
stateLink,
authLink,
clientIdentifierLink,
networkLink
])
});
return {
apolloClient,
const store = createStore(
reducer,
{}, // initial state
composeWithDevTools(
applyMiddleware(thunk, navigationMiddleware),
),
);
// persistent storage
const persistor = persistStore(store);
const cache = new ReduxCache({ store });
const reduxLink = new ReduxLink(store);
const httpLink = createHttpLink({ uri: `http://${URL}` });
// middleware for requests
const middlewareLink = setContext((req, previousContext) => {
// get the authentication token from local storage if it exists
const { jwt } = store.getState().auth;
if (jwt) {
return {
headers: {
authorization: `Bearer ${jwt}`,
},
};
}
return previousContext;
});
onPageLoad(async (sink) => {
if (checkIfBlacklisted(sink.request.url.path)) {
sink.appendToBody(`
`);
return;
}
const apolloClient = new ApolloClient({
ssrMode: true,
link: createHttpLink({
uri: Meteor.settings.public.graphQL.httpUri,
}),
cache: new InMemoryCache(),
});
const stylesheet = new ServerStyleSheet();
const app = stylesheet.collectStyles(
,
);
// NOTE: renderToStringWithData pre-fetches all queries in the component tree. This allows the data
// from our GraphQL queries to be ready at render time.
function create (initialState, { getToken, fetchOptions }) {
const httpLink = createHttpLink({
uri: 'https://api.graph.cool/simple/v1/cj5geu3slxl7t0127y8sity9r',
credentials: 'same-origin',
fetchOptions
})
const authLink = setContext((_, { headers }) => {
const token = getToken()
return {
headers: {
...headers,
authorization: token ? `Bearer ${token}` : ''
}
}
})
// Check out https://github.com/zeit/next.js/pull/4611 if you want to use the AWSAppSyncClient