Skip to content

Instantly share code, notes, and snippets.

@lorensr
Created April 2, 2020 09:12
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lorensr/5250fd77779fcc14466bcc5cd5f69a72 to your computer and use it in GitHub Desktop.
Save lorensr/5250fd77779fcc14466bcc5cd5f69a72 to your computer and use it in GitHub Desktop.
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