Created
May 21, 2019 12:56
-
-
Save mpj/d9ebdec7d0f91abfa04dc51368dbc509 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
//@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