После запроса к базе данных я получаю массив объектов, которые я назвал queryResult. Как я могу:
Сохранить массив объектов в кеше redis?
Обновить кэш redis по мере заполнения базы данных?
Вот пример того, как может выглядеть queryResult:
const queryResult=[
{
username: 'name1',
prop1: 'some string',
prop2: 'another string',
prop3: 'another string 2'
},
{
username: 'name2',
prop1: 'some string',
prop2: 'another string',
prop3: 'another string 2'
},
{
username: 'name3',
prop1: 'some string',
prop2: 'another string',
prop3: 'another string 2'
},...
]
Я пытался использовать get
, hget
, set
, hmset
et c но они не работали. Вот последнее, что я попробовал:
Промежуточное программное обеспечение кэша
function cache(req, res, next) {
const { username } = req.params;
client.get(username, (err, data) = {
if(err) throw err;
if(data !== null){
return res.send(setResponse(username, JSON.parse(data)));
}
next();
})
}
// controller/function handler
async function getRepos(req, res, next) {
try {
console.log('fetching...');
const { username } = req.params;
const resp = await fetch(`https://api.github.com/users/${username}`);
const result = await resp.json();
// set redis cache
client.set(username, JSON.stringify(result));
return res.send(setResponse(username, result));
} catch (error) {
console.error(error);
}
}
app.get('/repos/:username', cache, getRepos);