Skip to content

Instantly share code, notes, and snippets.

@mpj
Created May 21, 2019 12:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mpj/d9ebdec7d0f91abfa04dc51368dbc509 to your computer and use it in GitHub Desktop.
Save mpj/d9ebdec7d0f91abfa04dc51368dbc509 to your computer and use it in GitHub Desktop.
//@ts-check
const util = require('util')
const fs = require('fs')
const path = require('path')
const writeFile = util.promisify(require('fs').writeFile)
const readFile = util.promisify(require('fs').readFile)
function createSniffer({
fixtureDirectory,
dummy = false
}) {
if (dummy) {
return function sniffDummy(_, fn) {
return fn
}
}
if (!fs.existsSync(fixtureDirectory)) {
throw new Error('fixture directory must exist')
}
async function sniff(filename, fn) {
const cacheFilePath = path.join(fixtureDirectory, filename + '.json',)
if (fs.existsSync(cacheFilePath)) {
const data = await readFile(cacheFilePath, 'utf8')
if (data !== '') return JSON.parse(data)
}
const result = await fn()
writeFile(cacheFilePath, JSON.stringify(result, null, 2))
return result
}
sniff.off = function (filename, fn) {
const cacheFilePath = path.join(fixtureDirectory, filename + '.json')
writeFile(cacheFilePath, '', 'utf8')
return sniff(cacheFilePath, fn)
}
return sniff
}
module.exports = createSniffer
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment