aboutsummaryrefslogtreecommitdiff
path: root/umosapi/app_db/uobject.py
blob: 0ba328c3c8a403fc2d528791040035147de18f14 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
from flask import current_app

from .db import MongoDB


class UObject(object):
    def __init__(self, app=None):
        self.app = app

    def all(self):
        db = MongoDB(self.app)
        mongo = db.connection()
        return list(mongo.db.objects.find({}))

    def register(self, name, datas):
        db = MongoDB(self.app)
        mongo = db.connection()
        error = {}

        if not name:
            error = {"msg": "Object name is required.", "code": 400}
        elif type(datas) != dict:
            error = {
                "msg": "Object datas type is not dict (JSON).",
                "code": 400
            }
        elif len(list(mongo.db.objects.find({"name": name}))) > 0:
            error = {
                "msg": "Object {} is already registered.".format(name),
                "code": 409
            }
        if not error:
            mongo.db.objects.insert({"name": name, "datas": datas})
            return {"msg": "Object {} added.".format(name), "code": 201}
        return error

    def remove(self, name):
        db = MongoDB(self.app)
        mongo = db.connection()
        error = {}

        if not name:
            error = {"msg": "Object name is required", "code": 400}
        elif len(list(mongo.db.objects.find({"name": name}))) == 0:
            error = {
                'msg': "User {} not exist. So it's good".format(name),
                "code": 404
            }

        if not error:
            mongo.db.objects.remove({"name": name})
            return {"msg": "Object {} deleted".format(name), "code": 200}
        return error