Skip to content

Commit

Permalink
chore: adding pagination on villages
Browse files Browse the repository at this point in the history
  • Loading branch information
Yuefii committed Aug 25, 2024
1 parent 5d9e842 commit 40ff40a
Showing 1 changed file with 43 additions and 8 deletions.
51 changes: 43 additions & 8 deletions app/routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,16 +137,51 @@ def get_districts():
],
}

return jsonify({"data": response})
return jsonify(response)


@village_bp.route("/api/villages", methods=["GET"])
def get_villages():
show_all = request.args.get("show_all", "false").lower() == "true"
page = request.args.get("page", 1, type=int)
per_page = request.args.get("per_page", 10, type=int)
district_code = request.args.get("district_code")
if not district_code:
return jsonify({"error": "district code is required"}), 400
villages = Villages.query.filter_by(district_code=district_code).all()
if not villages:
return jsonify({"message": "no villages found for given district code"}), 404
response = [{"code": village.code, "name": village.name} for village in villages]
return jsonify({"data": response})

if show_all:
if district_code:
villages = Villages.query.filter_by(district_code=district_code).all()
else:
villages = Villages.query.all()
response = [
{"code": village.code, "name": village.name} for village in villages
]
else:
if district_code:
total_villages = Villages.query.filter_by(
district_code=district_code
).count()
villages_query = Villages.query.filter_by(
district_code=district_code
).paginate(page=page, per_page=per_page, error_out=False)
else:
total_villages = Villages.query.count()
villages_query = Villages.query.paginate(
page=page, per_page=per_page, error_out=False
)
total_pages = (total_villages + per_page - 1) // per_page
if page > total_pages:
return jsonify({"error": "page number exceeds total pages"}), 400
response = {
"pagination": {
"total_items": villages_query.total,
"total_pages": villages_query.pages,
"current_page": villages_query.page,
"per_page": villages_query.per_page,
},
"data": [
{"code": village.code, "name": village.name}
for village in villages_query.items
],
}

return jsonify(response)

0 comments on commit 40ff40a

Please sign in to comment.