Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Task 10 #3

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@ COPY --from=builder /usr/src/app/dist .
# Run the application as a non-root user.
USER node

ENV PORT=4000
EXPOSE 4000

CMD [ "node", "main.js" ]
4 changes: 2 additions & 2 deletions sql/init-tables.sql
Original file line number Diff line number Diff line change
Expand Up @@ -56,10 +56,10 @@ INSERT INTO carts (id, user_id, created_at, updated_at, status) VALUES
('36a181bf-eab9-4906-b01f-f68a779ad4d2', '277a20e5-5d1b-4d46-ab9a-d40378c015d8', '2023-12-21', '2023-12-22', 'OPEN');

INSERT INTO products (id, title, description, price) VALUES
('740c1845-c0f4-4587-87dd-78be1804f3b1', 'Kenya Kiringa Coffee', 'Like all Kenyan coffees, our Kiringa has a clean, fruity flavour and a subtle sweetness.', 20),
('740c1845-c0f4-4587-87dd-78be1804f3b1', 'Brazylia Santa Clara', 'The seeds come from natural processing, which suggests a high body and a specific dose of sweetness.', 20),
('61f30d6b-f1a2-4e8b-8158-d2e4987bf3b1', 'Drip Coffee Blend', 'Drip Coffee Blend is a mix of the highest quality beans from different parts of the world. ', 11),
('9670f8fe-ae3e-4286-990b-375a66bc7b95', 'Decaf Colombia Cauca Espresso', 'The beans of this coffee are a carefully selected blend of Arabica beans from the Colombian Cauca region. ', 12),
('bbb02a04-0f70-4075-872f-be580a0d0514', 'Fall Espresso', 'Delicious autumnal flavours and aromas wrapped up in a coffee bag - pleasantly tart red currant reminiscent of summer, juicy pomegranate and lots of sweetness tasting of honey and milk chocolate.', 14),
('bbb02a04-0f70-4075-872f-be580a0d0514', 'Burundi Mikuba', 'Bourbon variety, used from crops from the picturesque Mikuba hill in the Kayanza location.', 14),
('0d36c5e2-3bea-4ab3-bfc9-c66142fa0689', 'Ethiopia Yirga Beloya', 'More beans from Ethiopia - another temptation for the senses...', 15),
('dce6f5c8-092c-408b-bcbc-fd3c10dd211e', 'Costa Rica Las Lajas', 'Meet our latest filter COSTA RICA coffee from the Las Lajas farm, which comes from a semi-washed process, which is an intermediate method between washed and natural processing.', 16);

Expand Down
21 changes: 15 additions & 6 deletions src/cart/cart.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,16 +37,25 @@ export class CartController {
@UseGuards(BasicAuthGuard)
@Put()
async updateUserCart(@Req() req: AppRequest, @Body() body) { // TODO: validate body payload...
const cart = await this.cartService.updateCartItemsByUserId(getUserIdFromRequest(req), body)
const cart = await this.cartService.updateCartItemsByUserId(getUserIdFromRequest(req), body);

if (cart) {
return {
statusCode: HttpStatus.OK,
message: 'OK',
data: {
cart,
total: calculateCartTotal(cart),
}
};
}

return {
statusCode: HttpStatus.OK,
message: 'OK',
statusCode: HttpStatus.BAD_REQUEST,
data: {
cart,
total: calculateCartTotal(cart),
error: 'Product from DynamoDB does not exist in RDS.'
}
}
};
}

// @UseGuards(JwtAuthGuard)
Expand Down
7 changes: 5 additions & 2 deletions src/cart/models-rules/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,10 @@ import { Cart, CartItem } from '../models/cart';
* @returns {number}
*/
export function calculateCartTotal(cart: Cart): number {
return cart ? cart.items.reduce((acc: number, { product: { price }, count }: CartItem) => {
return acc += price * count;
return cart ? cart.items.reduce((acc: number, item: CartItem) => {
if (item.product) {
return acc += item.product.price * item.count;
}
return acc;
}, 0) : 0;
}
41 changes: 30 additions & 11 deletions src/cart/services/cart.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { InjectRepository } from '@nestjs/typeorm';
import { Carts } from 'src/db/entities/cart.entity';
import { Repository } from 'typeorm';
import { CartItems } from 'src/db/entities/cart-item.entity';
import { Products } from 'src/db/entities/products.entity';

@Injectable()
export class CartService {
Expand All @@ -15,6 +16,7 @@ export class CartService {
constructor(
@InjectRepository(Carts) private readonly cartRepo: Repository<Carts>,
@InjectRepository(CartItems) private readonly cartItemsRepo: Repository<CartItems>,
@InjectRepository(Products) private readonly productsRepo: Repository<Products>,
) {}

async findByUserId(userId: string): Promise<Cart> {
Expand Down Expand Up @@ -86,20 +88,25 @@ export class CartService {

async updateCartItemsByUserId(userId: string, cartItem: CartItem): Promise<Cart> {
const cart = await this.findOrCreateCartByUserId(userId);
const product = await this.findProductById(cartItem.product.id);

if (cartItem.count > 0) {
const item = await this.findByCartIdAndProductId(cart.id, cartItem.product.id);

if (item) {
await this.cartItemsRepo.update({ cart_id: cart.id, product_id: cartItem.product.id }, { count: cartItem.count });
if (product) {
if (cartItem.count > 0) {
const item = await this.findByCartIdAndProductId(cart.id, cartItem.product.id);

if (item) {
await this.cartItemsRepo.update({ cart_id: cart.id, product_id: cartItem.product.id }, { count: cartItem.count });
} else {
await this.createCartItemByCartId(cart.id, cartItem);
}
} else {
await this.createCartItemByCartId(cart.id, cartItem);
}
} else {
await this.cartItemsRepo.delete({ cart_id: cart.id, product_id: cartItem.product.id });
await this.cartItemsRepo.delete({ cart_id: cart.id, product_id: cartItem.product.id });
}

return this.findByUserId(userId);
}
return this.findByUserId(userId);

return null;
}

async updateCartByUserId(userId: string, status: CartStatuses): Promise<Cart> {
Expand All @@ -114,4 +121,16 @@ export class CartService {
// this.userCarts[ userId ] = null;
await this.cartRepo.delete({ user_id: userId });
}

async findProductById(productId: string): Promise<Products> {
try {
const product = await this.productsRepo.findOne({
where: { id: productId },
});
return product;
} catch(err) {
console.error(err);
return null;
}
}
}