【问题标题】:How to invalidate cache in Apollo Server RESTDataSource如何使 Apollo Server RESTDataSource 中的缓存无效
【发布时间】:2021-04-22 14:17:21
【问题描述】:

使用来自documentation 的简单“电影 API”示例。我在getMovie函数中添加了ttl,这样结果就缓存了10分钟。如何使updateMovie函数中的缓存失效?

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;
  }
}

我知道传递给 ApolloServer 的KeyValueCache 接口提供了一个delete 函数。但是,此对象似乎并未在数据源中公开。它被包裹在HTTPCache 中,它只公开了一个fetch 函数。 KeyValueCache 也包裹在 PrefixingKeyValueCache 中,因此假设 RESTDataSource 的内部实现,如果没有一些讨厌的黑客攻击,似乎几乎不可能在缓存中隐藏某些东西。

【问题讨论】:

    标签: caching apollo-server apollo-datasource-rest


    【解决方案1】:

    似乎我能找到的最佳解决方案是只保留 HTTP 缓存层,并使用单独的缓存层:

    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;
      }
    }
    

    它仍在使用应用程序缓存,但前缀与 HTTP 缓存不同。

    【讨论】:

      猜你喜欢
      • 2018-12-05
      • 2020-09-25
      • 2019-02-03
      • 2020-09-13
      • 2021-11-25
      • 2019-03-26
      • 2018-04-19
      • 2019-04-10
      • 1970-01-01
      相关资源
      最近更新 更多