Last active
March 3, 2023 08:18
-
-
Save dyrkow/e710a78f6907f122c3fd33404b5fc741 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
export interface IUseCase<TRequest, TResponse> { | |
execute(request?: TRequest): Promise<TResponse> | |
} | |
class AddProductToOrderUseCase implements IUseCase<Identifier, Promise<void>> { | |
protected productRepository: IProductRepository; | |
protected orderRepository: IOrderRepository; | |
async execute(productId: Identifier) { | |
const order = await this.orderRepository.getCurrent(); | |
const product = await this.productRepository.getById(productId); | |
order.addProduct(product); | |
await this.orderRepository.save(order); | |
} | |
} | |
class GetMenuProductsUseCase implements IUseCase<void, Promise<Product[]>> { | |
protected productRepository: IProductRepository; | |
async execute() { | |
const products = await this.productRepository.getAll(); | |
return products.map(ProductMapper.toDTO); | |
} | |
} | |
const useDraftOrder = () => { | |
const [products, setProducts] = useState([]); | |
const orderRepository = new ReduxDraftOrderRepository(store); | |
const productRepository = new ReduxProductRepository(store); | |
const addProductToOrderUseCase = AddProductToOrderUseCase(orderRepository, productRepository); | |
const getMenuProductsUseCase = GetMenuProductsUseCase(productRepository); | |
useEffect(() => { | |
getMenuProductsUseCase.execute().then(setProducts).catch(() => {}) | |
}, []); | |
const onAddProduct = (productId: string) => addProductToOrderUseCase.execute(productId); | |
return [products, onAddProduct]; | |
} | |
const OrderView = () => { | |
const [products, onAddProduct] = useDraftOrder(); | |
const renderItem = (props) => { | |
<div>{props.item.name}<button onClick={() => onAddProduct(props.item.id)}></button></div> | |
} | |
return ( | |
<div> | |
<FlatList renderItem={renderItem}/> | |
</div> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment