smartnpm/ts/smartnpm.classes.registrycache.ts

64 lines
2.1 KiB
TypeScript
Raw Normal View History

2022-04-04 21:21:49 +00:00
import { NpmRegistry } from './smartnpm.classes.npmregistry.js';
import * as plugins from './smartnpm.plugins.js';
2021-04-26 08:30:02 +00:00
2021-05-10 16:12:11 +00:00
export interface ICacheDescriptor {
registryUrl: string;
packageName: string;
filePath: string;
distTag?: string;
version?: string;
}
2021-04-26 08:30:02 +00:00
export class RegistryCache {
npmregistryRef: NpmRegistry;
public levelCache: plugins.levelcache.LevelCache;
constructor(npmRegistryRefArg: NpmRegistry) {
this.npmregistryRef = npmRegistryRefArg;
this.levelCache = new plugins.levelcache.LevelCache({
cacheId: encodeURIComponent(this.npmregistryRef.options.npmRegistryUrl),
});
}
2023-07-25 16:14:51 +00:00
public async getCachedFile(
cacheDescriptorArg: ICacheDescriptor
): Promise<plugins.smartfile.Smartfile> {
const cacheEntry = await this.levelCache.retrieveCacheEntryByKey(
this.getCacheDescriptorAsString(cacheDescriptorArg)
);
2021-04-26 08:30:02 +00:00
if (cacheEntry) {
return plugins.smartfile.Smartfile.fromFoldedJson(cacheEntry.contents.toString());
}
return null;
}
2023-07-25 16:14:51 +00:00
public async cacheSmartFile(
cacheDescriptorArg: ICacheDescriptor,
smartfileArg: plugins.smartfile.Smartfile
) {
2021-05-10 16:12:11 +00:00
if (smartfileArg && cacheDescriptorArg.version) {
2023-07-25 16:14:51 +00:00
await this.levelCache.storeCacheEntryByKey(
this.getCacheDescriptorAsString(cacheDescriptorArg),
new plugins.levelcache.CacheEntry({
contents: Buffer.from(smartfileArg.foldToJson()),
ttl: plugins.smarttime.getMilliSecondsFromUnits({ hours: 1 }),
})
);
2021-05-10 16:12:11 +00:00
} else {
2023-07-25 16:14:51 +00:00
await this.levelCache.storeCacheEntryByKey(
this.getCacheDescriptorAsString(cacheDescriptorArg),
new plugins.levelcache.CacheEntry({
contents: Buffer.from(smartfileArg.foldToJson()),
ttl: plugins.smarttime.getMilliSecondsFromUnits({ minutes: 1 }),
})
);
2021-04-29 20:44:47 +00:00
}
2021-04-26 08:30:02 +00:00
}
2021-05-10 16:12:11 +00:00
public getCacheDescriptorAsString(cacheDescriptorArg?: ICacheDescriptor) {
2023-07-25 16:14:51 +00:00
return `${cacheDescriptorArg.registryUrl}//+//${cacheDescriptorArg.packageName}//+//${
cacheDescriptorArg.filePath
}//+//${cacheDescriptorArg.distTag || cacheDescriptorArg.version}`;
2021-05-10 16:12:11 +00:00
}
2023-07-25 16:14:51 +00:00
}