UNPKG

mongoose-query-logger

Version:

![CI](https://github.com/marcosfede/mongoose-query-logger/workflows/CI/badge.svg) ![npm version](https://badgen.net/npm/v/mongoose-query-logger) ![types](https://badgen.net/npm/types/mongoose-query-logger) ![license](https://badgen.net/npm/license/mongoos

3 lines (2 loc) 12.9 kB
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var t,e=(t=require("chalk"))&&"object"==typeof t&&"default"in t?t.default:t;function n(t,e,n,r,o,i,a){try{var u=t[i](a),s=u.value}catch(t){return void n(t)}u.done?e(s):Promise.resolve(s).then(r,o)}function r(t){return function(){var e=this,r=arguments;return new Promise((function(o,i){var a=t.apply(e,r);function u(t){n(a,o,i,u,s,"next",t)}function s(t){n(a,o,i,u,s,"throw",t)}u(void 0)}))}}function o(){return(o=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var n=arguments[e];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(t[r]=n[r])}return t}).apply(this,arguments)}var i,a=(function(t){var e=function(t){var e=Object.prototype,n=e.hasOwnProperty,r="function"==typeof Symbol?Symbol:{},o=r.iterator||"@@iterator",i=r.asyncIterator||"@@asyncIterator",a=r.toStringTag||"@@toStringTag";function u(t,e,n){return Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}),t[e]}try{u({},"")}catch(t){u=function(t,e,n){return t[e]=n}}function s(t,e,n,r){var o=Object.create((e&&e.prototype instanceof f?e:f).prototype),i=new P(r||[]);return o._invoke=function(t,e,n){var r="suspendedStart";return function(o,i){if("executing"===r)throw new Error("Generator is already running");if("completed"===r){if("throw"===o)throw i;return{value:void 0,done:!0}}for(n.method=o,n.arg=i;;){var a=n.delegate;if(a){var u=x(a,n);if(u){if(u===l)continue;return u}}if("next"===n.method)n.sent=n._sent=n.arg;else if("throw"===n.method){if("suspendedStart"===r)throw r="completed",n.arg;n.dispatchException(n.arg)}else"return"===n.method&&n.abrupt("return",n.arg);r="executing";var s=c(t,e,n);if("normal"===s.type){if(r=n.done?"completed":"suspendedYield",s.arg===l)continue;return{value:s.arg,done:n.done}}"throw"===s.type&&(r="completed",n.method="throw",n.arg=s.arg)}}}(t,n,i),o}function c(t,e,n){try{return{type:"normal",arg:t.call(e,n)}}catch(t){return{type:"throw",arg:t}}}t.wrap=s;var l={};function f(){}function h(){}function p(){}var d={};d[o]=function(){return this};var g=Object.getPrototypeOf,v=g&&g(g(O([])));v&&v!==e&&n.call(v,o)&&(d=v);var y=p.prototype=f.prototype=Object.create(d);function m(t){["next","throw","return"].forEach((function(e){u(t,e,(function(t){return this._invoke(e,t)}))}))}function w(t,e){var r;this._invoke=function(o,i){function a(){return new e((function(r,a){!function r(o,i,a,u){var s=c(t[o],t,i);if("throw"!==s.type){var l=s.arg,f=l.value;return f&&"object"==typeof f&&n.call(f,"__await")?e.resolve(f.__await).then((function(t){r("next",t,a,u)}),(function(t){r("throw",t,a,u)})):e.resolve(f).then((function(t){l.value=t,a(l)}),(function(t){return r("throw",t,a,u)}))}u(s.arg)}(o,i,r,a)}))}return r=r?r.then(a,a):a()}}function x(t,e){var n=t.iterator[e.method];if(void 0===n){if(e.delegate=null,"throw"===e.method){if(t.iterator.return&&(e.method="return",e.arg=void 0,x(t,e),"throw"===e.method))return l;e.method="throw",e.arg=new TypeError("The iterator does not provide a 'throw' method")}return l}var r=c(n,t.iterator,e.arg);if("throw"===r.type)return e.method="throw",e.arg=r.arg,e.delegate=null,l;var o=r.arg;return o?o.done?(e[t.resultName]=o.value,e.next=t.nextLoc,"return"!==e.method&&(e.method="next",e.arg=void 0),e.delegate=null,l):o:(e.method="throw",e.arg=new TypeError("iterator result is not an object"),e.delegate=null,l)}function L(t){var e={tryLoc:t[0]};1 in t&&(e.catchLoc=t[1]),2 in t&&(e.finallyLoc=t[2],e.afterLoc=t[3]),this.tryEntries.push(e)}function _(t){var e=t.completion||{};e.type="normal",delete e.arg,t.completion=e}function P(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(L,this),this.reset(!0)}function O(t){if(t){var e=t[o];if(e)return e.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var r=-1,i=function e(){for(;++r<t.length;)if(n.call(t,r))return e.value=t[r],e.done=!1,e;return e.value=void 0,e.done=!0,e};return i.next=i}}return{next:b}}function b(){return{value:void 0,done:!0}}return h.prototype=y.constructor=p,p.constructor=h,h.displayName=u(p,a,"GeneratorFunction"),t.isGeneratorFunction=function(t){var e="function"==typeof t&&t.constructor;return!!e&&(e===h||"GeneratorFunction"===(e.displayName||e.name))},t.mark=function(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,p):(t.__proto__=p,u(t,a,"GeneratorFunction")),t.prototype=Object.create(y),t},t.awrap=function(t){return{__await:t}},m(w.prototype),w.prototype[i]=function(){return this},t.AsyncIterator=w,t.async=function(e,n,r,o,i){void 0===i&&(i=Promise);var a=new w(s(e,n,r,o),i);return t.isGeneratorFunction(n)?a:a.next().then((function(t){return t.done?t.value:a.next()}))},m(y),u(y,a,"Generator"),y[o]=function(){return this},y.toString=function(){return"[object Generator]"},t.keys=function(t){var e=[];for(var n in t)e.push(n);return e.reverse(),function n(){for(;e.length;){var r=e.pop();if(r in t)return n.value=r,n.done=!1,n}return n.done=!0,n}},t.values=O,P.prototype={constructor:P,reset:function(t){if(this.prev=0,this.next=0,this.sent=this._sent=void 0,this.done=!1,this.delegate=null,this.method="next",this.arg=void 0,this.tryEntries.forEach(_),!t)for(var e in this)"t"===e.charAt(0)&&n.call(this,e)&&!isNaN(+e.slice(1))&&(this[e]=void 0)},stop:function(){this.done=!0;var t=this.tryEntries[0].completion;if("throw"===t.type)throw t.arg;return this.rval},dispatchException:function(t){if(this.done)throw t;var e=this;function r(n,r){return a.type="throw",a.arg=t,e.next=n,r&&(e.method="next",e.arg=void 0),!!r}for(var o=this.tryEntries.length-1;o>=0;--o){var i=this.tryEntries[o],a=i.completion;if("root"===i.tryLoc)return r("end");if(i.tryLoc<=this.prev){var u=n.call(i,"catchLoc"),s=n.call(i,"finallyLoc");if(u&&s){if(this.prev<i.catchLoc)return r(i.catchLoc,!0);if(this.prev<i.finallyLoc)return r(i.finallyLoc)}else if(u){if(this.prev<i.catchLoc)return r(i.catchLoc,!0)}else{if(!s)throw new Error("try statement without catch or finally");if(this.prev<i.finallyLoc)return r(i.finallyLoc)}}}},abrupt:function(t,e){for(var r=this.tryEntries.length-1;r>=0;--r){var o=this.tryEntries[r];if(o.tryLoc<=this.prev&&n.call(o,"finallyLoc")&&this.prev<o.finallyLoc){var i=o;break}}i&&("break"===t||"continue"===t)&&i.tryLoc<=e&&e<=i.finallyLoc&&(i=null);var a=i?i.completion:{};return a.type=t,a.arg=e,i?(this.method="next",this.next=i.finallyLoc,l):this.complete(a)},complete:function(t,e){if("throw"===t.type)throw t.arg;return"break"===t.type||"continue"===t.type?this.next=t.arg:"return"===t.type?(this.rval=this.arg=t.arg,this.method="return",this.next="end"):"normal"===t.type&&e&&(this.next=e),l},finish:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var n=this.tryEntries[e];if(n.finallyLoc===t)return this.complete(n.completion,n.afterLoc),_(n),l}},catch:function(t){for(var e=this.tryEntries.length-1;e>=0;--e){var n=this.tryEntries[e];if(n.tryLoc===t){var r=n.completion;if("throw"===r.type){var o=r.arg;_(n)}return o}}throw new Error("illegal catch attempt")},delegateYield:function(t,e,n){return this.delegate={iterator:O(t),resultName:e,nextLoc:n},"next"===this.method&&(this.arg=void 0),l}},t}(t.exports);try{regeneratorRuntime=e}catch(t){Function("r","regeneratorRuntime = r")(e)}}(i={exports:{}}),i.exports);function u(t,e){var n={};return Object.keys(t).forEach((function(r){(function(t,e){return e.some((function(e){return e===t}))})(r,e)||(n[r]=t[r])})),n}function s(t,e){if(void 0===e&&(e="assertion failed"),!t)throw new Error(e)}function c(t){var e=[];return t.forEach((function(t){var n=function t(e,n){for(var r=0,o=Object.keys(e);r<o.length;r++){var i=o[r];if(i===n)return e[i];if(e[i]&&"object"==typeof e[i])return t(e[i],n)}}(t,"queryPlanner");n&&e.push(n)})),e}function l(t,e){return Array.isArray(e)&&e.length>100?e.slice(0,100).concat(e.length-100+" more items..."):e}function f(t,e){return JSON.stringify(t,l,e)}var h=["find","findOne","findOneAndUpdate","findOneAndRemove","findOneAndDelete","update","updateOne","updateMany","deleteOne","deleteMany"],p=["aggregate"],d=["count","countDocuments","estimatedDocumentCount"],g={targetMethods:["count","countDocuments","estimatedDocumentCount","find","findOne","findOneAndUpdate","findOneAndRemove","findOneAndDelete","update","updateOne","updateMany","deleteOne","deleteMany","aggregate"],explainMethods:["find","findOne","aggregate"],queryLogger:function(t,n){var r=t.operation,i=t.collectionName,a=t.executionTimeMS,u=t.filter,s=t.fields,c=t.options,l=t.update,h=t.additionalLogProperties;void 0===n&&(n=console.log);var p={};l&&(p.update=l),h&&(p=p?o({},p,{additionalLogProperties:h}):{additionalLogProperties:h});var d=[l,s,c].map((function(t){return t&&(e=t,0!==Object.keys(e).length||e.constructor!==Object)?f(t):null;var e})).filter((function(t){return t})),g=i+"."+r+"("+[f(u)].concat(d).join(", ")+")";n("mongoose: "+function(t){return t<100?e.green(t):t<1e3?e.yellow(t):e.red(t)}(a)+" ms "+g)},explainLogger:function(t,n){void 0===n&&(n=console.log),t.queryPlanners.forEach((function(t){var r=function(t){if(!t||0===t.length)return null;var n=t[0];return"IDHACK"===n.stage?null:"IXSCAN"===n.stage?e.green("IXSCAN "+f(n.keyPattern)):"COLLSCAN"===n.stage?e.red("COLLSCAN: "+f(t,4)):e.yellow("Stages: "+f(t,4))}(function(t){if(!t||!t.winningPlan)return console.error("no queryPlanner"),null;var e=[],n=t.winningPlan;for(e.push(u(n,["inputStage"]));void 0!==n.inputStage;)e.push(u(n=n.inputStage,["inputStage"]));return e.reverse(),e}(t));r&&n(r)}))},explain:!0,additionalLogProperties:!1};exports.MongooseQueryLogger=function(){function t(t){void 0===t&&(t={}),this.options=o({},g,t)}var e=t.prototype;return e.setQueryMethods=function(t){var e=void 0===t?{}:t,n=e.targetMethods,r=e.explainMethods;return n&&(this.options.targetMethods=n),r&&(this.options.explainMethods=r),this},e.setExplain=function(t){return void 0===t&&(t=!1),this.options.explain=t,this},e.setAdditionalLogProperties=function(t){return void 0===t&&(t=!1),this.options.additionalLogProperties=t,this},e.setQueryLogger=function(t){return this.options.queryLogger=t,this},e.setExplainLogger=function(t){return this.options.explainLogger=t,this},e.getPreQueryHook=function(){return function(){this.__startTime=Date.now()}},e.getPostQueryHook=function(){var t=this;return function(){try{s(null!==this.__startTime,"startTime was null"),s(this._collection,"no this._collection");var e={operation:this.op,collectionName:this._collection.collectionName,executionTimeMS:Date.now()-this.__startTime,filter:this._conditions,fields:this._fields,options:o({},this._options,this.options),update:this._update,additionalLogProperties:this.__additionalProperties};t.options.explain&&t.options.explainMethods.includes(this.op)?this._collection[this.op](this._conditions,o({explain:!0},this.options),(function(n,r){s(!n&&!!r,"error running explain"),Array.isArray(r)||(r=[r]);var i=c(r);s(0!==i.length,"no plans found"),t.options.queryLogger(e),t.options.explainLogger(o({},e,{queryPlanners:i}))})):t.options.queryLogger(e)}catch(t){console.error("Error in post middleware: ",t)}}},e.getPostAggregateHook=function(){var t=this;return r(a.mark((function e(){var n,r,i,u;return a.wrap((function(e){for(;;)switch(e.prev=e.next){case 0:if(e.prev=0,s(null!==this.__startTime,"startTime was null"),s(this._model,"no this._model"),r={operation:"aggregate",collectionName:this._model.collection.name,executionTimeMS:Date.now()-this.__startTime,filter:this._pipeline,fields:{},options:o({},this._options,this.options),update:{},additionalLogProperties:this.__additionalProperties},!t.options.explain||!t.options.explainMethods.includes("aggregate")||(null==(n=this.options)?void 0:n.explain)){e.next=15;break}return e.next=7,this._model.collection.collection.aggregate(this._pipeline,o({},this.options,{explain:!0})).toArray();case 7:i=e.sent,s(Array.isArray(i)&&i.length>0,"no aggregate explain"),s(0!==(u=c(i)).length,"no plans found"),t.options.queryLogger(r),t.options.explainLogger(o({},r,{queryPlanners:u})),e.next=16;break;case 15:t.options.queryLogger(r);case 16:e.next=21;break;case 18:e.prev=18,e.t0=e.catch(0),console.error("Error in post middleware: ",e.t0);case 21:case"end":return e.stop()}}),e,this,[[0,18]])})))},e.getPlugin=function(){var t=this;return function(e){t.options.additionalLogProperties&&(e.query.additionalLogProperties=function(t){return this.__additionalProperties=t,this}),t.options.targetMethods.filter((function(t){return h.includes(t)})).forEach((function(n){e.pre(n,t.getPreQueryHook()),e.post(n,t.getPostQueryHook())})),t.options.targetMethods.filter((function(t){return p.includes(t)})).forEach((function(n){e.pre(n,t.getPreQueryHook()),e.post(n,t.getPostAggregateHook())})),t.options.targetMethods.filter((function(t){return d.includes(t)})).forEach((function(n){e.pre(n,t.getPreQueryHook()),e.post(n,t.getPostQueryHook())}))}},t}(); //# sourceMappingURL=mongoose-query-logger.cjs.production.min.js.map