How to set Apollo link URI per query - initial uri stays, should I use dynamic uri (angular 8)

3.1k Views Asked by At

Summary

I'm building a simple search application in Angular 8, using Apollo with a graphql server over elasticsearch; I'm passing the elastic query to the backend in the URI, then graphql queries run within the elastic returned data. However, the URI is set in the first create of Apollo, then doesn't change for subsequent queries in that session.

Background

As a novice Angular/Apollo dev, I'm only trying to achieve the starting implementation for a future search tool; I've reviewed graphql-compose-elastic but it looks unwieldy, at least for the immediate prototype need. I have tried moving the Apollo declarations to a sub-module, using the URI as a Global or via localStorage, but the client won't reset the URI after query 1. I still get results (no errors) but they are always the same records returned from query 1.

Current code

I have a graphql.module.ts which creates the httpLink, and currently at runtime it fetches the uri string (including the elastic search) parameters from localStorage:

in component for search results (using Form + ag-grid) it sets the localstorage uricombo variable:

search.component.ts

uricombo = 'http://graqhql.server.internal:9000/graphql/esindex1/_search?q=title:beginners'

graphql.module.ts

httpLink.create({ uri: localStorage.getItem('uricombo') })

search.component.ts

this.querySubscription = this.apollo.watchQuery<any>({ query: AllBooksQuery, })

...which returns data rows to an ag-grid.

This is fine, but when the user submits subsequent search(s), the original uri is used, and the same records return again.

The stored uricombo value is definitely updated per search submit, while the Apollo link create method is only run once (the first time).

Current assumption is that once the apollo client is created, it retains the URI, but I'm not sure how to refactor this to refresh the URI - I suspect Dynamic URI will help, but not quite clear on how to implement.

As I said relatively new to both Angular and Apollo, (although long time Java jockey) - I may be doing something noobish. Any help / patterns / examples much appreciated

1

There are 1 best solutions below

0
On BEST ANSWER

I was able to resolve this just by naming the instance of apollo, rather than relying on the default instance:

this.apollo.create({ cache: new InMemoryCache(), link: this.httpLink.create({ uri: localStorage.getItem('uricombo') + localStorage.getItem('searchTerms') }) }, 'name1');

Once that was in place the query method updated results each submit.