Example #1
0
def index():
    u: User = get_user_from_app_context()

    if "_sort" in request.values:
        srt = request.values["_sort"]
    else:
        srt = "rating"

    sortExpr = SORT_MAP.get(srt)
    if sortExpr is None:
        raise ApiError(f"unknown sort operator \"{srt}\"")

    if get_boolean_request_param("_mine"):
        if u:
            # only mine posts
            query = {"author_id": u._id}
        else:
            # nothing to show, user is not logged in
            query = {"_id": NilObjectId}
    else:
        # otherwise show all not deleted posts
        query = {
            "$or": [
                {
                    "deleted": False
                },
            ]
        }
        if u:
            # if user is logged in, he can view his own deleted posts
            query["$or"].append({"author_id": u._id})

    questions = Question.find(query).sort(sortExpr)
    results = paginated(
        questions, transform=default_transform(fields=QUESTION_LIST_FIELDS))
    author_ids = set()
    for q in results["data"]:
        author_ids.add(resolve_id(q["author_id"]))
    authors = User.find({"_id": {"$in": list(author_ids)}})
    return json_response({"questions": results, "authors": {"data": authors}})