Skip to content

Instant Search: API cache fallback, timeout, localStorage #13751

@gibrown

Description

@gibrown

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: Instant Search: Add initial framework #12741 (comment)

Metadata

Metadata

Assignees

No one assigned

    Labels

    EnhancementChanges to an existing feature — removing, adding, or changing parts of it[Feature] SearchFor all things related to Search

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions