From da38889aa75a7d1ed44f9bfca0c2df8dcb12bb3b Mon Sep 17 00:00:00 2001 From: Andrew Godwin Date: Wed, 21 Dec 2022 21:54:49 +0000 Subject: [PATCH] Add account search endpoint --- api/views/accounts.py | 24 ++++++++++++++++++++++++ tests/api/test_accounts.py | 11 +++++++++++ 2 files changed, 35 insertions(+) diff --git a/api/views/accounts.py b/api/views/accounts.py index e505df7..c37db8b 100644 --- a/api/views/accounts.py +++ b/api/views/accounts.py @@ -1,6 +1,8 @@ from django.shortcuts import get_object_or_404 +from ninja import Field from activities.models import Post, PostInteraction +from activities.services import SearchService from api import schemas from api.decorators import identity_required from api.pagination import MastodonPaginator @@ -55,6 +57,28 @@ def familiar_followers(request): return result +@api_router.get("/v1/accounts/search", response=list[schemas.Account]) +@identity_required +def search( + request, + q: str, + fetch_identities: bool = Field(False, alias="resolve"), + following: bool = False, + limit: int = 20, + offset: int = 0, +): + """ + Handles searching for accounts by username or handle + """ + if limit > 40: + limit = 40 + if offset: + return [] + searcher = SearchService(q, request.identity) + search_result = searcher.search_identities_handle() + return [i.to_mastodon_json() for i in search_result] + + @api_router.get("/v1/accounts/{id}", response=schemas.Account) @identity_required def account(request, id: str): diff --git a/tests/api/test_accounts.py b/tests/api/test_accounts.py index 6ca37ae..fe4bfb7 100644 --- a/tests/api/test_accounts.py +++ b/tests/api/test_accounts.py @@ -10,3 +10,14 @@ def test_verify_credentials(api_token, identity, client): ).json() assert response["id"] == str(identity.pk) assert response["username"] == identity.username + + +@pytest.mark.django_db +def test_account_search(api_token, identity, client): + response = client.get( + "/api/v1/accounts/search?q=test", + HTTP_AUTHORIZATION=f"Bearer {api_token.token}", + HTTP_ACCEPT="application/json", + ).json() + assert response[0]["id"] == str(identity.pk) + assert response[0]["username"] == identity.username