def query_post(self, where, select, limit, skip, sort_field, sort_by):
        if not select:
            document_cursor = self.db.posts.find(where)
        else:
            values = select.values()
            unique_values = set(values)

            if len(unique_values) != 1:
                raise DilaError(
                    err_msg=
                    'Projection cannot have a mix of inclusion and exclusion.',
                    err_code='errors.badRequest',
                    status_code=400)
            document_cursor = self.db.posts.find(where, select)

        document_cursor.limit(limit)
        document_cursor.skip(skip)

        if sort_field:
            if sort_by == "asc":
                sort_by = pymongo.ASCENDING
            elif sort_by == "desc":
                sort_by = pymongo.DESCENDING
            else:
                raise DilaError(
                    err_msg='Please provide valid sort_by field: asc, desc.',
                    err_code='errors.badRequest',
                    status_code=400)
            document_cursor.sort([(sort_field, sort_by)])

        documents = list(document_cursor)

        return documents
    def update_post(self, post_id, raise_exception=False):
        body = request.json
        document = self.db.posts.find_one({'_id': ObjectId(post_id)})
        if raise_exception and not document:
            raise DilaError(
                err_msg=
                "Document not found by given id: <{}>, in collection: <{}>".
                format(post_id, "posts"),
                err_code="errors.resourceNotFound",
                status_code=404)
        document.pop("_id")
        current_sys = document.pop("sys")

        old_document = copy.deepcopy(document)
        document.update(body)

        if old_document == document:
            raise DilaError(
                err_msg="Document already same as the exist document",
                err_code="identicalDocumentError",
                status_code=409)
        current_sys["modified_at"] = datetime.utcnow()
        current_sys["modified_by"] = "system"

        document["sys"] = current_sys

        self.db.posts.update_one({'_id': ObjectId(post_id)},
                                 {"$set": document})
        document["_id"] = post_id

        return document
 def get_post(self, post_id, raise_exception=False):
     document = self.db.posts.find_one({"_id": ObjectId(post_id)})
     if raise_exception and not document:
         raise DilaError(
             err_msg=
             "Document not found by given id: <{}>, in collection: <{}>".
             format(post_id, "posts"),
             err_code="errors.resourceNotFound",
             status_code=404)
     return document
 def validate_by_schema(*args, **kwargs):
     try:
         body = request.json
         validate(body, schema)
     except ValidationError as e:
         raise DilaError(err_msg=e.message,
                         err_code="errors.validationError",
                         status_code=400)
     response = f(*args, **kwargs)
     return response
 def delete_post(document_id):
     """burada sadece gelen document_id li bir document var mı kontrolü yapılır,"""
     """validasyon işlemleri burada, database e erişme ve silme işlemleri post_service in içindeki delete_post ta gerçekleştirilir."""
     try:
         doc_id_as_obj_id = ObjectId(document_id)
     except InvalidId as ex:
         raise DilaError(
             err_msg=
             'Provided id is not valid ObjectId, please provide valid ObjectId',
             err_code='errors.badRequest',
             status_code=400)
     app.post_service.delete_post(doc_id_as_obj_id, raise_exception=True)
     return Response(json.dumps({}), status=204)
    def update_post(document_id):
        try:
            doc_id_as_obj_id = ObjectId(document_id)
        except InvalidId as ex:
            raise DilaError(
                err_msg=
                'Provided id is not valid ObjectId, please provide valid ObjectId',
                err_code='errors.badRequest',
                status_code=400)

        body = app.post_service.update_post(doc_id_as_obj_id,
                                            raise_exception=True)
        return Response(json.dumps(body, default=bson_to_json),
                        mimetype='application/json',
                        status=200)
    def query_post():
        """
        postları sorgulamak/filtrelemek için kullanılır
        kullanıcıdan where select limit skip sort parametreleri istenir
        bütün parametreler valide edilir

            request.args.get(parameter, 0))  #default değeri null değil de 0 olsun diye 0 set ettik
            select = body.get("select", {})  # selecti bulamazsa body de boş obje dön

        :return: envelop => data: {items: [], count: 0}
        """
        body = request.json
        raw_parameters = ["limit", "skip"]
        parameters = {}
        for parameter in raw_parameters:
            try:
                parameters[parameter] = int(request.args.get(parameter, 0))
            except ValueError:
                raise DilaError(
                    err_msg="{} parameter must be an integer. Provided value: {}"
                    .format(parameter, request.args.get(parameter)),
                    err_code='errors.badRequest',
                    status_code=400)

        limit = parameters.get("limit")
        skip = parameters.get("skip")

        sort_field = request.args.get("sort_field")
        sort_by = request.args.get("sort_by", "desc")

        if not limit and limit > 200:
            limit = 200
        where = body.get("where", {})
        select = body.get("select", {})

        documents = app.post_service.query_post(where, select, limit, skip,
                                                sort_field, sort_by)

        envelop = {"data": {"items": documents, "count": len(documents)}}

        return Response(json.dumps(envelop, default=bson_to_json),
                        mimetype='application/json',
                        status=200)
    def create_post(self, raise_exception=False):
        body = request.json
        title = body["title"]

        document = self.db.posts.find_one({
            "title": title,
            "is_active": True,
            "status": "active"
        })

        if raise_exception and document:
            raise DilaError(
                err_msg='Resource already exist in db with title: <{}>'.format(
                    title),
                err_code='errors.duplicateRecord',
                status_code=409)

        body['sys'] = {'created_at': datetime.utcnow(), 'created_by': 'system'}
        _ = self.db.posts.insert_one(body)

        return body