class DomainService(object): collection = Domain._get_collection() def create_domain(self, building, name): domain = { Domain.NAME: name, Domain.BUILDING: building, Domain.NODES: [] } self.collection.insert(domain) def retrieve_domain(self, building, name): return self.collection.find_one( { Domain.NAME: name, Domain.BUILDING: building }, {'_id': 0}) def exists_domain(self, building, name): return self.retrieve_domain(building, name) is not None
class NodeService(object): collection = Domain._get_collection() def retrieve_node(self, building, domain, name, tag): return self.collection.find_one( { Domain.NAME: domain, Domain.BUILDING: building }, { Domain.NODES: { '$elemMatch': { Node.NAME: name, Node.TAG: tag } }, '_id': 0 })[Domain.NODES][0] def list_node(self, building, domain, name): res = self.collection.aggregate([{ '$unwind': '$nodes' }, { '$match': { Domain.BUILDING: building, Domain.NAME: domain, 'nodes.name': name } }, { '$project': { Domain.NODES: 1, '_id': 0 } }])['result'] return [node[Domain.NODES] for node in res] def create_node(self, building, domain, name, tag, parent_name=None, parent_tag=None): node = {Node.NAME: name, Node.TAG: tag, Node.CHILDREN: []} self.collection.update({ Domain.NAME: domain, Domain.BUILDING: building }, {'$addToSet': { Domain.NODES: node }}) if not parent_name: return node.pop(Node.CHILDREN) self.collection.update( { Domain.NAME: domain, Domain.BUILDING: building, Domain.NODES: { '$elemMatch': { Node.NAME: parent_name, Node.TAG: parent_tag } } }, {'$addToSet': { 'nodes.$.children': node }})