@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.
85 lines (84 loc) • 2.92 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 storage item for saving and loading
* DID metadata and keys.
*/
class StorageItem {
/**
* Constructs a new instance on the @see StorageItem class.
* @param name of the DID.
* @param initialState of the DID.
* @param keys associated with the DID.
*/
constructor(name, initialState, keys) {
this.name = name;
this.initialState = initialState;
this.keys = keys;
/**
* Storage item version.
*/
this.version = 'v0.2.1';
/**
* Flag indicating whether the DID has been
* published to the network.
*/
this.published = false;
this.created = new Date();
}
/**
* Checks if the specified storage item exists.
* @param directory from which to load the storage item.
* @param name of the storage item to load.
*/
static exists(directory, name) {
if (!directory) {
throw new Error('A directory is required.');
}
if (!name) {
throw new Error('A name is required.');
}
// Check if the file exists.
const storageItemPath = path.join(directory, `${name}.json`);
return fs.existsSync(storageItemPath);
}
/**
* Loads the DID with @param name from the specified directory.
* @param directory from which to load the DID.
* @param name of the DID to load.
*/
static async load(directory, name) {
if (!directory) {
throw new Error('A directory is required.');
}
if (!name) {
throw new Error('A name is required.');
}
// Load the DID from the directory and
// return
const storageItemPath = path.join(directory, `${name}.json`);
const storageItemJson = await fs.readJson(storageItemPath, { encoding: 'utf-8' });
return class_transformer_1.plainToClass(StorageItem, storageItemJson);
}
/**
* Saves the instance of the DID to specified directory
* as a json file.
* @param directory to save the DID 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);
await fs.mkdir(basePath, { recursive: true });
// Write the json to file
const storageItemPath = path.join(directory, `${this.name}.json`);
await fs.writeJSON(storageItemPath, this, { spaces: 2 });
}
}
exports.default = StorageItem;