blob: 640182df6e9d2dda8b121ec2010430d8c3778933 [file] [log] [blame]
Matteo Scandolobe9b13d2016-01-21 11:21:03 -08001(function () {
2 'use strict';
3
4 angular.module('xos.serviceTopology')
5 .service('Services', function($resource){
Matteo Scandolo85aad312016-01-21 14:23:28 -08006 return $resource('/xos/services/:id', {id: '@id'});
7 })
8 .service('Tenant', function($resource){
9 return $resource('/xos/tenants');
10 })
11 .service('ServiceRelation', function($q, _, lodash, Services, Tenant){
12
13 // find all the relation defined for a given root
14 const findLevelRelation = (tenants, rootId) => {
15 return lodash.filter(tenants, service => {
16 return service.subscriber_service === rootId;
17 });
18 };
19
20 // find all the service defined by a given array of relations
21 const findLevelServices = (relations, services) => {
22 const levelServices = [];
23 lodash.forEach(relations, (tenant) => {
24 var service = lodash.find(services, {id: tenant.provider_service});
25 levelServices.push(service);
26 });
27 return levelServices;
28 };
29
30 const buildLevel = (tenants, services, rootService, parentName = null) => {
31
32 const tree = {
33 name: rootService.humanReadableName,
34 parent: parentName,
35 children: []
36 };
37
38 // build an array of unlinked services
39 // these are the services that should still placed in the tree
40 var unlinkedServices = lodash.difference(services, [rootService]);
41
42 // find all relations relative to this rootElement
43 const levelRelation = findLevelRelation(tenants, rootService.id);
44
45 // find all items related to rootElement
46 const levelServices = findLevelServices(levelRelation, services);
47
48 // remove this item from the list (performance
49 unlinkedServices = lodash.difference(unlinkedServices, levelServices);
50
51 lodash.forEach(levelServices, (service) => {
52 tree.children.push(buildLevel(tenants, unlinkedServices, service, rootService.humanReadableName));
53 });
54
55 return tree;
56 };
57
58 const buildServiceTree = (services, tenants) => {
59
60 // find the root service
61 // it is the one attached to subsriber_root
62 // as now we have only one root so this can work
63 const rootServiceId = lodash.find(tenants, {subscriber_root: 1}).provider_service;
64 const rootService = lodash.find(services, {id: rootServiceId});
65
66 const serviceTree = buildLevel(tenants, services, rootService);
67
68 return serviceTree;
69 };
70
71 this.get = () => {
72 var deferred = $q.defer();
73 var services, tenants;
74 Services.query().$promise
75 .then((res) => {
76 services = res;
77 return Tenant.query().$promise;
78 })
79 .then((res) => {
80 tenants = res;
81 deferred.resolve(buildServiceTree(services, tenants));
82 })
83 .catch((e) => {
84 throw new Error(e);
85 });
86
87 return deferred.promise;
88 }
Matteo Scandolobe9b13d2016-01-21 11:21:03 -080089 });
90
91}());