Created
April 2, 2020 09:12
-
-
Save lorensr/5250fd77779fcc14466bcc5cd5f69a72 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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