Skip to content

Instantly share code, notes, and snippets.

@BadMomber
Created November 13, 2023 11:08
Show Gist options
  • Save BadMomber/09898b5888c4366bc680cd235bfc6630 to your computer and use it in GitHub Desktop.
Save BadMomber/09898b5888c4366bc680cd235bfc6630 to your computer and use it in GitHub Desktop.
Code as OOP and as FP
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