implement all works of author
This commit is contained in:
@@ -28,8 +28,59 @@ async def get_author_works(
|
||||
client: OpenAlexWorksSearchClient | None = None,
|
||||
) -> model.WorkPage:
|
||||
search_client = client or OpenAlexWorksSearchClient()
|
||||
data = await _search_author_works_data(
|
||||
search_client,
|
||||
author_id,
|
||||
page,
|
||||
size,
|
||||
publication_year=publication_year,
|
||||
work_type=work_type,
|
||||
language=language,
|
||||
)
|
||||
|
||||
elements, total = _parse_work_search_response(data)
|
||||
return model.WorkPage(elements=elements, page=page, size=size, total=total)
|
||||
|
||||
|
||||
async def get_all_author_works(
|
||||
author_id: str,
|
||||
client: OpenAlexWorksSearchClient | None = None,
|
||||
) -> model.WorkList:
|
||||
search_client = client or OpenAlexWorksSearchClient()
|
||||
page = 1
|
||||
size = 100
|
||||
all_elements: list[model.Work] = []
|
||||
total = 0
|
||||
|
||||
while True:
|
||||
data = await _search_author_works_data(
|
||||
search_client,
|
||||
author_id,
|
||||
page,
|
||||
size,
|
||||
)
|
||||
elements, total = _parse_full_work_search_response(data)
|
||||
all_elements.extend(elements)
|
||||
|
||||
if not elements or len(all_elements) >= total:
|
||||
break
|
||||
|
||||
page += 1
|
||||
|
||||
return model.WorkList(elements=all_elements, total=total)
|
||||
|
||||
|
||||
async def _search_author_works_data(
|
||||
search_client: OpenAlexWorksSearchClient,
|
||||
author_id: str,
|
||||
page: int,
|
||||
size: int,
|
||||
publication_year: list[int] | None = None,
|
||||
work_type: list[str] | None = None,
|
||||
language: list[str] | None = None,
|
||||
) -> dict:
|
||||
try:
|
||||
data = await search_client.search_author_works(
|
||||
return await search_client.search_author_works(
|
||||
author_id,
|
||||
page,
|
||||
size,
|
||||
@@ -50,6 +101,8 @@ async def get_author_works(
|
||||
detail="OpenAlex works search request failed.",
|
||||
) from exc
|
||||
|
||||
|
||||
def _parse_work_search_response(data: dict) -> tuple[list[model.WorkSummary], int]:
|
||||
hits = data.get("hits", {})
|
||||
total = hits.get("total", 0)
|
||||
if isinstance(total, dict):
|
||||
@@ -67,7 +120,28 @@ async def get_author_works(
|
||||
detail="OpenAlex works search response could not be parsed.",
|
||||
) from exc
|
||||
|
||||
return model.WorkPage(elements=elements, page=page, size=size, total=total)
|
||||
return elements, total
|
||||
|
||||
|
||||
def _parse_full_work_search_response(data: dict) -> tuple[list[model.Work], int]:
|
||||
hits = data.get("hits", {})
|
||||
total = hits.get("total", 0)
|
||||
if isinstance(total, dict):
|
||||
total = total.get("value", 0)
|
||||
|
||||
try:
|
||||
elements = [
|
||||
model.Work.model_validate(hit.get("_source", {}))
|
||||
for hit in hits.get("hits", [])
|
||||
]
|
||||
except ValidationError as exc:
|
||||
logger.exception("OpenAlex works search response could not be parsed.")
|
||||
raise HTTPException(
|
||||
status_code=HTTP_502_BAD_GATEWAY,
|
||||
detail="OpenAlex works search response could not be parsed.",
|
||||
) from exc
|
||||
|
||||
return elements, total
|
||||
|
||||
|
||||
def _to_work_summary(source: dict) -> dict:
|
||||
|
||||
@@ -211,3 +211,8 @@ class WorkPage(BaseModel):
|
||||
page: int = Field(default=1, description="The current page number.")
|
||||
size: int = Field(default=20, description="The requested page size.")
|
||||
total: int = Field(default=0, description="The total number of works.")
|
||||
|
||||
|
||||
class WorkList(BaseModel):
|
||||
elements: List[Work] = Field(default_factory=list, description="All works.")
|
||||
total: int = Field(default=0, description="The total number of works.")
|
||||
|
||||
@@ -39,3 +39,14 @@ async def get_author_works(
|
||||
work_type=work_type,
|
||||
language=language,
|
||||
)
|
||||
|
||||
|
||||
@router.get("/{author_id}/works/all",
|
||||
operation_id="getAllAuthorWorks",
|
||||
response_model=model.WorkList,
|
||||
summary="Returns all works for an author.")
|
||||
async def get_all_author_works(
|
||||
author_id: Annotated[str, Path(description="The author id, for example A5023888391.")],
|
||||
principal: security.Principal = Depends(security.roles_allowed(["SUPER_ADMIN", "UNI_ADMIN"])),
|
||||
):
|
||||
return await logic.get_all_author_works(author_id)
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import json
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from fastapi import HTTPException
|
||||
@@ -76,6 +78,73 @@ async def test_get_author_works_maps_elasticsearch_response_to_work_page():
|
||||
assert page.elements[0].topics == ["Machine learning"]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_get_all_author_works_collects_all_pages():
|
||||
requested_pages = []
|
||||
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
payload = json_from_request(request)
|
||||
requested_pages.append(payload["from"] // payload["size"] + 1)
|
||||
page = requested_pages[-1]
|
||||
hits = [
|
||||
{
|
||||
"_source": {
|
||||
"id": f"https://openalex.org/W{page}",
|
||||
"doi": f"https://doi.org/10.1234/example-{page}",
|
||||
"title": f"Example work {page}",
|
||||
"display_name": f"Example work {page}",
|
||||
"type": "article",
|
||||
"language": "en",
|
||||
"publication_year": 2024,
|
||||
"publication_date": "2024-01-01",
|
||||
"cited_by_count": page,
|
||||
"primary_location": {
|
||||
"is_oa": True,
|
||||
"source": {
|
||||
"id": "https://openalex.org/S123",
|
||||
"display_name": "Example Source",
|
||||
},
|
||||
},
|
||||
"authorships": [
|
||||
{
|
||||
"author": {
|
||||
"id": "https://openalex.org/A5023888391",
|
||||
"display_name": "Example Author",
|
||||
},
|
||||
},
|
||||
],
|
||||
"topics": [],
|
||||
}
|
||||
}
|
||||
]
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={
|
||||
"hits": {
|
||||
"total": {"value": 2},
|
||||
"hits": hits,
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
client = OpenAlexWorksSearchClient(
|
||||
base_url="https://project.nes.uni-due.de/elastic",
|
||||
api_key="test-key",
|
||||
transport=httpx.MockTransport(handler),
|
||||
)
|
||||
|
||||
works = await logic.get_all_author_works("A5023888391", client=client)
|
||||
|
||||
assert requested_pages == [1, 2]
|
||||
assert works.total == 2
|
||||
assert [work.title for work in works.elements] == ["Example work 1", "Example work 2"]
|
||||
assert works.elements[0].id == "https://openalex.org/W1"
|
||||
assert works.elements[0].display_name == "Example work 1"
|
||||
assert works.elements[0].publication_date == "2024-01-01"
|
||||
assert works.elements[0].primary_location.is_oa is True
|
||||
assert works.elements[0].authorships[0].author.id == "https://openalex.org/A5023888391"
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_get_author_works_maps_missing_api_key_to_service_unavailable():
|
||||
client = OpenAlexWorksSearchClient(api_key="")
|
||||
@@ -101,3 +170,7 @@ async def test_get_author_works_maps_elasticsearch_errors_to_bad_gateway():
|
||||
await logic.get_author_works("A5023888391", page=1, size=20, client=client)
|
||||
|
||||
assert exc.value.status_code == 502
|
||||
|
||||
|
||||
def json_from_request(request: httpx.Request) -> dict:
|
||||
return json.loads(request.content.decode("utf-8"))
|
||||
|
||||
@@ -64,3 +64,45 @@ def test_get_author_works_returns_page(monkeypatch):
|
||||
"cited_by_count": 42,
|
||||
"topics": ["Machine learning"],
|
||||
}
|
||||
|
||||
|
||||
def test_get_all_author_works_returns_list(monkeypatch):
|
||||
config.settings.auth_disabled = True
|
||||
|
||||
async def fake_get_all_author_works(
|
||||
author_id: str,
|
||||
):
|
||||
assert author_id == "A5023888391"
|
||||
return model.WorkList(
|
||||
elements=[
|
||||
model.Work(
|
||||
id="https://openalex.org/W2741809807",
|
||||
doi="https://doi.org/10.7717/peerj.4375",
|
||||
title="Example work",
|
||||
display_name="Example work",
|
||||
type="article",
|
||||
language="en",
|
||||
publication_year=2023,
|
||||
cited_by_count=42,
|
||||
topics=[
|
||||
model.Topic(
|
||||
id="https://openalex.org/T10102",
|
||||
display_name="Machine learning",
|
||||
)
|
||||
],
|
||||
)
|
||||
],
|
||||
total=1,
|
||||
)
|
||||
|
||||
monkeypatch.setattr(logic, "get_all_author_works", fake_get_all_author_works)
|
||||
|
||||
response = client.get("/inse-service/authors/A5023888391/works/all")
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.json()
|
||||
assert data["total"] == 1
|
||||
assert data["elements"][0]["id"] == "https://openalex.org/W2741809807"
|
||||
assert data["elements"][0]["title"] == "Example work"
|
||||
assert data["elements"][0]["display_name"] == "Example work"
|
||||
assert data["elements"][0]["topics"][0]["display_name"] == "Machine learning"
|
||||
|
||||
Reference in New Issue
Block a user