2

Using the simple "Movies API" example from the documentation. I added a ttl to the getMovie function, so that the result is cached for 10 minutes. How can I invalidate the cache in the updateMovie function?

const { RESTDataSource } = require('apollo-datasource-rest');

class MoviesAPI extends RESTDataSource {
  async getMovie(id) {
    return this.get(`movies/${id}`, {}, { cacheOptions: { ttl: 600 } });
  }

  async updateMovie(id, data) {
    const movie = await this.put(`movies/${id}`, data);

    // invalidate cache here?!

    return movie;
  }
}

I know that the KeyValueCache interface that is passed to ApolloServer provides a delete function. However, this object doesn't seem to be exposed in data sources. It's wrapped inside HTTPCache, which only exposes a fetch function. The KeyValueCache is also wrapped inside a PrefixingKeyValueCache, so it seems almost impossible to invelidate something in the cache, without some nasty hacks, assuming the internal implementation of RESTDataSource.

Ropez
  • 3,485
  • 3
  • 28
  • 30

2 Answers2

5

It seems like the best solution I can find, is to just leave the HTTP cache layer alone, and use a separate cache layer:

const { RESTDataSource } = require('apollo-datasource-rest');
import { PrefixingKeyValueCache } from 'apollo-server-caching';

class MoviesAPI extends RESTDataSource {
  initialize(config) {
    super.initialize(config);
    this.movieCache = new PrefixingKeyValueCache(config.cache, 'movies:');
  }

  async getMovie(id) {
    const cached = await this.movieCache.get(id);
    if (cached) return cached;

    const movie = await this.get(`movies/${id}`);
    await this.movieCache.set(id, movie);
    return movie;
  }

  async updateMovie(id, data) {
    const movie = await this.put(`movies/${id}`, data);

    await this.movieCache.delete(id);

    return movie;
  }
}

It's still using the application cache, but with a different prefix than the HTTP cache.

Ropez
  • 3,485
  • 3
  • 28
  • 30
0

The HTTPCache can be cleared by resetting the store manually:

this.httpCache.keyValueCache.wrapped.store.reset()

David Hellsing
  • 106,495
  • 44
  • 176
  • 212