Skip to content

Instantly share code, notes, and snippets.

@mpj mpj/sniffix.js
Created May 21, 2019

Embed
What would you like to do?
//@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
You can’t perform that action at this time.