Created
November 13, 2023 11:08
-
-
Save BadMomber/09898b5888c4366bc680cd235bfc6630 to your computer and use it in GitHub Desktop.
Code as OOP and as FP
This file contains hidden or 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
| import {FORWARDS, START} from '@eventstore/db-client' | |
| import {client as eventStore} from './eventstore' | |
| interface Purchase { | |
| purchaseId: string | |
| name: string | |
| amount: number | |
| wasRefunded: boolean | |
| } | |
| // OOP Version of the code | |
| const getAllPurchases = async () => { | |
| const purchases: Purchase[] = [] | |
| const events = eventStore.readAll({ | |
| direction: FORWARDS, | |
| fromPosition: START, | |
| maxCount: 1000, | |
| }) | |
| for await (const {event} of events) { | |
| const data: any = event.data | |
| switch (event?.type) { | |
| case 'ProductPurchased': | |
| purchases.push({ | |
| purchaseId: data.purchaseId, | |
| amount: data.amount, | |
| name: data.name, | |
| wasRefunded: false, | |
| }) | |
| break | |
| case 'ProductRefunded': | |
| const purchase = getPurchaseById(purchases, data.purchaseId) | |
| if (purchase) { | |
| purchase.wasRefunded = true | |
| } | |
| break | |
| } | |
| } | |
| return purchases | |
| } | |
| function getPurchaseById(purchases: Purchase[], purchaseId: string) { | |
| return purchases.find((p: Purchase) => p.purchaseId === purchaseId) | |
| } | |
| export {getAllPurchases, Purchase} | |
| // FP Version of the code | |
| // const getAllPurchases = async () => { | |
| // const purchases: Purchase[] = [] | |
| // const getPurchaseById = createGetPurchaseById(purchases) | |
| // | |
| // const events = eventStore.readAll({ | |
| // direction: FORWARDS, | |
| // fromPosition: START, | |
| // maxCount: 1000, | |
| // }) | |
| // | |
| // for await (const {event} of events) { | |
| // const data: any = event.data | |
| // | |
| // switch (event?.type) { | |
| // case 'ProductPurchased': | |
| // purchases.push({ | |
| // purchaseId: data.purchaseId, | |
| // amount: data.amount, | |
| // name: data.name, | |
| // wasRefunded: false, | |
| // }) | |
| // break | |
| // | |
| // case 'ProductRefunded': | |
| // getPurchaseById(data.purchaseId).wasRefunded = true | |
| // break | |
| // } | |
| // } | |
| // | |
| // return purchases | |
| // } | |
| // | |
| // const createGetPurchaseById = (purchases: Purchase[]) => (purchaseId: string) => | |
| // purchases.filter((p) => p.purchaseId == purchaseId)[0] | |
| // | |
| // export {getAllPurchases, Purchase} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment