0

I am using MongoDB realm GraphQL API to access data. I am using Apollo-Angular.

The GraphQL API needs an API key to access the data. I tried with the postman and it work. Using the postman post request I pass the key in the Authorization that added in Header with the key: apiKey, value: The_Api_Key_from_Mongo

But how can I add this authorization Apollo-Angular settings?

const uri =
  'https://ap-south-1.aws.realm.mongodb.com/api/client/v2.0/app/myapp_with_id/graphql'; 

export function createApollo(httpLink: HttpLink): ApolloClientOptions<any> {
  return {
    link: httpLink.create({
      uri,
    }),
    cache: new InMemoryCache(),
  };
}

Simply: I have GraphQL api uri to access this API I have to pass api key. How can I do this in Apollo-Angular?

R. Richards
  • 24,603
  • 10
  • 64
  • 64
monzim
  • 526
  • 2
  • 4
  • 13

1 Answers1

0

You need to refactor your Apollo Angular return statement by passing this new param to the HttpLink. So instead of the link key in

  return {link: httpLink.create({uri})

holds a single object it will hold an array of objects. The new API key can be attached as an item in the array after passing it to the setContext() method.

1- Set the new authentication API key using setContext():

const authAPIKey = setContext(()=>({headers: new HttpHeaders().set('key', `APIKEY_PLACE_HOLDER`)}))

2- Set your URI as another const similar to the APIKey in step 1 above

  const URI = httpLink.create({uri})

3- Refactor your return statement to be

return {
    link: from([authAPIKey, URI]),
    cache: cache,
  };

4- Do not forget to import from in the return statement above from '@apollo/client/core' and setContext() from '@apollo/client/link/context'

onrails
  • 778
  • 5
  • 10
  • ``const uri = 'https://ap-south-1.aws.realm.mongodb.com/api/client/v2.0/app/myapp_with_id/graphql'; const authAPIKey = setContext(() => ({ headers: new HttpHeaders().set('key', key), })); export function createApollo(httpLink: HttpLink): ApolloClientOptions { return { link: from([ authAPIKey, httpLink.create({ uri, }), ]), cache: new InMemoryCache(), }; }`` Showing this error: https://ibb.co/ykssZ6x – monzim Sep 05 '22 at 00:39
  • you have a Cross Origin Ressource Sharing Error. Check your server authorization configuration – onrails Sep 05 '22 at 14:10