Examples · server · 338 of 339
shop
A small shop backend: typed routes, an agent behind a route, a voice line, and request input that the compiler keeps away from outside code.
tin run examples/server/shop.tin// A small shop backend: typed routes, an agent behind a route, a voice line, and request input
// that the compiler keeps away from outside code. Run it: tin serve examples/server/shop.tin
type Item = { id: int, name: string, cents: int }
/// Answers questions about the shop's teapots.
agent Support { model: "mock", system: "You help customers of a teapot shop. Be brief." }
/// Talks to customers who call in.
voice agent Phone { model: "mock" }
fn catalog(): Item[] => [Item { id: 1, name: "teapot", cents: 2400 }, Item { id: 2, name: "kettle", cents: 3900 }]
fn find(id: int): Option<Item> {
for it in catalog() {
if it.id == id {
return Some(it)
}
}
None
}
server Shop grants [net.listen(8080), model] {
agents: [Support]
get "/items" (req) => catalog()
get "/items/:id" (req): Result<Item, string> {
match parseInt(req.params.getOr("id", "")) {
Some(id) => match find(id) {
Some(it) => Ok(it),
None => Err("no item {id}"),
},
None => Err("an item id is a number"),
}
}
post "/ask" (req) => Support(req.body)
ws "/phone" = Phone
}