zamza
Version:
Apache Kafka discovery, indexing, searches, storage, hooks and HTTP gateway
69 lines (68 loc) • 2.11 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const Debug = require("debug");
const debug = Debug("zamza:model:statemodel");
const STATE_KEYS = {
noModel: true,
ENABLE_METADATA_JOB: "enable_metadata_job",
};
exports.STATE_KEYS = STATE_KEYS;
const KNOWN_STATE_KEYS = Object.keys(STATE_KEYS).map((key) => STATE_KEYS[key]);
class StateModel {
constructor(zamza) {
this.metrics = zamza.metrics;
this.name = "state";
this.model = null;
}
registerModel(mongoose, schemaConstructor) {
const schemaDefinition = {
key: String,
val: String,
};
const schema = new schemaConstructor(schemaDefinition);
// single index
schema.index({ key: 1 }, { unique: true });
this.model = mongoose.model(this.name, schema);
this.model.on("index", (error) => {
if (error) {
debug("Index creation failed", error.message);
}
else {
debug("Index creation successfull.");
}
});
debug("Registered model with schema.");
}
list() {
return this.model.find({}).lean().exec();
}
get(key) {
return this.model.findOne({ key }).exec().then((result) => {
if (result) {
return result.val;
}
else {
return null;
}
});
}
set(key, val) {
if (KNOWN_STATE_KEYS.indexOf(key) === -1) {
throw new Error("Unknown shared state key: " + key);
}
debug("Changing shared state for", key, val);
const queryOptions = {
upsert: true,
};
return this.model.findOneAndUpdate({ key }, { key, val }, queryOptions).exec().then(() => val);
}
del(key) {
debug("Deleting shared state for", key);
return this.model.deleteOne({ key }).exec();
}
truncateCollection() {
debug("Truncating collection");
return this.model.deleteMany({}).exec();
}
}
exports.StateModel = StateModel;