Example #1
0
    async def json_children(
        self, fields: list[str] = [], order_by: str = "id", deep: bool = False
    ) -> dict[str, Any]:
        """return all comments child of current comment
        (comments that reply to the current comment)

        Args:

            fields (list[str]): list of fields to return, default []
            order_by (str, optional): ordering return. Defaults to "id".
            deep (bool: optional): get/not also deep children
            (response to child's comment)

        Returns:

            dict[str, Any]: data found
        """
        from app.api.utils import API_functools

        fields = fields if len(fields) > 0 else API_functools.get_attributes(Comment)
        filter_key = {"top_parent_id" if deep else "parent_id": self.id}
        return await API_functools.add_owner_fullname(
            jsonable_encoder(
                await (
                    Comment.filter(**filter_key)
                    .prefetch_related("vote")
                    .annotate(votes=Count("vote", distinct=True))
                    .annotate(nb_children=Count("children", distinct=True))
                    .order_by(order_by)
                    .values(*fields, "votes", "nb_children")
                )
            )
        )
Example #2
0
async def filter_comments(
    req: Request,
    res: Response,
    max_comments: int,
    data: Optional[list[dict]] = None,
    filters: Optional[dict] = None,
    offset: Optional[int] = 20,
    limit: Optional[int] = 0,
    sort: Optional[str] = "id:asc",
):

    response = {
        "success": False,
        "comments": [],
    }
    if data is None:
        order_by = API_functools.valid_order(Comment, sort)
        if order_by is None:
            res.status_code = status.HTTP_400_BAD_REQUEST
            return {
                **response,
                "detail": invalid_sort_detail,
            }

    if offset < 0 or limit < 1:
        res.status_code = status.HTTP_400_BAD_REQUEST
        return {
            **response,
            "detail": "Invalid values: offset(>=0) or limit(>0)",
        }
    if data is None:
        comments = await API_functools.add_owner_fullname(
            jsonable_encoder(await (
                Comment.all() if filters is None else Comment.filter(**filters)
            ).prefetch_related("vote").prefetch_related("children").annotate(
                votes=Count("vote", distinct=True)
            ).annotate(nb_children=Count("children", distinct=True)
                       ).limit(limit).offset(offset).order_by(order_by).values(
                           *API_functools.get_attributes(Comment), "votes",
                           "nb_children")))
    else:
        comments = data

    if len(comments) == 0:
        res.status_code = status.HTTP_404_NOT_FOUND
        return {**response, "detail": "Not Found"}
    return API_functools.manage_next_previous_page(req,
                                                   comments,
                                                   max_comments,
                                                   limit,
                                                   offset,
                                                   data_type="comments")
 def test_comment_attributes(self):
     expected_attrs = (
         "id",
         "added",
         "edited",
         "content",
         "parent_id",
         "user_id",
         "top_parent_id",
     )
     actual_attrs = API_functools.get_attributes(Comment)
     for attr in expected_attrs:
         assert attr in actual_attrs
     assert len(expected_attrs) == len(actual_attrs)
 def test_user_attributes(self):
     expected_attrs = (
         "id",
         "is_admin",
         "first_name",
         "last_name",
         "email",
         "gender",
         "avatar",
         "job",
         "company",
         "date_of_birth",
         "country_of_birth",
     )
     actual_attrs = API_functools.get_attributes(Person)
     for attr in expected_attrs:
         assert attr in actual_attrs
     assert len(expected_attrs) == len(actual_attrs)
Example #5
0
 def test_get_attributes(self):
     # Test get_attribute with kwargs
     user_attributes = (
         "id",
         "is_admin",
         "name",
         "email",
         "gender",
         "avatar",
         "job",
         "company",
         "date_of_birth",
         "country_of_birth",
         "full_name",
     )
     assert (API_functools.get_attributes(
         Person,
         replace={"first_name": "name"},
         add=("full_name", ),
         exclude=("last_name", ),
     ) == user_attributes)
Example #6
0
async def comments_by_ID(
    req: Request,
    res: Response,
    comment_ID: int,
    children: bool = False,
    limit: Optional[int] = 20,
    offset: Optional[int] = 0,
    sort: Optional[str] = "id:asc",
) -> Dict[str, Any]:
    """Get comment by ID

    Args:

        comment_ID (int): comment ID
        children (bool): get current comment children
        limit (int, optional): max number of returned comments.
            Defaults to 100.
        offset (int, optional): first comment to return (use with limit).
            Defaults to 1.
        sort (str, optional): the order of the result.
            attribute:(asc {ascending} or desc {descending}). Defaults to "id:asc".

    Returns:

        Dict[str, Any]: contains comment found
    """
    key, value = ("comment", {}) if not children else ("comments", [])
    response = {"success": True, key: value, "detail": "Successful operation"}

    if not await Comment.exists(pk=comment_ID):
        res.status_code = status.HTTP_404_NOT_FOUND
        response["success"] = False
        response["detail"] = "Not Found"
        return response

    if children:
        order_by = API_functools.valid_order(Comment, sort)

        if order_by is None:
            res.status_code = status.HTTP_400_BAD_REQUEST
            return {
                **response,
                "success": False,
                "detail": invalid_sort_detail,
            }
        comment = await Comment.filter(pk=comment_ID).first()
        comments = await comment.json_children(order_by=order_by)
        response["comments"] = comments
        return await filter_comments(
            req,
            res,
            len(response["comments"]),
            data=response["comments"],
            offset=offset,
            limit=limit,
            sort=sort,
        )

    else:
        response["comment"] = API_functools.get_or_default(
            await API_functools.add_owner_fullname([
                API_functools.get_or_default(
                    jsonable_encoder(await Comment.filter(
                        pk=comment_ID
                    ).prefetch_related("vote").prefetch_related(
                        "children").annotate(
                            votes=Count("vote", distinct=True)
                        ).annotate(nb_children=Count("children", distinct=True)
                                   ).values(
                                       *API_functools.get_attributes(Comment),
                                       "votes",
                                       "nb_children",
                                   )),
                    index=0,
                    default={},
                )
            ]),
            index=0,
            default={},
        )

    return response
Example #7
0
 def test_is_attribute_of(self):
     for attr in API_functools.get_attributes(Person):
         assert API_functools.is_attribute_of(attr, Person) is True
     assert API_functools.is_attribute_of("invalid", Person) is False