@decentralized-identity/ion-cli
Version:
A Command Line Interface (CLI) to make working with the ION network and using ION DIDs easy peasy lemon squeezy.
90 lines (89 loc) • 3.18 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const class_transformer_1 = require("class-transformer");
const fs = require("fs-extra");
const path = require("path");
/**
* Class describing a cache item for saving and reading
* cached DIDs.
*/
class CacheItem {
/**
* Constructs a new instance on the @see Message class.
* @param name for the cache item.
* @param did being cached.
* @param document containing the latest state of the DID.
* @param lastResolved indicating the last time the cached item was resolved.
* @param published indicating whether the DID has been published to the network.
*/
constructor(name, did, document, lastResolved, published) {
this.name = name;
this.did = did;
this.document = document;
this.lastResolved = lastResolved;
this.published = published;
/**
* Package version.
*/
this.version = 'v0.2.0';
this.created = new Date();
}
/**
* Loads the cache item with @param name from the specified directory.
* @param directory that contains the cache.
* @param name of the cache item to read.
* @returns the cached item if found, otherwise undefined.
*/
static async read(directory, name) {
if (!directory) {
throw new Error('A directory is required.');
}
if (!name) {
throw new Error('A name is required.');
}
try {
// Load the cache item from the directory and
// return
const cacheItemPath = path.join(directory, `cache/${CacheItem.appendType(name)}`);
const cacheJson = await fs.readJson(cacheItemPath);
return class_transformer_1.plainToClass(CacheItem, cacheJson);
}
catch (error) {
// If the item is found, but is invalid
// rethrow the error.
if (error instanceof SyntaxError) {
throw error;
}
}
}
/**
* Saves the instance of the cache item to specified directory
* as a json file.
* @param directory to save the package to.
*/
async save(directory) {
if (!directory) {
throw new Error('A directory is required.');
}
// This will also create the specified directory if
// it does not exist.
const basePath = path.join(directory, 'cache');
await fs.mkdir(basePath, { recursive: true });
// Now save the item
const cacheItemPath = path.join(directory, `cache/${CacheItem.appendType(this.name)}`);
await fs.writeJSON(cacheItemPath, this, { spaces: 2 });
}
/**
* Checks to see if the file name includes the
* type '.json' and if not appends.
* @param fileName to check.
* @returns the filename with type appended.
*/
static appendType(fileName) {
if (fileName.endsWith('.json')) {
return fileName;
}
return `${fileName}.json`;
}
}
exports.default = CacheItem;