question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Update / set dynamic uri

See original GitHub issue

I’ve got things working with a hardcoded url endpoint, but I can’t figure out how to set the uri after bootstrapping. I tried

const networkInterface = createNetworkInterface({
        // TODO - add method to set url / setup network interface (or just take url paramter in this function)
        uri: '{unknown at this point}',
    });
networkInterface.use([{
        applyMiddleware(req: any, next: any) {
            req.uri = '{myUrlHere}';
            next();
        }
    }]);

but that does not seem to work.

How do I set / change the uri?

My use case: I have a helper repository that wraps apollo for graphql, and the main repo has the url. The main repo sets the urls, and at that point, I need to set the graphql url (I don’t know it ahead of time, as it is set by a function call with which url to use).

Issue Analytics

  • State:closed
  • Created 7 years ago
  • Reactions:2
  • Comments:15 (3 by maintainers)

github_iconTop GitHub Comments

6reactions
tariknzcommented, Jul 13, 2017

@carlospalacin this looks like it creates a new instance of the client on every request.

I think I found a more efficient way of doing this when I was looking at this ticket: https://github.com/apollographql/apollo-client/issues/1267

NetworkInterface is referenced so you can just extend it and update it in your application.

Basically you create a new class that extends HTTPFetchNetworkInterface:

import { HTTPFetchNetworkInterface } from 'apollo-client';

export class GraphQLNetworkInterface extends HTTPFetchNetworkInterface {
    public setUri(uri: string) {
        this._uri = uri;
    }
}

Then create your client as instructed, but using the new network interface. Make sure you export the networkInterface when creating it:

import { ApolloClient } from 'apollo-client';
import { GraphQLNetworkInterface } from './graphql-network-interface';

export const networkInterface = new GraphQLNetworkInterface('[DEFAULT URL]');

const client = new ApolloClient({ networkInterface });

export function provideClient(): ApolloClient {
  return client;
}

Lastly, provide the networkInterface instance you created above in your module

{ provide: GraphQLNetworkInterface, useValue: networkInterface },

Then basically you can inject GraphQLNetworkInterface anywhere in your application and call the setUri to update the URI. It will be the same instance of the network interface you used to instantiate the client.

3reactions
carlospalacincommented, Jun 22, 2017

Hi! I leave my solution, I have created apollo-client-manager.ts:

import { ClientMap } from 'apollo-angular/build/src/types';
import { ApolloClient, createNetworkInterface } from 'apollo-client';
import { Apollo } from 'apollo-angular';

export class ApolloClientManager {
    private client: ApolloClient;

    static getClient(uri: string = undefined): ApolloClient {
        const cm = new ApolloClientManager(uri);
        return cm.client;
    }

    static getClientMap(uri: string = undefined): ClientMap {
        return { 'default' : ApolloClientManager.getClient(uri) };
    }

    static apollo(uri: string = undefined): Apollo {
        return new Apollo(ApolloClientManager.getClientMap(uri));
    }

    constructor(
        uri: string = undefined
    ) {
        const networkInterface = createNetworkInterface({
            uri: uri ? uri : '/graphql'
        });

// middleware form JWT
        networkInterface.use([{
            applyMiddleware(req, next) {
                if (!req.options.headers) {
                    req.options.headers = {};  // Create the header object if needed.
                }
                // get the authentication token from local storage if it exists
                req.options.headers.authorization = localStorage.getItem('token') || null;
                next();
            }
        }]);

        this.client = new ApolloClient({
            networkInterface
        });
    }
}

and apollo-service.ts:

import { Injectable } from '@angular/core';
import { Apollo } from 'apollo-angular';
import { ApolloClientManager } from './apollo-client-manager';

@Injectable()
export class ApolloService {

    _apollo: Apollo;
    _uri: string;

    constructor() { }

    apollo(uri) {
        if (! this._apollo || uri !== this._uri) {
            this._uri = uri;
            this._apollo = ApolloClientManager.apollo(this._uri);
        }
        return this._apollo;
    }
}

and graphql.module.ts:

import { NgModule, Inject } from '@angular/core';
import { ApolloClient, createNetworkInterface } from 'apollo-client';
import { ApolloModule } from 'apollo-angular';
import { ApolloClientManager } from './apollo-client-manager';

@NgModule({
    imports: [
        ApolloModule.forRoot(ApolloClientManager.getClient)
    ],
    exports: [ApolloModule],
    providers: [
        ApolloService
    ]
})
export class GraphQLModule { }

you can create your apollo instance with service:

@Component({
    selector: 'ps-selector-list',
    templateUrl: './selector-list.component.html'
})
export class SelectorListComponent {

    constructor(
        private apolloService: ApolloService
    ) { }

    ngOnInit() {
        // this with custom uri
        this.apolloService
            .apollo('http://my-uri.com/graphql').watchQuery({
                query: gql`
                 {
                    actions {
                      id
                      name
                    }
                    packages {
                      id
                      name
                      root
                      sort
                    }
                 }
                `
            }).subscribe(({data}) => {
                console.log(data);
            });

        // and this with default uri
        this.apolloService
            .apollo().watchQuery({
                query: gql`
                 {
                    actions {
                      id
                      name
                    }
                    packages {
                      id
                      name
                      root
                      sort
                    }
                 }
                `
            }).subscribe(({data}) => {
                console.log(data);
            });
    }
}

don’t forget import graphql.module.ts in your module This works fine for me

Read more comments on GitHub >

github_iconTop Results From Across the Web

How to Update URL for Dynamic URLs - Stack Overflow
If you want to try this using AddThis, you can change the title and url by updating the page's title and history like...
Read more >
Update** Update dynamic page URL field in a collection?
I have a dynamic form that collates information from two collections for a specific user. The dynamic form URL is set to my...
Read more >
Updating WebSEAL for dynamic URLs - IBM
Use the dynurl update command to update the WebSEAL protected object space with entries made in the dynurl.conf configuration file. Create, edit, or...
Read more >
Is it possible to dynamically update the source URL ... - TechNet
Hi Imke,. I've created a first table as you explained. Now, i have trouble to understand how to create a new query and...
Read more >
Set dynamic url in field via a business rule - ServiceNow
I have a business rule that calls a REST Service to create an Incident in another ServiceNow instance. Upon return I will have...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found