'use strict';
/**
* The ETag Management API
* @exports zanata/etag
*
* @requires fs
* @requires mkdirp
* @requires path
* @requires zanata/etagCacheCollection
*/
const fs = require('fs');
const ETagCacheCollection = require('./etagCacheCollection.js');
const ETagVersion = 1;
const mkdirp = require('mkdirp');
const path = require('path');
/**
* @class
* @classdesc The ETag class to read/write.
*/
class ETag {
/**
*
*
* @param {string} file - The place of the ETag file
*
* @throws {TypeError} Version mismatch
*/
constructor(file) {
if (!(this instanceof ETag)) {
throw new TypeError('Unable to call a class as a function');
}
this.file = file;
try {
let data = fs.readFileSync(file);
let json = JSON.parse(data);
if (json.version && json.version == ETagVersion)
this.collection = new ETagCacheCollection(JSON.parse(data));
else
throw new TypeError('Version mismatch');
} catch (e) {
this.collection = new ETagCacheCollection();
}
this.collection.cache.version = ETagVersion;
}
/**
* Store the ETag caches into the file
*/
save() {
mkdirp(path.dirname(this.file), (e) => {
if (e)
throw e;
});
fs.writeFileSync(this.file, this.collection.toJSON());
return this;
}
/**
* The callback type that is invoked from {@link module:zanata/etag~ETag#find}.
*
* @callback findCallback
* @param {module:zanata/etagCache~ETagCache} cache
*/
/**
* Seach the ETag cache from the collections.
*
* @param {string} docId - the document id
* @param {string} versionId - the version id
* @param {string} lang - the language name
* @param {module:zanata/etag~findCallback} cb - the callback function to obtain the result
*/
find(docId, versionId, lang, cb) {
cb(this.collection.get(docId, versionId, lang));
return this;
}
/**
* Add a cache into the collection
*
* @param {module:zanata/etagCache~ETagCache} cache - the cache object
*/
add(cache) {
this.collection.add(cache);
return this;
}
}
module.exports = ETag;