Container[operation] = function()

in src/plugins/MongoosePlugin.ts [93:151]


    Container[operation] = function () {
      let span = ContextManager.currentSpan;

      if ((span as any)?.mongooseInCall)
        // mongoose has called into itself internally
        return _original.apply(this, arguments);

      const host = `${this.db.host}:${this.db.port}`;
      span = ContextManager.current.newExitSpan('Mongoose/' + operation, Component.MONGOOSE, Component.MONGODB);

      span.start();

      try {
        span.component = Component.MONGOOSE;
        span.layer = SpanLayer.DATABASE; // mongodb may not actually be called so we set these here in case
        span.peer = host;

        span.tag(Tag.dbType('MongoDB'));
        span.tag(Tag.dbInstance(this.db.name));

        const hasCB = typeof arguments[arguments.length - 1] === 'function';

        if (hasCB) {
          const wrappedCallback = wrapCallback(span, arguments[arguments.length - 1], 0);

          arguments[arguments.length - 1] = function () {
            // in case of immediate synchronous callback from mongoose
            (span as any).mongooseInCall = false;

            wrappedCallback.apply(this, arguments as any);
          };
        }

        (span as any).mongooseInCall = true; // if mongoose calls into itself while executing this operation then ignore it
        let ret = _original.apply(this, arguments);
        (span as any).mongooseInCall = false;

        if (!hasCB) {
          if (ret && typeof ret.then === 'function') {
            // generic Promise check
            ret = wrapPromise(span, ret);
          } else {
            // no callback passed in and no Promise or Cursor returned, play it safe
            span.stop();

            return ret;
          }
        }

        span.async();

        return ret;
      } catch (err) {
        span.error(err);
        span.stop();

        throw err;
      }
    };