Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,9 @@ public final class Api {

public static final String BASE_URL = "https://api.postcode.gov.ng";

/** Characters of autocomplete text sent. A full code with its separators is 15. */
private static final int MAX_PARTIAL = 64;

// Responses are read as a tree and checked by hand: data binding would turn a missing
// boolean into false, and a renamed field into "not assigned".
/** Levels of nesting a body may have: what serde_json, behind the Rust crate, reads. */
Expand Down Expand Up @@ -57,13 +60,17 @@ public static Request<Lookup> lookup(Postcode code) {
/**
* Suggests completions for a partial postcode such as {@code EK 01 A}.
*
* @throws IllegalArgumentException for a blank {@code partial}: the live API never answers one
* @throws IllegalArgumentException for a blank {@code partial}, which the live API never answers,
* or one over 64 characters
*/
public static Request<Autocomplete> autocomplete(String partial) {
// Unicode White_Space, as the other implementations trim: isBlank() keeps a no-break space.
if (partial.chars().allMatch(c -> Character.isSpaceChar(c) || (c >= '\t' && c <= '\r') || c == 0x85)) {
throw new IllegalArgumentException("partial must not be empty");
}
if (partial.codePointCount(0, partial.length()) > MAX_PARTIAL) {
throw new IllegalArgumentException("partial is over " + MAX_PARTIAL + " characters");
}
return new Request<>("/v1/search/autocomplete", List.of(Map.entry("q", partial)), Api::readAutocomplete);
}

Expand Down
10 changes: 9 additions & 1 deletion js/packages/ng-postcode-js/src/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ import { Postcode, SEGMENTS, type Segment, trimWhiteSpace } from "./postcode.js"

export const BASE_URL = "https://api.postcode.gov.ng";

/** Characters of autocomplete text sent. A full code with its separators is 15. */
const MAX_PARTIAL = 64;

/** A GET request whose successful response decodes to `T`. */
export interface Request<T> {
readonly path: string;
Expand Down Expand Up @@ -137,11 +140,16 @@ export function lookup(code: Postcode, level = 1): Request<Lookup> {
/**
* Suggest completions for a partial postcode such as `EK 01 A`.
*
* Throws `RangeError` for an empty `partial`: the live API never answers one.
* Throws `RangeError` for an empty `partial`, which the live API never answers, or one
* over 64 characters.
*/
export function autocomplete(partial: string): Request<Autocomplete> {
if (typeof partial !== "string") throw new TypeError("partial must be text");
if (!trimWhiteSpace(partial)) throw new RangeError("partial must not be empty");
// Spread counts characters, where `length` counts an emoji as two.
if ([...partial].length > MAX_PARTIAL) {
throw new RangeError(`partial is over ${MAX_PARTIAL} characters`);
}
return { path: "/v1/search/autocomplete", params: [["q", partial]], read: readAutocomplete };
}

Expand Down
8 changes: 7 additions & 1 deletion python/src/ng_postcode/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@

BASE_URL = "https://api.postcode.gov.ng"

_MAX_PARTIAL = 64
"""Characters of autocomplete text sent. A full code with its separators is 15."""

_MAX_DEPTH = 127
"""Levels of nesting a body may have: what serde_json, behind the Rust crate, reads."""

Expand Down Expand Up @@ -161,12 +164,15 @@ def lookup(code: Postcode, level: int = 1) -> Request[Lookup]:
def autocomplete(partial: str) -> Request[Autocomplete]:
"""Suggest completions for a partial postcode such as `EK 01 A`.

Raises `ValueError` for an empty `partial`: the live API never answers one.
Raises `ValueError` for an empty `partial`, which the live API never answers, or one
over 64 characters.
"""
if not isinstance(partial, str):
raise TypeError(f"partial must be text, got {partial!r}")
if not partial.strip(WHITE_SPACE):
raise ValueError("partial must not be empty")
if len(partial) > _MAX_PARTIAL:
raise ValueError(f"partial is over {_MAX_PARTIAL} characters")
return Request("/v1/search/autocomplete", (("q", partial),), _autocomplete)


Expand Down
3 changes: 3 additions & 0 deletions spec/requests.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@
{ "name": "autocomplete_next_line", "request": "autocomplete", "args": {"q": "\u0085"}, "sends": null },
{ "name": "autocomplete_control_character", "request": "autocomplete", "args": {"q": "\u001c"}, "sends": {"path": "/v1/search/autocomplete", "query": [["q", "\u001c"]]} },
{ "name": "autocomplete_blank", "request": "autocomplete", "args": {"q": " "}, "sends": null },
{ "name": "autocomplete_at_the_length_limit", "request": "autocomplete", "args": {"q": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"}, "sends": {"path": "/v1/search/autocomplete", "query": [["q", "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"]]} },
{ "name": "autocomplete_limit_counts_characters", "request": "autocomplete", "args": {"q": "\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00"}, "sends": {"path": "/v1/search/autocomplete", "query": [["q", "\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00\ud83d\ude00"]]} },
{ "name": "autocomplete_too_long", "request": "autocomplete", "args": {"q": "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"}, "sends": null },
{ "name": "reverse", "request": "reverse", "args": {"lat": 7.6211, "lng": 5.2214}, "sends": {"path": "/v1/search/reverse", "query": [["lat", "7.6211"], ["lng", "5.2214"]]} },
{ "name": "reverse_within", "request": "reverse", "args": {"lat": 7.6211, "lng": 5.2214, "metres": 100}, "sends": {"path": "/v1/search/reverse", "query": [["lat", "7.6211"], ["lng", "5.2214"], ["max_distance_m", "100"]]} },
{ "name": "nearby_within", "request": "nearby", "args": {"lat": 7.6211, "lng": 5.2214, "metres": 62.5}, "sends": {"path": "/v1/search/nearby", "query": [["lat", "7.6211"], ["lng", "5.2214"], ["radius", "62.5"]]} },
Expand Down
11 changes: 11 additions & 0 deletions src/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ use crate::{Postcode, Segment};

pub const BASE_URL: &str = "https://api.postcode.gov.ng";

/// Characters of autocomplete text sent. A full code with its separators is 15.
const MAX_PARTIAL: usize = 64;

/// A GET request whose successful response decodes to `T`.
#[derive(Clone, Debug)]
pub struct Request<T> {
Expand Down Expand Up @@ -41,6 +44,8 @@ pub enum InvalidRequest {
Level(u8),
/// The autocomplete text is empty, which the live API never answers.
EmptyQuery,
/// The autocomplete text is over 64 characters.
QueryTooLong,
/// The named coordinate or distance is not a finite number.
NotFinite(&'static str),
/// The named coordinate is off the globe: latitude beyond 90, or longitude beyond 180.
Expand All @@ -64,6 +69,9 @@ pub fn autocomplete(partial: &str) -> Result<Request<Autocomplete>, InvalidReque
if partial.trim().is_empty() {
return Err(InvalidRequest::EmptyQuery);
}
if partial.chars().count() > MAX_PARTIAL {
return Err(InvalidRequest::QueryTooLong);
}
let query = [("q", partial.to_owned())];
Ok(Request::get(
"/v1/search/autocomplete",
Expand Down Expand Up @@ -341,6 +349,9 @@ impl fmt::Display for InvalidRequest {
match self {
Self::Level(level) => write!(f, "level must be 1 to 5, got {level}"),
Self::EmptyQuery => f.write_str("autocomplete text must not be empty"),
Self::QueryTooLong => {
write!(f, "autocomplete text is over {MAX_PARTIAL} characters")
}
Self::NotFinite(name) => write!(f, "{name} must be a finite number"),
Self::OutOfRange(name) => write!(f, "{name} is off the globe"),
Self::Negative(name) => write!(f, "{name} must not be negative"),
Expand Down
Loading