Skip to content

Commit

Permalink
👌 IMPROVE: added books get route
Browse files Browse the repository at this point in the history
  • Loading branch information
hyper-dot committed Oct 13, 2024
1 parent f6932cf commit ddbde62
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 0 deletions.
6 changes: 6 additions & 0 deletions src/app/sales/product/product.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,10 @@ export class ProductController {
await this.service.addNewProduct(req.body, user);
return res.json({ message: 'Product created successfully' });
});

getAllProducts = asyncWrapper(async (req, res) => {
const user = req.userId;
const data = await this.service.getAllProducts(user);
return res.json({ message: 'Products fetched successfully', data });
});
}
1 change: 1 addition & 0 deletions src/app/sales/product/product.routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ class ProductRouter {
}

mountRoutes() {
this.router.get('/', this.controller.getAllProducts);
this.router.post('/', this.controller.addnewProduct);
}
}
Expand Down
22 changes: 22 additions & 0 deletions src/app/sales/product/product.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,32 @@ import { productSchema, TProductSchema } from '../../../schema/product.schema';
import { BadRequestError } from '../../../utils/exceptions';

export class ProductService {
async getAllProducts(user: string) {
const products = await ProductModel.find({ user });
const productsWithTotalQty = products.map((product) => {
const totalQty = product.batches.reduce(
(sum, batch) => sum + batch.qty,
0,
);

// Return the product object with the additional totalQty field
return {
...product.toObject(), // Convert the product document to a plain JS object
totalQty,
};
});

return productsWithTotalQty;
}

async addNewProduct(payload: TProductSchema, user: string) {
const { data, success } = productSchema.safeParse(payload);
if (!success) throw new BadRequestError('Invalid payload format');

const existingProduct = await ProductModel.findOne({ name: data.name });
console.log('EXISTING PRODUCT', existingProduct);
if (existingProduct) throw new BadRequestError('Product exist already');

const batches = [
{
batchNo: 1,
Expand Down

0 comments on commit ddbde62

Please sign in to comment.