Created
January 3, 2018 15:29
-
-
Save msfidelis/9f1f7b2b1eab5e94e2079b3ddf7987d4 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 'use strict'; | |
| const Joi = require('joi'); | |
| const Boom = require('boom'); | |
| const Hash = require('take-my-hash'); | |
| const cache = require('../configs/cache'); | |
| const ProductService = require('../services/products'); | |
| module.exports = [ | |
| /** | |
| * Listagem de produtos | |
| * @default: Itens por página: 10 | |
| */ | |
| { | |
| method: "GET", | |
| path: "/products", | |
| handler: (req, res) => { | |
| // Paginations configs | |
| const page = req.query.page || 1; | |
| const limit = req.query.limit || 10; | |
| const options = { | |
| select: '_id name price', | |
| limit: limit, | |
| page: page | |
| }; | |
| const query = {}; | |
| // Filtros opcionais | |
| if (req.query.tag) { | |
| query.tags = req.query.tag; | |
| } | |
| if (req.query.name) { | |
| query.name = new RegExp(`^${req.query.name}`, "i"); | |
| } | |
| const searchhash = Hash.sha1(JSON.stringify(query) + JSON.stringify(options)); | |
| // Procura a busca no cache do redis | |
| cache.getAsync(searchhash) | |
| .then(listcache => { | |
| //Responde o cache para o usuário | |
| if (listcache) { | |
| listcache = JSON.parse(listcache); | |
| res(listcache); | |
| } else { | |
| ProductService | |
| .searchProductsWithPagination(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