Project

General

Profile

1
import {BehaviorSubject, from, Observable, Subscription, throwError as observableThrowError} from 'rxjs';
2
import {Injectable} from '@angular/core';
3
import {Response} from '@angular/http';
4
import {HttpClient} from '@angular/common/http';
5
import {catchError, map} from "rxjs/operators";
6
import {properties} from "../../../../../environments/environment";
7

    
8
@Injectable({  providedIn: 'root' })
9
export class ContextsService {
10
  private communitiesSubject: BehaviorSubject<any> = new BehaviorSubject(null);
11
  private promise: Promise<any>;
12
  private sub: Subscription = null;
13

    
14
  constructor(private http: HttpClient ) {
15
  }
16

    
17
  ngOnDestroy() {
18
    if(this.sub) {
19
      this.sub.unsubscribe();
20
    }
21
  }
22

    
23
  public getCommunities( apiUrl:string):any {
24
  let  url   = apiUrl + 's/';
25
      return this.http.get(url)
26
                    .pipe(map(res => this.parseCommunities(res, true) ))
27
                    // .do(request => console.info("Get claims: offset = "))
28
                    .pipe(catchError(this.handleError));
29
  }
30
  public getPublicCommunities( apiUrl:string):any {
31
    let  url   = apiUrl + 's/';
32
    return this.http.get(url)
33
      .pipe(map(res => this.parseCommunities(res, false) ));
34
  }
35

    
36
  public initCommunities() {
37
    let url = properties.contextsAPI + 's/';
38
    this.promise = new Promise<any>((resolve => {
39
      this.sub = this.http.get((properties.useLongCache) ? (properties.cacheUrl + encodeURIComponent(url)) : url)
40
        .pipe(map(res => this.parseCommunities(res, true) ))
41
        .subscribe(
42
          (communties) => {
43
            this.communitiesSubject.next(communties);
44
            resolve();
45
          },
46
          error => {
47
            this.communitiesSubject.error(error);
48
            resolve();
49
          });
50
    }));
51

    
52
  }
53

    
54
  async getCommunitiesByStateAsync(getAll: boolean) {
55
    if(!this.promise) {
56
      this.initCommunities();
57
    }
58

    
59
    await this.promise;
60
    if(this.sub){
61
      this.sub.unsubscribe();
62
    }
63
    if(getAll) {
64
      return this.communitiesSubject.getValue();
65
    } else {
66
      return this.communitiesSubject.getValue().filter(community => community.status != 'hidden');
67
    }
68
  }
69

    
70
  getPublicCommunitiesByState(): Observable<any> {
71
    return from(this.getCommunitiesByStateAsync(false));
72
  }
73

    
74
  getCommunitiesByState(): Observable<any> {
75
    return from(this.getCommunitiesByStateAsync(true));
76
  }
77

    
78
  parseCommunities(data, getall){
79
    var communities = [];
80

    
81
    for(var i = 0; i< data.length; i++){
82
      if(data[i].type && (data[i].type == "ri" || data[i].type == "community")){
83
        if(getall || data[i].status!='hidden') {
84
          communities.push(data[i]);
85
        }
86
      }
87
    }
88
    return communities;
89
  }
90
  public getCategories(communityId :string, apiUrl:string):any {
91
    //console.info('ContextsService:  request categories for community  with id '+communityId);
92
    let url= apiUrl  + '/' + communityId ;
93
      return this.http.get(url)
94
                    //.map(request => <any> request.json())
95
                    // .do(request => console.info("Get claims: offset = " ))
96
                    .pipe(catchError(this.handleError));
97
  }
98
  public getConcepts(categoryId :string, keyword: string, parsing:boolean, apiUrl:string):any {
99
    //console.info('ContextsService:  request concept for category  with id '+categoryId + ' and keyword '+ keyword);
100
    let url= apiUrl  + '/category/' + categoryId;
101

    
102

    
103
      return this.http.get(url )
104
                    .pipe(catchError(this.handleError))
105
                    .pipe(map(res => (parsing)?this.parse(res):res));
106
  }
107
  public getSubConcepts(subConceptID :string, keyword: string, parsing:boolean, apiUrl:string):any {
108
    //console.info('ContextsService:  request subscriptions concept for concept with id '+subConceptID + ' and keyword '+ keyword);
109
    let url= apiUrl  + '/category/concept/' + subConceptID;
110
    let key = url+"_parsing="+parsing;
111

    
112

    
113
      return this.http.get(url )
114
                    .pipe(catchError(this.handleError))
115
                    .pipe(map(res => (parsing)?this.parseSubConcepts(res):res));
116
  }
117
  parse (data: any):any {
118
      var array =[]
119
      if(!Array.isArray(data) && data.id && data.label){
120
        var value ={id:"",label:"",hasSubConcept:""};
121
        value.id = data.id;
122
        value.label = data.label;
123
        value.hasSubConcept = data.hasSubConcept;
124
        array.push(value);
125
      }
126
      for(var i = 0; i < data.length; i++){
127
        var value={id:"",label:"",hasSubConcept:""};
128
        value.id = data[i].id;
129
        value.label = data[i].label;
130
        value.hasSubConcept = data[i].hasSubConcept;
131
        array.push(value);
132
      }
133

    
134
      return array;
135

    
136
  }
137
  parseSubConcepts (data: any):any {
138
      var array = []
139
      if(data.length >0 && data[0].concepts){
140
        var concepts = data[0].concepts;
141
        for(var i = 0; i < concepts.length; i++){
142
          var value ={id:"",label:"",hasSubConcept:""};
143
          value.id = concepts[i].id;
144
          value.label = concepts[i].label;
145
          value.hasSubConcept = concepts[i].hasSubConcept;
146
          if(concepts[i].concepts){
147
            var subconcepts = concepts[i].concepts;
148
            for(var x = 0; x < subconcepts.length; x++){
149
              var value ={id:"",label:"",hasSubConcept:""};
150
              value.id = subconcepts[x].id;
151
              value.label = subconcepts[x].label;
152
              value.hasSubConcept = subconcepts[x].hasSubConcept;
153
              array.push(value);
154
            }
155
          }
156
          array.push(value);
157
        }
158
    }
159
      return array;
160

    
161
  }
162

    
163
  private handleError (error: Response) {
164
    // in a real world app, we may send the error to some remote logging infrastructure
165
    // instead of just logging it to the console
166
    console.log(error);
167
    return observableThrowError(error  || 'Server error');
168
  }
169
}
(3-3/9)