1

使用文档中的简单“电影 API”示例。我ttlgetMovie函数中添加了一个,以便将结果缓存 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;
  }
}

我知道KeyValueCache传递给 ApolloServer 的接口提供了一个delete功能。但是,此对象似乎并未在数据源中公开。它被包裹在里面HTTPCache,它只暴露一个fetch函数。KeyValueCache也被包裹在 a中PrefixingKeyValueCache,因此假设RESTDataSource.

4

1 回答 1

4

似乎我能找到的最佳解决方案是只保留 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 缓存不同。

于 2020-04-09T09:11:54.213 回答