From 1e6d99a713d12e8f7d4d62e279fa1d46ac711d27 Mon Sep 17 00:00:00 2001 From: Patrick <50352812+Mueller-Patrick@users.noreply.github.com> Date: Thu, 20 May 2021 20:59:50 +0200 Subject: [PATCH] BETTERZON-116: Adding API endpoint for searching a new product (#62) --- .../src/models/products/products.router.ts | 23 ++++++++++++++ .../src/models/products/products.service.ts | 30 +++++++++++++++++++ 2 files changed, 53 insertions(+) diff --git a/Backend/src/models/products/products.router.ts b/Backend/src/models/products/products.router.ts index dd332e5..115d655 100644 --- a/Backend/src/models/products/products.router.ts +++ b/Backend/src/models/products/products.router.ts @@ -106,3 +106,26 @@ productsRouter.get('/vendor/:id', async (req: Request, res: Response) => { res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'})); } }); + +// POST products/ +productsRouter.post('/', async (req: Request, res: Response) => { + const asin: string = req.body.asin; + + if (!asin) { + res.status(400).send('Missing parameters.'); + return; + } + + try { + const result: boolean = await ProductService.addNewProduct(asin); + + if (result) { + res.sendStatus(201); + } else { + res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'})); + } + } catch (e) { + console.log('Error handling a request: ' + e.message); + res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'})); + } +}); diff --git a/Backend/src/models/products/products.service.ts b/Backend/src/models/products/products.service.ts index 7d397ab..4dd03a8 100644 --- a/Backend/src/models/products/products.service.ts +++ b/Backend/src/models/products/products.service.ts @@ -17,6 +17,7 @@ const pool = mariadb.createPool({ import {Product} from './product.interface'; import {Products} from './products.interface'; +import * as http from 'http'; /** @@ -197,3 +198,32 @@ export const findByVendor = async (id: number): Promise => { return prodRows; }; + +/** + * Makes a callout to a crawler instance to search for the requested product + * @param asin The amazon asin of the product to look for + */ +export const addNewProduct = async (asin: string): Promise => { + try { + let options = { + host: 'crawl.p4ddy.com', + path: '/searchNew', + port: '443', + method: 'POST' + }; + + let req = http.request(options, res => { + return res.statusCode === 202; + }); + req.write(JSON.stringify({ + asin: asin, + key: process.env.CRAWLER_ACCESS_KEY + })); + req.end(); + } catch (err) { + console.log(err); + throw(err); + } + + return false; +};