I’m trying to pass a bound method to a function, but I can’t quite figure out the syntax. It seems like javascript wants to somehow differentiate between an unbound method and a bound method, but where the calling context changes that. (Most programming languages simply define a method as a bound class function).
What’s the syntax for passing a bound method to a function, and then calling that bound method in the new scope?
Here’s the relevant snippets
const mongoose = require('mongoose');
const caching = require('../lib/caching')
const Blog = mongoose.model('Blog');
// This is where I'm trying to pass a method to another function. I'm unclear of the syntax here
Blog.find = caching.makeCachable(Blog.find.bind(Blog), Blog)
module.exports = app => {
app.get('/api/blogs', requireLogin, async (req, res) => {
let blogs = await Blog.find({_user: req.user.id});
return res.send(blogs);
});
// ... other routes
}
caching.js
const util = require('util');
const redis = require('redis');
const client = redis.createClient('redis://localhost:6379');
const asyncGet = util.promisify(client.get).bind(client);
const DEFAULT_CACHING = [
'EX', 60 * 60 * 1,//caching expires after 4 hours
]
// This is where I take the method and pass it on to another function. I hope this just passes through
function makeCachable(method, thisObject) {
console.log(method, thisObject, `${method.className}.${method.name}`);
return cachedQuery.bind(method, `${thisObject.className}.${method.name}`);
}
async function cachedQuery(queryFunction, queryKey, queryParams=null, cacheConfig=DEFAULT_CACHING) {
//check redis before executing queryFunction
const redisKey = JSON.stringify([queryKey, queryParams]);
const cacheValue = await asyncGet(redisKey);
if(cacheValue) {
return JSON.parse(cacheValue);
}
// This is where I try to call the bound method
const blogs = await queryFunction.call(queryParams);
if(blogs) {
client.set(redisKey, JSON.stringify(blogs), ...cacheConfig);
}
return blogs;
}
exports.makeCachable = makeCachable;