Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: random entry #113

Merged
merged 6 commits into from
May 22, 2024
Merged
Show file tree
Hide file tree
Changes from 2 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
22 changes: 22 additions & 0 deletions API.md
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,28 @@ Every matching is case-insensitive.
curl hh3.gbdev.io/api/search?tags=Open Source,RPG&platform=GBC
```

### GET `/random`

Return a random entry.

The following query parameters can be used:

- `type` (exact matching)
- `developer` (exact matching)
- `platform` (exact matching)
- `tags` (exact matching, comma-separated array e.g. `/search?tags=Open Source,RPG`)

More than one query parameter can be specified. They will be concatenated in "AND" statements, i.e. `/random?type=homebrew&platform=GBC` will return every Homebrew developed with GBC features.

Every matching is case-insensitive.

#### Examples

```bash
# Get every RPG released as Open Source with Game Boy Color features:
curl hh3.gbdev.io/api/random?tags=Open Source,RPG&platform=GBC
```

### Pagination

Every result is paginated. These additional query params can be used in any of the previous routes:
Expand Down
1 change: 1 addition & 0 deletions hhub/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
path("all", views.entries_all),
path("stats", views.stats),
path("search", views.search_entries),
path("random", views.random_entries),
]
),
)
Expand Down
99 changes: 99 additions & 0 deletions hhub/views.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import json
import random

from django.core.exceptions import FieldError
from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator
Expand Down Expand Up @@ -78,6 +79,104 @@ def entries_all(request):
return JsonResponse(serializer.data, safe=False)


def random_entries(request):
"""
Returns a random entry matching some condition.

Similar to search
"""
# Parse query params, providing defaults
# Filters
developer = request.GET.get("developer", "")
typetag = request.GET.get("typetag", "")
tags = request.GET.get("tags", "")
platform = request.GET.get("platform", "")

# Pagination
# Request a specific page
page = request.GET.get("page", "")
# Request a specific number of results (>1,<30)
num_elements = request.GET.get("results", 10)

# Order and sort
order_by_param = request.GET.get("order_by", "")
sort_by_param = request.GET.get("sort", "")

# Start by selecting everything
entries = Entry.objects.all()

# Boundaries for elements per page
# if num_elements <= 1:
# num_elements = 1
# elif num_elements >= 30:
# num_elements = 30

# change 3 to how many random items you want
entries = random.sample(list(entries), int(num_elements))

# sort and order
if sort_by_param:
entries = sort_and_order(entries, order_by_param, sort_by_param)

if developer:
entries = entries.filter(developer=developer)

if platform:
entries = entries.filter(platform=platform)

if typetag:
entries = entries.filter(typetag=typetag)

if tags:
# Read the value of tags as an array of tags separated by commas
tags = tags.split(",")
entries = entries.filter(tags__contains=tags)

results = len(entries)

# Prepare paginators and number of results
paginator = Paginator(entries, num_elements)

# Request the desired page of results
try:
entries = paginator.page(page)
except PageNotAnInteger:
entries = paginator.page(1)
page = 1
except EmptyPage:
entries = paginator.page(paginator.num_pages)
page = paginator.num_pages

serializer = EntrySerializer(entries, many=True)

# Read from disks the manifests of the result entries
json_entries = []
for entry in entries:
data = open(f"db-sources/{entry.basepath}/{entry.slug}/game.json").read()
json_data = json.loads(data)
# Enrich the manifest with some values available only in the (postgres) database
json_data["basepath"] = entry.basepath
json_entries.append(json_data)

# Prepare final JSON response
return JsonResponse(
{
# total number of results from the query
"results": results,
# total number of pages
"page_total": paginator.num_pages,
# current request page
"page_current": page,
# number of elements in this page
"page_elements": len(serializer.data),
# array of entries manifests
"entries": json_entries,
},
# Allow non-dict instances to be passed and serialized
safe=False,
)


def search_entries(request):
"""
Returns every entry matching the conditions given in the query
Expand Down
Loading