Giter Site home page Giter Site logo

drcallaway / apollo-link-timeout Goto Github PK

View Code? Open in Web Editor NEW
70.0 4.0 22.0 764 KB

An Apollo Link that aborts requests that take longer than a specified timeout

Home Page: https://www.npmjs.com/package/apollo-link-timeout

License: MIT License

TypeScript 100.00%

apollo-link-timeout's Introduction

apollo-link-timeout

An Apollo Link that aborts requests that aren't completed within a specified timeout period. Note that timeouts are enforced for query and mutation operations only (not subscriptions).

Installation

npm install apollo-link-timeout

or

yarn add apollo-link-timeout

Usage

import ApolloLinkTimeout from 'apollo-link-timeout';
import { createHttpLink } from 'apollo-link-http';
import { ApolloClient } from 'apollo-client';

...

const timeoutLink = new ApolloLinkTimeout(10000); // 10 second timeout

const httpLink = createHttpLink({ uri: "/graphql" });

const timeoutHttpLink = timeoutLink.concat(httpLink);

const apolloClient = new ApolloClient({ link: timeoutHttpLink });

// use timeout-enabled Apollo client...

// Override timeout from any query 
<Query
 query={SOME_QUERY}
 variables={{
    someVar1: "foo",
    someVar2: "bar",
   }}
  context={{ timeout: 3000 }}
>
// ...

See Apollo documentation for information on using the Apollo client.

apollo-link-timeout's People

Contributors

christophehurpeau avatar danmaas avatar dependabot[bot] avatar drcallaway avatar gbenga504 avatar jdmoody avatar mikaoelitiana avatar tahmidrahman avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

apollo-link-timeout's Issues

Release status

Hi, hello. Thanks for the amazing job here.

The master branch has a few fixes that allows this lib to be used with Apollo 3, but the latest release seems to be from 2019. It would be nice if we could generate a new release from master to allow folks to use the latest version in their projects without the need of forking. Is there a plan for that?

Thank you!

Missing release for version 1.2.1

Hi :)

We are using the version 1.2.1 of this lib for one of our projects. Our OSS clearing team now asked me for a link of the source code of the npm package. Unfortunately the last release listed here is 1.1.7
Would be awesome if you could add the one for 1.2.1 as well!

Thanks!

Allow TimeoutError to have 504 statusCode

I think the 408 HTTP code is usually used when the client takes too long to send a request to the server:

The client did not produce a request within the time that the server
was prepared to wait. The client MAY repeat the request without
modifications at any later time.

I think a 504 may be more accurate for this error because it is the server that has failed to send a response to the client:

The server, while acting as a gateway or proxy, did not receive a
timely response from the upstream server it accessed in attempting to
complete the request.

This is especially accurate for my use-case where I'm using this link for SSR, so I have a server acting as a proxy that will eventually return a 504 to the client.


I'm happy to make a PR for this, I just wanted to sanity-check my understanding ๐Ÿ˜Š

I was planning on adding an additional statusCode parameter to the TimeoutLink constructor that is used to set the underlying TimeoutError's statusCode. (I would default the link's statusCode to a 408 to maintain backwards-compatibility)

Crash

Since I updated expo to sdk 46 (thus react native to 0.69.4 and react to 18), my react native web app is blank and the console displays the following error:

bootstrap:79 Uncaught TypeError: Cannot read properties of undefined (reading 'call')
    at l (bootstrap:79:22)
    at Module.<anonymous> (index.js:1:1)
    at l (bootstrap:79:22)
    at Object.<anonymous> (timeoutLink.js:21:14)
    at l (bootstrap:79:22)
    at 64 (app.f48d05ca.chunk.js:1:374083)
    at l (bootstrap:79:22)
    at 1181 (app.f48d05ca.chunk.js:1:6318)
    at l (bootstrap:79:22)
    at 817 (app.f48d05ca.chunk.js:1:513405)

โฑ Increase timeout in batched cases

I was exploring a case where we are using @apollo/client/link/batch-http.

In our case, we batched queries that have the same operation name. So we finally with an array of requests in a single HTTP request. Something like that

// request body

[
  { operationName: "SomeQuery",  variables: {} },
  { operationName: "SomeQuery",  variables: {} }
]

So, shouldn't we have been catching this case and increasing the timeout based on the number of queries? Because I feeling that we are setting up the timeout per query and in a batched case we are doing more than one so obviously this will take more time.

Maybe we could enable a flag to do that? Currently, we are increasing the timeout manually using the context.

Happy to contribute if it needs it and also hear other thoughts about it. ๐Ÿ˜Š

Timeouts not respected

HI,
I'm not sure how to exactly report on this because I have tests of my link chain that verify requests are timing out... but, it appears in some cases, specifically low to no network situations, that the timeout is not being respected. Any ideas?

Update package to ESM format

Please convert this useful package to ESM format!
Angular 12+ complains about the package being in CJS/AMD format which can cause optimization issues.

Thx!

Network errors causes red error / app crash.

I have found that if the request resolves before the timeout occurs, but is an error, then an uncaught exception occurs. Generally this is caused by an error response from the server such as a 500 response.

I think this is due to the subscription to the chained observable no handling the an error caught further down the apollo link chain. I believe you can pass an error callback to the subscribe method (

), specifically the error callback of the local observable to resolve this issue.

Error while SSR

Hello, I was using this lib for SSR, and latest version started to fail

Stack trace pretty obvious:

ReferenceError: window is not defined
    at ...\node_modules\apollo-link-timeout\src\timeoutLink.ts:65:7

Angular compatibility

Hello, the latest version uses @apollo/client which has React dependecies in it.
For Angular, you should import from @apollo/client/core check this
This little change fixes the lib for Angular and should also be compatible with React.

Build es version to support react-native

Hey,

it would be grate to have an es version for react-native and also better treeshaking with webpack.
It seems you build with typescript so I don't know how that would work to have multiple targets, but if you want I can look into this and help create a PR

I have this error with react-native:

[Thu Jul 08 2021 13:37:09.203]  ERROR    ReferenceError: Can't find variable: client_1

And the only reference of client_1 is apollo-link-timeout. Modifying to import * as client_1 from '@apollo/client'; in the dist file works.

Thanks

Sourcemaps are not working properly

Hi,
I'm having the next problem with the sourcemap when compiling my project:

Module Warning (from ./node_modules/source-map-loader/dist/cjs.js):
Failed to parse source map from '[dir]/node_modules/apollo-link-timeout/src/TimeoutError.ts' file: Error: ENOENT: no such file or directory, open '[dir]/node_modules/apollo-link-timeout/src/TimeoutError.ts'

this is because in the package.json files config is set to only publish the lib folder https://github.com/drcallaway/apollo-link-timeout/blob/master/package.json#L46

Then what happens is that the sourcemap generated, e.g. for TimeoutError.js will point to the original file in src which is not included in the package.

{"version":3,"file":"TimeoutError.js","sourceRoot":"","sources":["../src/TimeoutError.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA;IAA0C,gCAAK;IAI7C,sBAAY,OAAe,EAAE,OAAe,EAAE,UAAwB;QAAxB,2BAAA,EAAA,gBAAwB;QAAtE,YACE,kBAAM,OAAO,CAAC,SAGf;QAFC,KAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,KAAI,CAAC,UAAU,GAAG,UAAU,CAAC;;IAC/B,CAAC;IACH,mBAAC;AAAD,CAAC,AATD,CAA0C,KAAK,GAS9C"}

A fix could be just to add the src folder to the distributable in the package.json and publish a new version

  "files": [
    "lib",
    "src"
  ],

Let me know if I can do it myself and open PR, thank you!

Add statusCode property to TimeoutError

TimeoutError error should contains a 408 code as statusCode property.

This would make easier to handle timeout errors. E.g:

if (networkError.statusCode === 408) { โ€ฆ }

Otherwise we are only getting an error message Timeout exceeded. Handling errors by error message is a mess IMO.

A couple of issues/comments/suggestions

Hi @drcallaway ๐Ÿ‘‹ nice repo!

I ran across this when trying to help some other people, and I noticed a couple of things that I think should be fixed/improved, especially since this is a link that seems to be used by a decent number of people.

  1. Using an abort controller and reaching into the fetch request breaks the link abstraction. One link shouldn't be concerned with and/or reach into the internals of another link (in this case the http link). Doing so violates assumptions made by other links. The proper way for an observable to cancel a request is to simply unsubscribe and let the cancellation propagate through the chain in an orderly fashion. apollo-link-http already aborts the request if you unsubscribe from it, so nothing more should be needed. If it doesn't work as expected, then it's a bug that should be fixed in apollo-link-http.
  2. Bug: Exposing a timeoutRef violates abstraction boundaries in a similar way as #1. This time the timeout link is the one being reached into, leaving other subscribers between the timeout link and whoever reached into it high and dry (they never complete, nor do they ever get a TimeoutError). Whoever is using timeoutRef should just unsubscribe instead of reaching in.
  3. Suggestion: Add tests for standard link functionality. Currently this link doesn't tests that it properly propagates errors, properly unsubscribes, etc. There are also no
  4. Suggestion: Use travis or Circle CI to run tests on every PR.
  5. Minor suggestion: When not passing a timeout to the constructor, I think it would be better to set the timeout to 0 (i.e. no timeout) and not 15 seconds, because 15 seconds is a completely arbitrary value, whereas no timeout is a reasonable non-arbitrary choice.
  6. Very minor suggestion: add the timeout value to the TimeoutError and its error message, eg. "Operation timed out after x ms". Not all operations will have the same timeout, and knowing immediately what the timeout was can be helpful for debugging.

Since this is a really useful package, I hope you have the time and motivation to maintain it. If not, it might also be possible to hand the package over to the Apollo maintainers, if they're inclined to look after it.

have a timeout function

We integrate a number of endpoints on our api. Some endpoints are slower than others. I would ideally like to be able to have a function that allows me to return the appropriate timeout depending on the query / mutation.

Override timeout value from context?

It would be great to have an easy way to override timeout value from context so different values can be used on a same client. Something like :

options: {
    context: {
      timeout: 3000
    }
  }

Migration guide to v4.0.0?

In 1.4, we were doing:

const timeoutLink = new ApolloLinkTimeout(30000);

const link = split(
  // split based on operation type
  ({ query }) => {
    const definition = getMainDefinition(query);
    return definition.kind === 'OperationDefinition' && definition.operation === 'subscription';
  },
  wsLink,
  // Wrapping these in this way will retry requests if they timeout
  ApolloLink.from([logRocketToDatadogLink, authLink, retryLink, timeoutLink, httpLink]),
);

But this isn't compatible with 4.0. Also tried:

ApolloLink.from([logRocketToDatadogLink, authLink, retryLink, timeoutLink.concat(httpLink)]),

`controller` is not a valid fetch option

As far as I can tell looking at MDN docs, etc. signal is a valid fetch option, but controller is not:

https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters

The code here uses controller instead of signal when interacting with fetch options:

controller = fetchOptions.controller || new AbortController();

I haven't tested this link out, so I don't know exactly what will happen, but it looks like there would be bugs due to this.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.