from flask import current_app from bson.objectid import ObjectId 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.uobjects.find({})) def register(self, datas): db = MongoDB(self.app) mongo = db.connection() error = {} if type(datas) != dict: error = { "msg": "UObject datas type is not dict (JSON).", "code": 400 } if not error: _id = mongo.db.uobjects.insert({"datas": datas}) return {"_id": str(_id), "msg": "UObject added.", "code": 201} return error def remove(self, _id): db = MongoDB(self.app) mongo = db.connection() error = {} if not _id: error = {"msg": "UObject _id is required", "code": 400} elif len(list(mongo.db.uobjects.find({"_id": ObjectId(_id)}))) == 0: error = { "msg": "UObject {} not exist. So it's good.".format(_id), "code": 404 } if not error: mongo.db.uobjects.remove({"_id": ObjectId(_id)}) return {"msg": "UObject {} deleted".format(_id), "code": 200} return error def update(self, _id, datas): db = MongoDB(self.app) mongo = db.connection() error = {} if not _id: error = {"msg": "UObject _id is required", "code": 400} elif len(list(mongo.db.uobjects.find({"_id": ObjectId(_id)}))) == 0: error = { "msg": "UObject {} does not exist.".format(_id), "code": 404 } datas = dict( ("datas.{}".format(key), value) for (key, value) in datas.items() ) if not error: mongo.db.uobjects.update_one( {"_id": ObjectId(_id)}, {"$set": datas} ) return {"msg": "UObject updated.", "code": 200} return error def eq(self, key, value): db = MongoDB(self.app) mongo = db.connection() datas = list(mongo.db.uobjects.find( {"datas.{}".format(key): {"$eq": value}} )) if datas: return { "msg": "UObjects found", "datas": datas, "code": 200 } else: return { "msg": "UObjects not found", "datas": datas, "code": 404 } def reset(self): db = MongoDB(self.app) mongo = db.connection() mongo.db.uobjects.remove() return "done"