Apollo-link: Question: How to handle the case when forward is undefined?

Created on 22 Dec 2017  路  2Comments  路  Source: apollographql/apollo-link

I have this example link:

const consoleLink = new ApolloLink((operation, forward): Observable<
  FetchResult
> | null => {
  console.log(`starting request for ${operation.operationName}`);
  return forward(operation).map((data: FetchResult) => {
    console.log(`ending request for ${operation.operationName}`);
    return data;
  });
});

I get a typescript compile error object is possibly undefined on the forward parameter.

The ApolloLink constructor accepts a RequestHandler which is defined like (operation: Operation, forward?: NextLink) => Observable<FetchResult> | null. By this definition, forward might be undefined.

When I develop my own custom link, I need to handle the case that forward can be undefined. My question is how I handle this. What should I return in this case?

question

Most helpful comment

Seems returning null works.

const authMiddleware = new ApolloLink((operation, forward) => {
  operation.setContext({
   headers: new HttpHeaders()
     .set('Authorization', sessionService.getUserToken())
  })

  if (forward)
    return forward(operation)
  else
    return null
})

All 2 comments

Seems returning null works.

const authMiddleware = new ApolloLink((operation, forward) => {
  operation.setContext({
   headers: new HttpHeaders()
     .set('Authorization', sessionService.getUserToken())
  })

  if (forward)
    return forward(operation)
  else
    return null
})

Since this issue is really outdated I am closing it but if you are still concerned about this feel free to reopen and I'll get back to you asap.

Was this page helpful?
0 / 5 - 0 ratings