Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Differences between new HttpLink and createHttpLink from package apollo-link-http

In tutorial

https://www.howtographql.com/vue-apollo/1-getting-started/

there is presented new HttpLink syntax, but in official docs

https://www.apollographql.com/docs/link/links/http/

function createHttpLink is applied.

None of these two sources describes the differences between these methods.

like image 439
Daniel Avatar asked Jun 19 '19 08:06

Daniel


People also ask

What is HttpLink?

HttpLink is a terminating link that sends a GraphQL operation to a remote endpoint over HTTP. Apollo Client uses HttpLink by default when you provide the uri option to the ApolloClient constructor. HttpLink supports both POST and GET requests, and you can configure HTTP options on a per-operation basis.

What is the latest version of Apollo?

Apollo Client 3.6. 0 (2022-04-26)

How are HTTP request sent by Apollo Client authenticated?

Apollo Client uses HttpLink to send GraphQL operations to a server over HTTP. The link supports both POST and GET requests, and it can modify HTTP options on a per-query basis. This comes in handy when implementing authentication, persisted queries, dynamic URIs, and other granular updates.

What is uri in Apollo Client?

uri specifies the URL of our GraphQL server. cache is an instance of InMemoryCache , which Apollo Client uses to cache query results after fetching them.


1 Answers

There is no fundamental difference between the two.

If you look at the apollo-link-http package source here, you can see that the exported createHttpLink method returns a new instance of the ApolloLink class initialized with the options you passed to createHttpLink (lines 62-194).

At the end of the same file, you can see that the package also exports the HttpLink class, which extends the ApolloLink class (lines 256-261):

export class HttpLink extends ApolloLink {
  public requester: RequestHandler;
  constructor(opts?: HttpLink.Options) {
    super(createHttpLink(opts).request);
  }
}

As you can see from the code above, when you create an apollo http link by creating a new instance of the HttpLink class, the options you pass to the constructor are internally passed on to createHttpLink, which returns an instance of ApolloLink as mentioned above, and that instance's RequestHandler is passed on to (i.e. copied) to the new HttpLink instance's parent, which is also an instance of ApolloLink (see lines 96-124 here for a peek at ApolloLink's own constructor).

Note that the apollo-link-http package's own docs do NOT mention the new HttpLink syntax, so I would stick to the createHttpLink syntax for future compatibility.

like image 86
Thomas Hennes Avatar answered Sep 23 '22 10:09

Thomas Hennes