From ae7948b2b822432dda4e3887ecf64e13be55d9ad Mon Sep 17 00:00:00 2001 From: clapscofield Date: Fri, 5 Mar 2021 18:06:41 -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 | 7 ++++++- services/inventory/index.js | 6 ++++++ 3 files changed, 17 insertions(+), 1 deletion(-) diff --git a/proto/inventory.proto b/proto/inventory.proto index c819783e..4f8edac7 100644 --- a/proto/inventory.proto +++ b/proto/inventory.proto @@ -2,6 +2,7 @@ syntax = "proto3"; service InventoryService { rpc SearchAllProducts(Empty) returns (ProductsResponse) {} + rpc SearchProductByID(Payload) returns (ProductResponse) {} } message Empty{} @@ -18,3 +19,7 @@ message ProductResponse { message ProductsResponse { repeated ProductResponse products = 1; } + +message Payload { + int32 id = 1; +} \ No newline at end of file diff --git a/services/controller/index.js b/services/controller/index.js index 19258e78..3525cb48 100644 --- a/services/controller/index.js +++ b/services/controller/index.js @@ -43,16 +43,21 @@ 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); } }); }); - /** * Inicia o router */ diff --git a/services/inventory/index.js b/services/inventory/index.js index 2eeabc9d..20bcd276 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(), () => {