Прототип драйвера узла mongodb для метода Array для использования Redis - PullRequest
0 голосов
/ 03 апреля 2020

Следуя курсу удэми Node JS: Расширенные понятия от @Stephen Grider.

Существует часть, использующая Redis внутри собственного метода query.exe c из Mon goose с использованием прототипа:

const mongoose = require('mongoose');
const exec = mongoose.Query.prototype.exec;
mongoose.Query.prototype.exec = function (){
   ...
   return exec.apply(this, arguments);
}

пытался реплицировать в драйвер узла mongodb вместо mon goose тот же лог c, который сначала создавал прототип mon go find ( Collection -> Collection. prototype.find = deprecateOptions () и кое-что работало с проблемой, когда получение кэшированного значения представляет собой строку, которая анализирует и получает json, но ожидается, что метод find возвращает курсор.

Существует проблема, если попытаться создать курсор, в конечном итоге будет следовать за обычным потоком mongodb, и он получит доступ к БД, что, как мне кажется, должно произойти.

const mongodb = require('mongodb');
const find = mongodb.Collection.prototype.find;
mongodb.Collection.prototype.find = async function () {
        try {
            console.log('IM ABOUT TO RUN A FIND!!!')
            console.log(util.inspect(arguments))

            const key = JSON.stringify(Object.assign({}, arguments, {
                collection: this.s.namespace.collection
            }))

            //to check to see if this query has already been executed
            //and if it has return the result right away (reads from redis instead of mongo)
            const cachedValue = await client.get(key);

            if(cachedValue){
                console.log('cachedValue:'+cachedValue)
                //from the cached value string convert to json
                const cachedValueObj = JSON.parse(cachedValue);
                //now convert this json into a mongodb cursor if possible
                console.log(`cached this value is: ${util.inspect(this.s.topology.cursor)}`)
                console.log(`and the arguments are: ${util.inspect(arguments)}`)

                const cacheValueCursor = new this.s.topology.cursor(this, this.s.namespace,findCommand, newOptions), newOptions)
                return cacheValueCursor;//cachedValueObj;

            }

            //other wise issue the query *as normal* 
            const result = await find.apply(this, arguments);
            let arrayResult = await result.toArray();
            client.set(key,JSON.stringify(arrayResult));
            console.log(`result cursor is!!!: ${util.inspect(result)}`)

            return result//returns the cursor as expected

            //return find.apply(this, arguments);

        } catch (error) {
            console.log(`cachedValue error is: ${error}`);
        }
    }

Так что вместо find требуется прототип toArray метод, так как ожидается, что он вернет json так же, как тот, который был извлечен из кэшированной версии redis (после разбора), но тот, где застрял, не может найти Cursor.prototype.toArray в репозитории mongodb

пытался выполнить следующее, но, похоже, не работает и в этом методе toArray может предотвратить доступ к БД или произойдет, если это произойдет, если это даст случай вверх в этой реализации будет помещен redis вдоль моих вызовов mongodb find ...

const toArray = mongodb.Cursor.prototype.toArray;

mongodb.Cursor.prototype.toArray = async function () {
    console.log(`mongodb.Collection.prototype.toArray this: ${util.inspect(this)}`);//${util.inspect(this)}
    return toArray.apply(this, arguments);
}
...