Skip to content

Instantly share code, notes, and snippets.

Avatar
🏠
Working from home

Loren ☺️ lorensr

🏠
Working from home
View GitHub Profile
View FooDataSource-structure.js
import { DataSource } from 'apollo-datasource'
import { InMemoryLRUCache } from 'apollo-server-caching'
import DataLoader from 'dataloader'
class FooDataSource extends DataSource {
constructor(dbClient) { ... }
initialize({ context, cache } = {}) { ... }
didEncounterError(error) { ... }
View resolvers.js
const resolvers = {
Query: {
getFoo: (_, { id }, context) =>
context.dataSources.myFoos.get(id, { ttlInSeconds: 60 })
},
Mutation: {
updateFoo: async (_, { id, fields }, context) => {
if (context.isAdmin) {
context.dataSources.myFoos.updateFields(id, fields)
}
View dataSources.js
import FooClient from 'imaginary-foo-library'
import MyFooDB from './MyFooDB'
const fooClient = new FooClient({ uri: 'https://foo.graphql.guide:9001' })
const server = new ApolloServer({
typeDefs,
resolvers,
dataSources: () => ({
View MyFooDB.js
import FooDataSource from './FooDataSource'
import { reportError } from './utils'
export default class MyFooDB extends FooDataSource {
async updateFields(id, fields) {
const doc = await this.get(id)
return this.update(id, {
...doc,
...fields
})
View FooDataSource-update.js
async update(id, newDoc) {
try {
await this.db.update(id, newDoc)
this.cache.delete(this.cacheKey(id))
} catch (error) {
this.didEncounterError(error)
}
}
View FooDataSource-get.js
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 })
View FooDataSource-cacheKey.js
cacheKey(id) {
return `foo-${this.db.connectionURI}-${id}`
}
View FooDataSource-initialize.js
import { InMemoryLRUCache } from 'apollo-server-caching'
...
initialize({ context, cache } = {}) {
this.context = context
this.cache = cache || new InMemoryLRUCache()
}
View FooDataSource-constructor.js
import { DataSource } from 'apollo-datasource'
import DataLoader from 'dataloader'
class FooDataSource extends DataSource {
constructor(dbClient) {
super()
this.db = dbClient
this.loader = new DataLoader(ids => dbClient.getByIds(ids))
}
You can’t perform that action at this time.