Skip to content

Instantly share code, notes, and snippets.

@fvilante
Created April 13, 2019 22:57
Show Gist options
  • Save fvilante/35c74d634f0bc29547217e164e2a59ba to your computer and use it in GitHub Desktop.
Save fvilante/35c74d634f0bc29547217e164e2a59ba to your computer and use it in GitHub Desktop.
Paradox 3.0
// Demonstration of Core Concepts
// Event Source Reducer functional style and typesafe
// =========================
// Lib Event Source
// =========================
type UserDocument = object
type State = ReadonlyArray<object>
interface UserEvent<TDocument extends UserDocument> {
readonly kind: EventKind
readonly document: Partial<TDocument>
}
type EventReducer<
TDocument extends UserDocument,
TEvent extends UserEvent<TDocument>
> = (
document: TDocument,
event: TEvent
) =>
TDocument
const EventReducer = <
TDocument extends UserDocument,
TEvent extends UserEvent<TDocument>
>(
document: TDocument,
event: TEvent
) =>
({ ...document, ...event.document })
// =========================
// Client-Code
// =========================
// import { UserDocument, UserEvent, EventReducer } from './event_source'
// documents
interface Person extends UserDocument {
name: string
age: number
}
interface Address {
street: string
zipCode: number
}
// events
type ChangePersonName = (newName: string) => UserEvent<Person>
type ChangeAddressZipCode = (zipCode: number) => UserEvent<Address>
// -- implementation ---
const ChangePersonName: ChangePersonName =
name => ({
kind: "ChangePersonName",
document: { name }
})
const ChangeAddressZipCode: ChangeAddressZipCode =
zipCode => ({
kind: "ChangeAddressZipCode",
document: { zipCode }
})
// test - Generate Events
const initialPerson: Person = {
name: "Gustavo",
age: 666
}
const initialAddress: Address = {
street: "R. Roz",
zipCode: 7
}
// test
// ok -> no Error
const newPersonState = EventReducer(initialPerson,ChangePersonName("Flavio"))
// ok -> Error = imcompatible parameters
const newPersonState2 = EventReducer(initialAddress, ChangePersonName("Flavio"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment