From 3cad745e0cded969e2b51794f4a3f05857d023be Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marcos=20Vin=C3=ADcius?= Date: Thu, 11 Mar 2021 21:51:40 -0300 Subject: [PATCH] =?UTF-8?q?Tarefa=20pr=C3=A1tica=20#1=20-=20Microservices?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- proto/inventory.proto | 5 +++++ services/controller/index.js | 17 +++++++++++++++++ services/inventory/index.js | 6 ++++++ 3 files changed, 28 insertions(+) diff --git a/proto/inventory.proto b/proto/inventory.proto index c819783e..83e05025 100644 --- a/proto/inventory.proto +++ b/proto/inventory.proto @@ -2,6 +2,11 @@ syntax = "proto3"; service InventoryService { rpc SearchAllProducts(Empty) returns (ProductsResponse) {} + rpc SearchProductByID(Payload) returns (ProductResponse) {} +} + +message Payload { + int32 id = 1; } message Empty{} diff --git a/services/controller/index.js b/services/controller/index.js index 19258e78..6f669c89 100644 --- a/services/controller/index.js +++ b/services/controller/index.js @@ -42,6 +42,23 @@ app.get('/shipping/:cep', (req, res, next) => { ); }); +app.get('/product/:id', (req, res, next) => { + // Chama método do microsserviço. + inventory.SearchProductByID({ id: req.params.id }, (err, product) => { + // Se ocorrer algum erro de comunicação + // com o microsserviço, retorna para o navegador. + if (err) { + console.error(err); + res.status(500).send({ error: 'something failed :(' }); + } else { + // Caso contrário, retorna resultado do + // microsserviço (um arquivo JSON) com os dados + // do produto pesquisado + res.json(product); + } + }); +}); + app.get('/product/:id', (req, res, next) => { inventory.SearchProductByID({ id: req.params.id }, (err, product) => { if (err) { diff --git a/services/inventory/index.js b/services/inventory/index.js index 2eeabc9d..f4a1657d 100644 --- a/services/inventory/index.js +++ b/services/inventory/index.js @@ -20,6 +20,12 @@ server.addService(inventoryProto.InventoryService.service, { products: products, }); }, + SearchProductByID: (payload, callback) => { + callback( + null, + products.find((product) => product.id == payload.request.id) + ); + }, }); server.bindAsync('127.0.0.1:3002', grpc.ServerCredentials.createInsecure(), () => {