Automattic / Automattic/jetpack

Instant Search: API cache fallback, timeout, localStorage

Open
#13,751 6 comments 0 reactions 0 assignees View on GitHub
[Feature] Search Enhancement
Dominant language
PHP
Stars
1.8k
Forks
898
Avg merge
1d 18h
Merged PRs (30d)
774

Description

It seems like we could greatly improve our search API handling for when there are errors:
- Currently we don't do anything about non-200 responses from the API. Can probably do something like this:

```
return fetch(
`https://public-api.wordpress.com/rest/v1.3/sites/${ siteId }/search?${ queryString }`
).then( response => {
if (response.ok) {
return response;
} else {
const error = new Error( response.statusText );
error.response = response;
return Promise.reject( error );
}
} ).then( response => {
const r = response.json();
apiCache.put( key, r );
return r;
} ).catch( error => {
const cachedOldVal = apiCache.get( key );
if ( cachedOldVal ) {
return cachedVal;
}
return error;
} );
```

- I think we could have multiple layers to our api caching:

```
//Two layer in memory cache
// - 5 min TTL normally
// - 30 min to fall back on if we lose connectivity
//TODO: store cache data in the browser - esp for mobile
const apiCache = new Cache( 300 * 1000 );
const apiCacheFallback = new Cache( 1800 * 1000 );
```

- That `apiCacheFallback` we should probably store in localStorage so that we can fallback to it even when losing network connectivity. If that is the case then we should probably keep it around longer (or indefinitely). We should probably always try to hit the real api, but then use the backup if it is there.
- I think we should also think about slow connections. Implement some sort of a request timeout (https://davidwalsh.name/fetch-timeout ?) and if we already have the data in memory then let's go ahead and use a shorter timeout (less than a second) so that we fallback to the local data more quickly.
- We need to handle cancelling in transit requests: https://github.com/Automattic/jetpack/pull/12741#discussion_r299373087

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.