aboutsummaryrefslogtreecommitdiff
path: root/umosapi/api.py
blob: 57ae00a79a3111d12b6aaf9e5ba315f36c2838f0 (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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
from flask import Flask, Blueprint, jsonify, request
from flask_restplus import Resource, Api, fields

from json import loads

from .utils import sanitize
from .app_db.uobject import UObject

app = Flask(__name__, instance_relative_config=True)

bp = Blueprint('api', __name__, url_prefix='/api')

env = app.config['DEBUG']

if env is not False:
    env = '/doc'

api = Api(
        bp,
        doc=env,
        title="UMoSApi",
        description="""
        Unity Mongo Save Api is a simple API for save Unity
        object in Mongo database. The terme uobject means Unity Object.
        """,
        version=0.1
    )

uobject = UObject(app)


class fieldsDict(fields.Raw):
    __schema_type__ = ["Dict"]
    __schema_example__ = {"key": "token"}


user_model = api.model('UObject', {
    'datas': fieldsDict(
        required=False,
        description='Datas of the uobject in JSON format',
        example={"key": "token"}
    )
})


@api.route('/objects', endpoint='objetcs')
class Objects(Resource):
    def get(self):
        """ Get uobjects list """
        uobjects = uobject.all()
        if not uobjects:
            return loads('{"msg": "No uobjects"}'), 404
        return sanitize(uobjects), 200


@api.route("/objects/register")
class Register(Resource):
    @api.expect(user_model)
    def post(self):
        """ Register new uobject """
        args = request.get_json(force=True)
        status = uobject.register(args.get('datas'))

        if '_id' in status:
            return {"_id": status['_id'], "msg": status['msg']}, status['code']
        else:
            return {"msg": status['msg']}, status['code']


@api.route("/objects/<_id>")
class Update(Resource):
    @api.expect(user_model)
    def patch(self, _id):
        """ Edit an uobject. """
        args = request.get_json(force=True)
        status = uobject.update(_id, args.get('datas'))

        return {"msg": status['msg']}, status['code']


@api.route('/objects/<_id>')
@api.doc(params={'_id': '5d244cc13f3d46cb739912ae'})
class Remove(Resource):
    def delete(self, _id):
        """ Remove an uobject """
        status = uobject.remove(_id)

        return {"msg": status['msg']}, status['code']