Last active
July 2, 2021 20:41
-
-
Save rmcfadzean/4790d02ba9b2ccca196312b61ffbba84 to your computer and use it in GitHub Desktop.
Playing around with xstate & Copilot
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
import { createMachine } from 'xstate'; | |
interface Booking { | |
id: string; | |
flight: Flight; | |
paid: boolean; | |
} | |
interface Passenger { | |
name: string; | |
bookings: Booking[]; | |
} | |
interface Flight { | |
from: string; | |
to: string; | |
date: Date; | |
} | |
// xstate machine for flight bookings |
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
const booking = createMachine<Booking>({ | |
id: 'booking', | |
initial: 'pending', | |
context: { | |
passengers: [], | |
}, | |
states: { | |
pending: { | |
on: { | |
PENDING: { | |
target: 'pending', | |
cond: (c) => c.passengers.length === 0, | |
}, | |
BOOK: { | |
actions: assign<Booking>({ | |
id: () => { | |
const now = new Date(); | |
return `${now.getFullYear()}-${now.getMonth() + 1}-${now.getDate()}-${now.getTime()}`; | |
}, | |
}), | |
target: 'booked', | |
cond: (c) => c.passengers.length > 0, | |
}, | |
CANCEL: 'cancelled', | |
}, | |
}, | |
booked: { | |
on: { | |
CANCEL: 'pending', | |
}, | |
}, | |
cancelled: { | |
on: { | |
PENDING: 'pending', | |
}, | |
}, | |
}, | |
}); | |
// xstate machine for passengers | |
const passenger = createMachine<Passenger>({ | |
id: 'passenger', | |
initial: 'pending', | |
context: { | |
bookings: [], | |
}, | |
states: { | |
pending: { | |
on: { | |
PENDING: 'pending', | |
BOOK: { | |
target: 'booked', | |
cond: (c) => c.bookings.length === 0, | |
}, | |
}, | |
}, | |
booked: { | |
on: { | |
CANCEL: 'pending', | |
}, | |
}, | |
}, | |
}); | |
const flight = createMachine<Flight>({ | |
id: 'flight', | |
initial: 'pending', | |
context: { | |
passengers: [], | |
}, | |
states: { | |
pending: { | |
on: { | |
PENDING: { | |
target: 'pending', | |
cond: (c) => c.passengers.length === | |
// ran out of characters I guess |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment