Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
private async _handleAsync(
request: IncomingMessage,
response: ServerResponse,
) {
debug(
'Incoming request %s %s',
request.method,
request.url,
request.headers,
);
const cacheKey = this._getCacheKey(request);
try {
const entry = await cacache.get(this._options.cachePath, cacheKey);
if (entry.metadata.createdAt + this._options.ttl > Date.now()) {
debug('Sending cached response for %s', cacheKey);
this._sendCachedEntry(entry.data, entry.metadata, response);
return;
}
debug('Cache entry expired for %s', cacheKey);
// (continue to forward the request)
} catch (error) {
if (error.code !== 'ENOENT') {
console.warn('Cannot load cached entry.', error);
}
debug('Cache miss for %s', cacheKey);
// (continue to forward the request)
}
await this._forwardRequest(request, response);
//
//
// Much slower way to get cache with pacote
//
// const promise = pacote
// .packument(
// pkgName,
// this.getPacoteOpts({
// offline: true,
// "full-metadata": true,
// "fetch-retries": 3
// })
// )
const promise = cacache
.get(this._cacheDir, cacheKey, { memoize: true })
.then(cached => {
foundCache = true;
const packument = JSON.parse(cached.data);
logger.debug("found", pkgName, "packument cache");
return queueMetaFetchRequest(packument);
})
.catch(err => {
if (foundCache) {
// the .then above threw an error - not expectec
throw err;
}
return queueMetaFetchRequest();
})
.then(meta => {
this._metaStat.done++;
.then(() => {
// If `cache` enabled, we try to get compressed source from cache, if cache doesn't found, we run `imagemin`.
if (options.cache) {
return cacache.get(cacheDir, cacheKey).then(
({ data }) => data,
() =>
runImagemin(
result.input,
imageminOptions
).then(optimizedSource =>
cacache
.put(cacheDir, cacheKey, optimizedSource)
.then(() => optimizedSource)
)
);
}
// If `cache` disable, we just run `imagemin`.
return runImagemin(result.input, imageminOptions);
})
cache.put(CACHE, KEY, CONTENTS, OPTS, function (err) {
if (err) { throw err }
cacache.get(CACHE, KEY, OPTS, function (err, data, meta) {
if (err) { throw err }
var memoized = cache._clearMemoized()[CACHE + ':' + KEY]
t.equal(data, CONTENTS, 'data in db correct')
t.ok(meta, 'got metadata')
delete meta.time
var target = {
path: path.join(CACHE, 'content', DIGEST),
key: KEY,
digest: DIGEST,
metadata: OPTS.metadata
}
t.deepEqual(meta, target, 'cache index entry correct')
t.deepEqual(memoized, {
data: data,
meta: OPTS.metadata
}, 'contents memoized')
async function fetchPackage(
{ registry, cache, expires = 5 * 60 * 1000 },
name,
now = Date.now()
) {
let meta = await cacache
.get(cache, `spackage:${name}`)
.then(xs => JSON.parse(String(xs.data)))
.catch(() => null);
if (!meta || now - Date.parse(meta.date) > Number(expires)) {
const pkgReq = await fetch(`${registry}/v1/packages/package/${name}`);
meta = {
date: Date.parse(pkgReq.headers.date),
data: await pkgReq.json()
};
if (pkgReq.status > 399) {
console.log(name, meta.data);
throw new Error();
}
async function fetchObject({ registry, cache }, integrity, load = false) {
const parsed = ssri.parse(integrity);
const algo = parsed.pickAlgorithm();
const [{ digest }] = parsed[algo];
if (digest === EMPTY_HASH && algo === 'sha512') {
return load ? { data: EMPTY_BUF } : true;
}
if (await cacache.get.hasContent(cache, integrity)) {
return load ? cacache.get(cache, integrity) : true;
}
const response = await fetch(
`${registry}/v1/objects/object/${algo}/${encodeURIComponent(digest)}`
);
if (response.status > 399) {
throw new Error('error fetching object');
}
let destIntegrity = null;
const dest = cacache.put.stream(cache, integrity);
dest.on('integrity', i => (destIntegrity = i));
await pipeline(response.body, dest);
if (!parsed.match(destIntegrity)) {
null,
getSyntheticMeta(imageOptions, meta),
imageOptions,
globalOptions,
loader,
),
);
}
const imageCacheKey = loader.resourcePath + hashOptions(imageOptions);
const metaCacheKey = `meta${imageCacheKey}`;
const bufferCacheKey = `buffer${imageCacheKey}`;
const cachedResult =
typeof globalOptions.cacheDir === 'string'
? Promise.all([
cacache
.get(globalOptions.cacheDir, bufferCacheKey)
.then(({data}) => {
return data;
})
.catch(() => Promise.resolve(null)),
cacache
.get(globalOptions.cacheDir, metaCacheKey)
.then(({data}) => {
return JSON.parse(data.toString('utf8'));
})
.catch(() => Promise.resolve(null)),
])
: Promise.resolve([null, null]);
const sharpResult = cachedResult.then(([buffer, info]) => {
if (buffer && info) {
);
}
const imageCacheKey = loader.resourcePath + hashOptions(imageOptions);
const metaCacheKey = `meta${imageCacheKey}`;
const bufferCacheKey = `buffer${imageCacheKey}`;
const cachedResult =
typeof globalOptions.cacheDir === 'string'
? Promise.all([
cacache
.get(globalOptions.cacheDir, bufferCacheKey)
.then(({data}) => {
return data;
})
.catch(() => Promise.resolve(null)),
cacache
.get(globalOptions.cacheDir, metaCacheKey)
.then(({data}) => {
return JSON.parse(data.toString('utf8'));
})
.catch(() => Promise.resolve(null)),
])
: Promise.resolve([null, null]);
const sharpResult = cachedResult.then(([buffer, info]) => {
if (buffer && info) {
return {buffer, info};
}
const generatedImage = new Promise(function(resolve, reject) {
const transformedImage = transformImage(image, meta, imageOptions);
transformedImage.toBuffer(function(err, buffer, info) {
if (err) {
.on('data', ({ key }) => {
promises.push(
cacache.get(this.path, key).then(({ data }) => {
cache[key] = JSON.parse(data);
}),
);
})
.on('error', reject)