import { DataSource } from 'apollo-datasource' | |
import { InMemoryLRUCache } from 'apollo-server-caching' | |
import DataLoader from 'dataloader' | |
class FooDataSource extends DataSource { | |
constructor(dbClient) { | |
super() | |
this.db = dbClient | |
this.loader = new DataLoader(ids => dbClient.getByIds(ids)) | |
} | |
initialize({ context, cache } = {}) { | |
this.context = context | |
this.cache = cache || new InMemoryLRUCache() | |
} | |
didEncounterError(error) { | |
throw error | |
} | |
cacheKey(id) { | |
return `foo-${this.db.connectionURI}-${id}` | |
} | |
async get(id, { ttlInSeconds } = {}) { | |
const cacheDoc = await cache.get(this.cacheKey(id)) | |
if (cacheDoc) { | |
return JSON.parse(cacheDoc) | |
} | |
const doc = await this.loader.load(id) | |
if (ttlInSeconds) { | |
cache.set(this.cacheKey(id), JSON.stringify(doc), { ttl: ttlInSeconds }) | |
} | |
return doc | |
} | |
async update(id, newDoc) { | |
try { | |
await this.db.update(id, newDoc) | |
this.cache.delete(this.cacheKey(id)) | |
} catch (error) { | |
this.didEncounterError(error) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment