BETTERZON-97: Adding API endpoint to get all products listed by a specific vendor (#50)

This commit is contained in:
Patrick 2021-05-18 00:24:00 +02:00 committed by GitHub
parent 061d1a46e0
commit 16ed1070c2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 57 additions and 0 deletions

View File

@ -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.'}));
}
});

View File

@ -159,3 +159,41 @@ export const findList = async (ids: [number]): Promise<Products> => {
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<Products> => {
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;
};