refactor lookups to separate functions

This allows them to be used separately.
This commit is contained in:
Johann150 2023-06-10 11:20:02 +02:00 committed by stuebinm
parent 913f865fbd
commit a7823fc059

View file

@ -86,35 +86,40 @@ fn unpercent(encoded: String) -> String {
res
}
fn the_lookup(
/// Looks up a query in a Map by exact value, no fuzzy matching.
fn lookup_exact(query: String, lookup: Map(String, String)) -> #(Int, String) {
case map.get(lookup, query) {
Ok(result) -> #(200, result)
_ -> #(404, "??")
}
}
/// Looks up a station by its name, with fuzzy matching.
fn lookup_by_name(
query: String,
stations: Map(String, String),
ds100s: Map(String, String),
fuzzy: fn(String) -> List(String)
) -> #(Int, String) {
case map.get(ds100s, query) {
Ok(name) -> #(200, name)
io.println(query)
case map.get(stations, query) {
Ok(ds100) -> #(200, ds100)
_ -> {
io.println(query)
case map.get(stations, query) {
Ok(ds100) -> #(200, ds100)
_ -> {
let results = fuzzy(query)
|> list.filter_map(fn (res) { map.get(ds100s, string.uppercase(res)) })
case results {
// results -> {
// let names = results
// |> list.map (fn (res) {
// map.get(ds100s, string.uppercase(res))
// |> result.map(fn(a) { "/" <> a })
// |> result.unwrap("/")})
// #(200, string.join(names, "\n"))
// }
[res] -> #(302, res)
[res, ..] -> #(302, res)
_ -> #(404, "??")
}
}
let results = fuzzy(query)
|> list.filter_map(fn (res) { map.get(ds100s, string.uppercase(res)) })
case results {
// results -> {
// let names = results
// |> list.map (fn (res) {
// map.get(ds100s, string.uppercase(res))
// |> result.map(fn(a) { "/" <> a })
// |> result.unwrap("/")})
// #(200, string.join(names, "\n"))
// }
[res] -> #(302, res)
[res, ..] -> #(302, res)
_ -> #(404, "??")
}
}
}
@ -135,8 +140,16 @@ fn lookup_station(
200,
"ds100 → Name: " <> baseurl <> "/NN\n" <> "Name → ds100: " <> baseurl <> "/Nürnberg Hbf",
)
Request(method: Get, path: "/" <> path, ..) ->
the_lookup(unpercent(path), stations, ds100s, fuzzy)
Request(method: Get, path: "/" <> path, ..) -> {
let path = unpercent(path)
let by_ds100 = lookup_exact(path, ds100s)
case by_ds100.0 {
200 -> by_ds100
_ -> lookup_by_name(path, stations, ds100s, fuzzy)
}
}
_ -> #(404, "intended usage is e.g. curl " <> baseurl <> "/FF")
}
let body = bit_builder.from_string(text)