Skip to content

Instantly share code, notes, and snippets.

@msfidelis
Created December 28, 2017 21:35
Show Gist options
  • Save msfidelis/5862c3888162695c95bab9cc2298bb93 to your computer and use it in GitHub Desktop.
Save msfidelis/5862c3888162695c95bab9cc2298bb93 to your computer and use it in GitHub Desktop.
module.exports = [
{
method: "GET",
path: "/products",
handler: (req, res) => {
// Paginations configs
let page = req.query.page || 1;
let limit = req.query.limit || 10;
let options = {
select: '_id name price',
limit: limit,
page: page
};
let query = {};
// Optional Filters
if (req.query.tag) {
query.tags = req.query.tag;
}
if (req.query.name) {
query.name = new RegExp(`^${req.query.name}`, "i");
}
let searchhash = hash.sha1(JSON.stringify(query) + JSON.stringify(options));
// Procura a busca no cache do redis
cache.getAsync(searchhash)
.then(listcache => {
if (listcache) {
//Responde o cache para o usuário
console.log("Veio do cache");
listcache = JSON.parse(listcache);
res(listcache);
} else {
console.log("Não veio do cache");
ProductsSchema
.paginate(query, options)
.then(products => {
//Seta o Item no cache com expiracão de 2 minutos e responde o request
cache.setAsync(searchhash, JSON.stringify(products), 'EX', 120)
.then(success => {
res(products);
}).catch(err => {
res(Boom.internal(err));
});
})
.catch(err => {
res(err);
});
}
});
},
config: {
validate: {
query: {
page: Joi.number(),
limit: Joi.number(),
tag: Joi.string(),
name: Joi.string()
}
}
}
}
// ...
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment