Omit redundant short_label, full_label, and level from GET /regions.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Ilya Mukhortov 2026-09-18 10:32:29 +10:00
parent fa6c1db46d
commit 9ab9baca48
4 changed files with 78 additions and 16 deletions

View File

@ -34,7 +34,7 @@ UI и API ищут жилой адрес так: **Субъект РФ → на
## Подписи в UI ## Подписи в UI
Код: `client/src/App.jsx`. Порядок как в адресе: крупное → мелкое. Субъект РФ (`level === 1`) не пишем. Поле показывает `option.label`. JSON: `label` — только объект, `short_label` — срез шага, `full_label` — вся цепочка с субъектом. Вложенный `parent` только при `include_parent=true` (по умолчанию false); `parent_id` всегда есть. `compact=true` — только `fias_id`, `label`, `short_label`, `level`, `region_code`, `full_label`; `include_parent` в этом режиме не действует. Код: `client/src/App.jsx`. Порядок как в адресе: крупное → мелкое. Субъект РФ (`level === 1`) не пишем. Поле показывает `option.label`. JSON: `label` — только объект, `short_label` — срез шага, `full_label` — вся цепочка с субъектом. У `GET /regions` нет `short_label`, `full_label` и `level` (они совпадают с `label` / всегда 1). Вложенный `parent` только при `include_parent=true` (по умолчанию false); `parent_id` всегда есть. `compact=true` — только `fias_id`, `label`, `short_label`, `level`, `region_code`, `full_label`; для регионов — `fias_id`, `label`, `region_code`. `include_parent` в этом режиме не действует.
Полный адрес `Приморский край, Надеждинский р-н, п. Западный, тер. СНТ Маргаритка, ул. Агатовая` делится так: Полный адрес `Приморский край, Надеждинский р-н, п. Западный, тер. СНТ Маргаритка, ул. Агатовая` делится так:

View File

@ -25,7 +25,7 @@ from .models import AddressObject, House, format_region_code
api = NinjaAPI(title="FIAS Address API", version="1.0.0", docs_url="docs/") api = NinjaAPI(title="FIAS Address API", version="1.0.0", docs_url="docs/")
class AddressNodeOut(Schema): class RegionOut(Schema):
id: int id: int
fias_id: UUID fias_id: UUID
object_id: int | None object_id: int | None
@ -33,10 +33,9 @@ class AddressNodeOut(Schema):
name: str name: str
type_name: str type_name: str
label: str label: str
level: int
region_code: str region_code: str
kladr_id: str kladr_id: str
parent: "AddressNodeOut | None" = None parent: "RegionOut | None" = None
@staticmethod @staticmethod
def resolve_region_code(obj: AddressObject) -> str: def resolve_region_code(obj: AddressObject) -> str:
@ -47,6 +46,11 @@ class AddressNodeOut(Schema):
return getattr(obj, "label", None) or address_label(obj.type_name, obj.name) return getattr(obj, "label", None) or address_label(obj.type_name, obj.name)
class AddressNodeOut(RegionOut):
level: int
parent: "AddressNodeOut | None" = None
class AddressOut(AddressNodeOut): class AddressOut(AddressNodeOut):
full_label: str full_label: str
short_label: str short_label: str
@ -111,6 +115,11 @@ class SearchResponse(Schema):
items: list[AddressOut] items: list[AddressOut]
class RegionSearchResponse(Schema):
count: int
items: list[RegionOut]
class AddressCompactOut(Schema): class AddressCompactOut(Schema):
fias_id: UUID fias_id: UUID
label: str label: str
@ -192,9 +201,12 @@ def present_addresses(result: SearchResult, include_parent: bool) -> SearchResul
) )
def compact_address(obj) -> dict: REGION_COMPACT_KEYS = ("fias_id", "label", "region_code")
def compact_address(obj, *, keys: tuple[str, ...] | None = None) -> dict:
view = obj if isinstance(obj, AddressView) else AddressView(obj, include_parent=True) view = obj if isinstance(obj, AddressView) else AddressView(obj, include_parent=True)
return { payload = {
"fias_id": view.fias_id, "fias_id": view.fias_id,
"label": view.label, "label": view.label,
"short_label": view.resolved_short_label, "short_label": view.resolved_short_label,
@ -202,14 +214,22 @@ def compact_address(obj) -> dict:
"region_code": format_region_code(view.region_code), "region_code": format_region_code(view.region_code),
"full_label": view.resolved_full_label, "full_label": view.resolved_full_label,
} }
if keys is None:
return payload
return {key: payload[key] for key in keys}
def present_search(result: SearchResult, params: SearchParams): def present_search(
result: SearchResult,
params: SearchParams,
*,
compact_keys: tuple[str, ...] | None = None,
):
if params.compact: if params.compact:
return JsonResponse( return JsonResponse(
{ {
"count": result.count, "count": result.count,
"items": [compact_address(item) for item in result.items], "items": [compact_address(item, keys=compact_keys) for item in result.items],
}, },
encoder=DjangoJSONEncoder, encoder=DjangoJSONEncoder,
) )
@ -553,9 +573,13 @@ def health(request):
return {"status": "ok"} return {"status": "ok"}
@api.get("regions", response=SearchResponse, tags=["addresses"]) @api.get("regions", response=RegionSearchResponse, tags=["addresses"])
def regions(request, params: Query[SearchParams]): def regions(request, params: Query[SearchParams]):
return present_search(search((AddressObject.Level.REGION,), params), params) return present_search(
search((AddressObject.Level.REGION,), params),
params,
compact_keys=REGION_COMPACT_KEYS,
)
@api.get("cities", response=SearchResponse, tags=["addresses"]) @api.get("cities", response=SearchResponse, tags=["addresses"])

View File

@ -45,6 +45,7 @@ def test_search_city(addresses):
COMPACT_KEYS = {"fias_id", "label", "short_label", "level", "region_code", "full_label"} COMPACT_KEYS = {"fias_id", "label", "short_label", "level", "region_code", "full_label"}
REGION_COMPACT_KEYS = {"fias_id", "label", "region_code"}
@pytest.mark.django_db @pytest.mark.django_db
@ -86,6 +87,17 @@ def test_compact_ignores_include_parent(addresses):
assert "parent" not in item assert "parent" not in item
@pytest.mark.django_db
def test_compact_regions_omit_label_slices_and_level(addresses):
response = Client().get(api_url("regions"), {"query": "прим", "compact": "true"})
assert response.status_code == 200
item = response.json()["items"][0]
assert set(item) == REGION_COMPACT_KEYS
assert item["label"] == "Приморский край"
assert item["region_code"] == "25"
@pytest.mark.django_db @pytest.mark.django_db
def test_address_label_avoids_type_repetition(addresses): def test_address_label_avoids_type_repetition(addresses):
region, city = addresses region, city = addresses
@ -105,7 +117,9 @@ def test_address_label_avoids_type_repetition(addresses):
) )
assert region_response.json()["items"][0]["label"] == "Приморский край" assert region_response.json()["items"][0]["label"] == "Приморский край"
assert region_response.json()["items"][0]["full_label"] == "Приморский край" assert "short_label" not in region_response.json()["items"][0]
assert "full_label" not in region_response.json()["items"][0]
assert "level" not in region_response.json()["items"][0]
assert street_response.json()["items"][0]["label"] == "снт Актинидия" assert street_response.json()["items"][0]["label"] == "снт Актинидия"
assert street_response.json()["items"][0]["short_label"] == "снт Актинидия" assert street_response.json()["items"][0]["short_label"] == "снт Актинидия"
assert street_response.json()["items"][0]["full_label"] == "Приморский край, г Владивосток, снт Актинидия" assert street_response.json()["items"][0]["full_label"] == "Приморский край, г Владивосток, снт Актинидия"

View File

@ -110,6 +110,15 @@ function toAddressOption(address) {
}; };
} }
function toRegionOption(address) {
return {
value: address.fias_id,
label: address.label || addressTitle(address),
meta: `Субъект РФ · ${address.region_code}`,
address,
};
}
function toStreetOption(address) { function toStreetOption(address) {
return { return {
value: address.fias_id, value: address.fias_id,
@ -153,6 +162,15 @@ function compactAddress(address) {
}; };
} }
function compactRegion(address) {
if (!address) return null;
return {
fias_id: address.fias_id,
label: address.label || addressTitle(address),
region_code: address.region_code,
};
}
async function loadAddresses(path, query, extra, minLength = 2, toOption = toAddressOption) { async function loadAddresses(path, query, extra, minLength = 2, toOption = toAddressOption) {
const normalizedQuery = query.trim(); const normalizedQuery = query.trim();
if (normalizedQuery.length < minLength) return []; if (normalizedQuery.length < minLength) return [];
@ -173,10 +191,16 @@ async function loadHouses(query, street) {
} }
const loadRegions = (query, { includeParent, compact } = {}) => const loadRegions = (query, { includeParent, compact } = {}) =>
loadAddresses("regions", query, { loadAddresses(
include_parent: String(Boolean(includeParent)), "regions",
compact: String(Boolean(compact)), query,
}); {
include_parent: String(Boolean(includeParent)),
compact: String(Boolean(compact)),
},
2,
toRegionOption,
);
const loadLocalities = (query, regionId, { includeParent, compact } = {}) => const loadLocalities = (query, regionId, { includeParent, compact } = {}) =>
loadAddresses("localities", query, { loadAddresses("localities", query, {
region_id: String(regionId), region_id: String(regionId),
@ -403,7 +427,7 @@ export default function App() {
const result = region const result = region
? compact ? compact
? { ? {
region: compactAddress(region.address), region: compactRegion(region.address),
locality: compactAddress(locality?.address), locality: compactAddress(locality?.address),
street: compactAddress(street?.address), street: compactAddress(street?.address),
house: house?.house ?? null, house: house?.house ?? null,