summaryrefslogtreecommitdiff
path: root/inventory/schema.py
blob: 4837d583491826a560311194e950f97d48d7df9e (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
import bson
from flask import url_for
from marshmallow import Schema, fields

# Map ObjectId to String
Schema.TYPE_MAPPING[bson.ObjectId] = fields.String


class ObjectId(fields.Field):
    def _serialize(self, value, attr, obj, **kwargs):
        if value is None:
            return value
        return str(value)

    def _deserialize(self, value, attr, data, **kwargs):
        if value is None:
            return value
        return bson.ObjectId(value)


class FieldSchema(Schema):
    name = fields.String(required=True)
    value = fields.String(required=True)
    # type


class NodeSchema(Schema):
    _id = ObjectId(dump_only=True, data_key='id')
    name = fields.String(required=True)
    parent_id = ObjectId(default=None)
    _fields = fields.List(fields.Nested(FieldSchema()), default=[], attribute='fields', data_key='fields')

    # These are not set by the caller, but by the API endpoint
    created_at = fields.AwareDateTime(dump_only=True)
    updated_at = fields.AwareDateTime(dump_only=True)

    # Not actual stored fields
    parent = fields.Nested(lambda: NodeSchema(), dump_only=True)
    children = fields.List(fields.Nested(lambda: NodeSchema()), dump_only=True)
    url = fields.Function(lambda obj: url_for('.node', node_id=obj['_id']), dump_only=True)