UNPKG

zamza

Version:

Apache Kafka discovery, indexing, searches, storage, hooks and HTTP gateway

93 lines (92 loc) 2.69 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const Debug = require("debug"); const debug = Debug("zamza:model:hookmodel"); const mongoose = require("mongoose"); class HookModel { constructor(zamza) { this.metrics = zamza.metrics; this.name = "hook"; this.model = null; } registerModel(passedMongoose, schemaConstructor) { const schemaDefinition = { name: String, endpoint: String, authorizationHeader: String, authorizationValue: String, disabled: Boolean, subscriptions: [ { topic: String, disabled: Boolean, ignoreReplay: Boolean, }, ], timestamp: Number, }; const schema = new schemaConstructor(schemaDefinition); // single index // schema.index({ name: 1, type: -1}); // compound index // schema.index({ name: 1, timestamp: 1 }, { unique: false }); this.model = passedMongoose.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."); } asObjectId(id) { if (typeof id === "object") { return id; } return mongoose.Types.ObjectId(id); } get(id) { return this.model.findOne({ _id: this.asObjectId(id) }).lean().exec(); } getForName(name) { return this.model.findOne({ name }).lean().exec(); } list() { return this.model.find({}).lean().exec().then((hooks) => { return hooks.map((hook) => { delete hook.__v; return hook; }); }); } upsert(hook) { let query = {}; if (hook._id) { query = { _id: this.asObjectId(hook._id), }; } else if (hook.name) { query = { name: hook.name, }; } const queryOptions = { upsert: true, new: true, }; return this.model.findOneAndUpdate(query, hook, queryOptions).exec(); } delete(id) { return this.model.deleteMany({ _id: this.asObjectId(id), }).exec(); } truncateCollection() { debug("Truncating collection"); return this.model.deleteMany({}).exec(); } } exports.HookModel = HookModel;