Exemplo n.º 1
0
 def post(self):
     post_data = request.get_json()
     response_object = {
         "message": "Invalid payload."
     }
     if not post_data:
         return response_object, 400
     subject = post_data.get("subject")
     description = post_data.get("description")
     keys = ["subject", "description"]
     post_keys = post_data.keys()
     has_invalid_keys = [k not in keys for k in post_keys]
     has_unknown_keys = len(post_keys) != len(keys)
     try:
         if any(has_invalid_keys) or has_unknown_keys:
             raise ValueError
         current_user = get_jwt_identity()
         topic = Topic(
             subject=subject,
             description=description,
             created_by=current_user,
             updated_by=current_user
         )
         topic.insert()
         new_topic = Topic.find(id=topic.id)
         response_object = new_topic.json()
         return response_object, 201
     except ValueError:
         db.session.rollback()
         db.session.flush()
         return response_object, 400
Exemplo n.º 2
0
 def test_topic_message_relationship(self):
     user = User(name="testname",
                 email="*****@*****.**",
                 password="******")
     user.insert()
     topic = Topic(subject="subject",
                   description="description",
                   created_by=user.id.__str__(),
                   updated_by=user.id.__str__())
     topic.insert()
     self.assertIsInstance(topic.messages.all(), list)
Exemplo n.º 3
0
 def test_topic_json(self):
     user = User(name="testname",
                 email="*****@*****.**",
                 password="******")
     user.insert()
     topic = Topic(subject="subject",
                   description="description",
                   created_by=user.id.__str__(),
                   updated_by=user.id.__str__())
     topic.insert()
     self.assertTrue(isinstance(topic.json(), dict))
Exemplo n.º 4
0
 def test_topic_user_relationship(self):
     user = User(name="testname",
                 email="*****@*****.**",
                 password="******")
     user.insert()
     topic = Topic(subject="subject",
                   description="description",
                   created_by=user.id.__str__(),
                   updated_by=user.id.__str__())
     topic.insert()
     self.assertEqual(user.id, topic.created_by)
     self.assertEqual(user.id, topic.updated_by)
Exemplo n.º 5
0
 def insert(self, topic_id: str) -> None:
     """Insert a new message in the database."""
     topic = Topic.find(id=topic_id)
     if topic:
         if not topic.deleted_at:
             topic.messages.append(self)
             db.session.commit()
     else:
         raise TopicNotFound("Topic does not exists.")
Exemplo n.º 6
0
 def test_create_topic(self):
     user = User(name="testname",
                 email="*****@*****.**",
                 password="******")
     user.insert()
     topic = Topic(subject="subject",
                   description="description",
                   created_by=user.id.__str__(),
                   updated_by=user.id.__str__())
     topic.insert()
     self.assertTrue(uuid_pattern_matched(topic.id.__str__()))
     self.assertEqual(topic.subject, 'subject')
     self.assertEqual(topic.description, 'description')
     self.assertTrue(topic.created_by)
     self.assertTrue(uuid_pattern_matched(topic.created_by.__str__()))
     self.assertTrue(topic.updated_by)
     self.assertTrue(uuid_pattern_matched(topic.updated_by.__str__()))
     self.assertTrue(topic.created_at)
     self.assertTrue(iso8601_pattern_matched(topic.created_at))
     self.assertTrue(topic.updated_at)
     self.assertTrue(iso8601_pattern_matched(topic.updated_at))
Exemplo n.º 7
0
 def find_all(cls, topic_id: str, page: int) -> List[Dict]:
     """Find all messages from a given topic."""
     topic = Topic.find(id=uuid.UUID(topic_id))
     if topic:
         if not topic.deleted_at:
             messages = (cls.query.filter_by(topic_id=topic.id.__str__(
             )).order_by(cls.created_at.desc()).paginate(
                 page=page,
                 per_page=current_app.config.get("COMMENTS_PER_PAGE"),
                 error_out=False))
             pagination_data = (messages.has_next, messages.next_num, [
                 message.json() for message in messages.items
             ])
             return pagination_data
     else:
         raise TopicNotFound("Topic does not exists.")
Exemplo n.º 8
0
 def get(self, id):
     response_object = {
         "message": "Invalid ID."
     }
     try:
         topic = Topic.find(id=id)
         if not topic or topic.deleted_at:
             return {
                 "message": "Topic does not exists."
             }, 404
         response_object = {
             "data": topic.json()
         }
         return response_object, 200
     except sqlalchemy.exc.DataError:
         db.session.rollback()
         db.session.flush()
         return response_object, 400
Exemplo n.º 9
0
 def get(self):
     get_data = request.get_json()
     response_object = {
         "message": "Invalid payload."
     }
     if not get_data:
         return response_object, 400
     default_page = current_app.config.get("PAGE_COUNT")
     page = get_data.get("page") or default_page
     try:
         (has_next, next_num, topics) = Topic.find_all(page=page)
         response_object = {
             "data": topics,
             "has_next": has_next,
             "next_num": next_num
         }
         return response_object, 200
     except ValueError:
         db.session.rollback()
         db.session.flush()
         return response_object, 400
Exemplo n.º 10
0
 def delete(self, id):
     response_object = {
         "message": "Invalid payload."
     }
     try:
         topic = Topic.find(id=id)
         if not topic or topic.deleted_at:
             response_object["message"] = "Topic does not exists."
             return response_object, 404
         current_user = get_jwt_identity()
         if str(current_user) != str(topic.created_by):
             response_object["message"] = (
                 "You do not have permission to do that."
             )
             return response_object, 401
         topic.delete()
         return {"success": True}, 202
     except sqlalchemy.exc.DataError:
         db.session.rollback()
         db.session.flush()
         return response_object, 400
Exemplo n.º 11
0
def seed_db():
    """Seeds the database."""
    import string
    import json
    from app.api.rest.users.models import User
    from app.api.rest.topics.models import Topic
    from app.api.rest.messages.models import Message

    user1 = User.find(email="*****@*****.**")
    user2 = User.find(email="*****@*****.**")
    if not user1:
        user1 = User(name="mark", email="*****@*****.**", password="******")
        user1.insert()
        user1.id = user1.id.__str__()
    if not user2:
        user2 = User(name="juan",
                     email="*****@*****.**",
                     password="******")
        user2.insert()
        user2.id = user2.id.__str__()
    seed_data = json.load(open("seed.json"))
    alphabet = list(string.ascii_lowercase)
    alphabet.reverse()
    for i in alphabet:
        topic = Topic(subject=f"{i} This is a sample Subject",
                      description=seed_data.get("lorem"),
                      created_by=user2.id,
                      updated_by=user2.id)
        db.session.add(topic)
    for i in range(1, 31):
        topic.messages.append(
            Message(message=f"Sample Comment {i}",
                    created_by=user2.id,
                    updated_by=user2.id))
    for i in range(1, 31):
        topic.messages.append(
            Message(message=f"Sample Comment {i}",
                    created_by=user1.id,
                    updated_by=user1.id))
    db.session.commit()
Exemplo n.º 12
0
 def patch(self, id):
     post_data = request.get_json()
     response_object = {
         "message": "Invalid payload."
     }
     if not post_data:
         return response_object, 400
     keys = ["subject", "description"]
     post_keys = post_data.keys()
     has_unknown_keys = len(post_keys) != len(keys)
     has_invalid_keys = [k not in keys for k in post_keys]
     subject = post_data.get("subject")
     description = post_data.get("description")
     try:
         if any(has_invalid_keys) or has_unknown_keys:
             raise ValueError
         current_user = get_jwt_identity()
         topic = Topic.find(id=id)
         if not topic:
             return {
                 "message": "Topic does not exists."
             }, 404
         current_user = get_jwt_identity()
         if str(current_user) != str(topic.created_by):
             return {
                 "message": "You do not have permission to do that."
             }, 401
         topic.subject = subject
         topic.description = description
         db.session.commit()
         response_object = topic.json()
         return response_object, 200
     except (ValueError, sqlalchemy.exc.DataError):
         db.session.rollback()
         db.session.flush()
         return response_object, 400