From 16ed1070c2ba5c1f68db3bad49ee58c92990f4a3 Mon Sep 17 00:00:00 2001 From: Patrick <50352812+Mueller-Patrick@users.noreply.github.com> Date: Tue, 18 May 2021 00:24:00 +0200 Subject: [PATCH] BETTERZON-97: Adding API endpoint to get all products listed by a specific vendor (#50) --- .../src/models/products/products.router.ts | 19 ++++++++++ .../src/models/products/products.service.ts | 38 +++++++++++++++++++ 2 files changed, 57 insertions(+) diff --git a/Backend/src/models/products/products.router.ts b/Backend/src/models/products/products.router.ts index f0ea9a3..dd332e5 100644 --- a/Backend/src/models/products/products.router.ts +++ b/Backend/src/models/products/products.router.ts @@ -87,3 +87,22 @@ productsRouter.get('/list/:ids', async (req: Request, res: Response) => { res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'})); } }); + +// GET products/vendor/:id +productsRouter.get('/vendor/:id', async (req: Request, res: Response) => { + const id: number = parseInt(req.params.id, 10); + + if (!id) { + res.status(400).send('Missing parameters.'); + return; + } + + try { + const products: Products = await ProductService.findByVendor(id); + + res.status(200).send(products); + } 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 c0bee72..7d397ab 100644 --- a/Backend/src/models/products/products.service.ts +++ b/Backend/src/models/products/products.service.ts @@ -159,3 +159,41 @@ export const findList = async (ids: [number]): Promise => { return prodRows; }; + +/** + * Fetches and returns the products that the given vendor has price entries for + * @param id The id of the vendor to fetch the products for + */ +export const findByVendor = async (id: number): Promise => { + let conn; + let prodRows = []; + try { + conn = await pool.getConnection(); + + // Get the relevant product ids + let relevant_prod_ids = []; + const relevantProds = await conn.query('SELECT product_id FROM prices WHERE vendor_id = ? GROUP BY product_id', id); + for (let row in relevantProds) { + if (row !== 'meta') { + relevant_prod_ids.push(relevantProds[row].product_id); + } + } + + // Fetch products + const rows = await conn.query('SELECT product_id, name, asin, is_active, short_description, long_description, image_guid, date_added, last_modified, manufacturer_id, selling_rank, category_id FROM products WHERE product_id IN (?)', [relevant_prod_ids]); + for (let row in rows) { + if (row !== 'meta') { + prodRows.push(rows[row]); + } + } + + } catch (err) { + throw err; + } finally { + if (conn) { + conn.end(); + } + } + + return prodRows; +};