Skip to content

Instantly share code, notes, and snippets.

@danielrearden
Created October 12, 2017 13:32
Show Gist options
  • Save danielrearden/41c707930bd2563d55baa753bb5f73ff to your computer and use it in GitHub Desktop.
Save danielrearden/41c707930bd2563d55baa753bb5f73ff to your computer and use it in GitHub Desktop.
queryWrapper
import crypto from 'crypto'
import redis from 'services/redis'
export async function queryWrapper (query, ttl) {
// these could also be passed explicitly to the function, but that may leave more room for error?
let table, method
query.modify(qb => {
table = qb._table || 'some_fallback'
method = qb._method
})
// if this is a SELECT query, attempt to read/write from cache
if (method === 'select' || method === 'first') {
const hashedQuery = crypto.createHash('md5').update(query.toString()).digest('hex')
const cached = redis.get(`${table}:${hashedQuery}`)
if (cached) return JSON.parse(cached)
const queryResult = await query
redis.set(`${table}:${hashedQuery}`, JSON.stringify(queryResult))
if (ttl) redis.expire(`${table}:${hashedQuery}`, ttl)
return queryResult
}
// if this isn't a SELECT query, invalidate all keys for this table
const keys = await redis.keys(`${table}:`)
await redis.del(keys)
return query
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment