Created
December 16, 2020 16:44
-
-
Save radzserg/0c68f9f55bf1475578afd8fc4676ba94 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class OrderManager { | |
public createOrder(orderData): Order { | |
this.validate(orderData); | |
const order = new Order(orderData); | |
order.setTotalPrice(this.calculateTotal(orderData)); | |
this.pay(orderData) | |
await this.save(orderData); | |
return order; | |
} | |
private calculateTotal(orderData): number { | |
let totalPrice = orderData.items.reduce( (totalPrice, orderItem) => totalPrice + (orderItem.price * orderItem.quantity)); | |
totalPrice = totalPrice + totalPrice * 0.05; // add service commission | |
return totalPrice; | |
} | |
private validate(orderData) { | |
if (!orderData.items.length) { | |
throw new ValidationError("Cannot create an order: cart is empty"); | |
} | |
orderData.items.forEach((orderItem) => { | |
if (orderItem.productId === undefined || orderItem.quantity === undefined || orderItem.price === undefined) { | |
throw new ValidationError("Cannot create an order: product ID is missing"); | |
} | |
}) | |
} | |
private pay(orderData) { | |
const paymentGateway = new MyPaymentGateway(process.env.STRIPE_KEY); | |
paymentGateway.pay(orderData.totalPrice, orderData.paymentInfo); | |
} | |
private async save(orderData): Order { | |
await orderRepository.save(orderData); | |
return order; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment