heyomi
heyomi

Reputation: 415

How to implement custom Apollo Server KeyValueCache?

I'm looking for a working example of Apollo Server Caching using a custom KeyValueCache implementation - https://www.npmjs.com/package/apollo-server-caching

This is a snippet of what I'm currently working with.

export default class MyCache implements KeyValueCache {
  cachedInfo: [];

  async set(key: string, value: string, options?: KeyValueCacheSetOptions): Promise<void> {
    this.cachedInfo[key] = value;
  }

  async get(key: string): Promise<string | undefined> {
    if (this.cachedInfo[key]) return this.cachedInfo[key];
  }

  async delete(key: string): Promise<boolean> {
    this.cachedInfo[key] = null;
    return this.cachedInfo[key] === null;
  }
}

So far, each query throws an error ...

 "message": "Cannot read property 'fqc:1e5108601dcce15b1e80befed8f799d75322c573a873d274ec466adc4bd52f59' of undefined"

The cachedInfo is empty so nothing will be returned. I don't know what I'm missing.

Any help is appreciated.

Upvotes: 1

Views: 954

Answers (1)

Lin Du
Lin Du

Reputation: 102527

Property cachedInfo has no initializer and is not definitely assigned in the constructor.

Change cachedInfo: [] to cachedInfo = {}; will solve the issue.

A working example: https://github.com/mrdulin/apollo-graphql-tutorial/tree/master/src/stackoverflow/60977550

Upvotes: 1

Related Questions