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,16 +86,23 @@ fn unpercent(encoded: String) -> String {
res 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, query: String,
stations: Map(String, String), stations: Map(String, String),
ds100s: Map(String, String), ds100s: Map(String, String),
fuzzy: fn(String) -> List(String) fuzzy: fn(String) -> List(String)
) -> #(Int, String) { ) -> #(Int, String) {
case map.get(ds100s, query) {
Ok(name) -> #(200, name)
_ -> {
io.println(query) io.println(query)
case map.get(stations, query) { case map.get(stations, query) {
Ok(ds100) -> #(200, ds100) Ok(ds100) -> #(200, ds100)
_ -> { _ -> {
@ -117,8 +124,6 @@ fn the_lookup(
} }
} }
} }
}
}
fn lookup_station( fn lookup_station(
request: Request(t), request: Request(t),
@ -135,8 +140,16 @@ fn lookup_station(
200, 200,
"ds100 → Name: " <> baseurl <> "/NN\n" <> "Name → ds100: " <> baseurl <> "/Nürnberg Hbf", "ds100 → Name: " <> baseurl <> "/NN\n" <> "Name → ds100: " <> baseurl <> "/Nürnberg Hbf",
) )
Request(method: Get, path: "/" <> path, ..) -> Request(method: Get, path: "/" <> path, ..) -> {
the_lookup(unpercent(path), stations, ds100s, fuzzy) 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") _ -> #(404, "intended usage is e.g. curl " <> baseurl <> "/FF")
} }
let body = bit_builder.from_string(text) let body = bit_builder.from_string(text)