Project

General

Profile

1 61381 k.triantaf
import {BehaviorSubject, from, Observable, Subscription, throwError as observableThrowError} from 'rxjs';
2
import {Injectable} from '@angular/core';
3
import {HttpClient} from '@angular/common/http';
4
import {catchError, map} from "rxjs/operators";
5
import {properties} from "../../../../../environments/environment";
6
7
@Injectable({  providedIn: 'root' })
8
export class ContextsService {
9
  private communitiesSubject: BehaviorSubject<any> = new BehaviorSubject(null);
10
  private promise: Promise<any>;
11
  private sub: Subscription = null;
12
13
  constructor(private http: HttpClient=null ) {
14
  }
15
16
  ngOnDestroy() {
17
    if(this.sub) {
18
      this.sub.unsubscribe();
19
    }
20
  }
21
22
  public getCommunities( apiUrl:string):any {
23
  let  url   = apiUrl + 's/';
24
      return this.http.get(url)
25
                    .pipe(map(res => this.parseCommunities(res, true) ))
26
                    // .do(request => console.info("Get claims: offset = "))
27
                    .pipe(catchError(this.handleError));
28
  }
29
  public getPublicCommunities( apiUrl:string):any {
30
    let  url   = apiUrl + 's/';
31
    return this.http.get(url)
32
      .pipe(map(res => this.parseCommunities(res, false) ));
33
  }
34
35
  public initCommunities() {
36
    let url = properties.contextsAPI + 's/';
37
    this.promise = new Promise<any>((resolve => {
38
      this.sub = this.http.get((properties.useLongCache) ? (properties.cacheUrl + encodeURIComponent(url)) : url)
39
        .pipe(map(res => this.parseCommunities(res, true) ))
40
        .subscribe(
41
          (communties) => {
42
            this.communitiesSubject.next(communties);
43
            resolve();
44
          },
45
          error => {
46
            this.communitiesSubject.error(error);
47
            resolve();
48
          });
49
    }));
50
51
  }
52
53
  async getCommunitiesByStateAsync(getAll: boolean) {
54
    if(!this.promise) {
55
      this.initCommunities();
56
    }
57
58
    await this.promise;
59
    if(this.sub){
60
      this.sub.unsubscribe();
61
    }
62
    if(getAll) {
63
      return this.communitiesSubject.getValue();
64
    } else {
65
      return this.communitiesSubject.getValue().filter(community => community.status != 'hidden');
66
    }
67
  }
68
69
  getPublicCommunitiesByState(): Observable<any> {
70
    return from(this.getCommunitiesByStateAsync(false));
71
  }
72
73
  getCommunitiesByState(): Observable<any> {
74
    return from(this.getCommunitiesByStateAsync(true));
75
  }
76
77
  parseCommunities(data, getall){
78
    var communities = [];
79
80
    for(var i = 0; i< data.length; i++){
81
      if(data[i].type && (data[i].type == "ri" || data[i].type == "community")){
82
        if(getall || data[i].status!='hidden') {
83
          communities.push(data[i]);
84
        }
85
      }
86
    }
87
    return communities;
88
  }
89
  public getCategories(communityId :string, apiUrl:string):any {
90
    //console.info('ContextsService:  request categories for community  with id '+communityId);
91
    let url= apiUrl  + '/' + communityId ;
92
      return this.http.get(url)
93
                    //.map(request => <any> request.json())
94
                    // .do(request => console.info("Get claims: offset = " ))
95
                    .pipe(catchError(this.handleError));
96
  }
97
  public getConcepts(categoryId :string, keyword: string, parsing:boolean, apiUrl:string):any {
98
    //console.info('ContextsService:  request concept for category  with id '+categoryId + ' and keyword '+ keyword);
99
    let url= apiUrl  + '/category/' + categoryId;
100
101
102
      return this.http.get(url )
103
                    .pipe(catchError(this.handleError))
104
                    .pipe(map(res => (parsing)?this.parse(res):res));
105
  }
106
  public getSubConcepts(subConceptID :string, keyword: string, parsing:boolean, apiUrl:string):any {
107
    //console.info('ContextsService:  request subscriptions concept for concept with id '+subConceptID + ' and keyword '+ keyword);
108
    let url= apiUrl  + '/category/concept/' + subConceptID;
109
    let key = url+"_parsing="+parsing;
110
111
112
      return this.http.get(url )
113
                    .pipe(catchError(this.handleError))
114
                    .pipe(map(res => (parsing)?this.parseSubConcepts(res):res));
115
  }
116
  parse (data: any):any {
117
      var array =[]
118
      if(!Array.isArray(data) && data.id && data.label){
119
        var value ={id:"",label:"",hasSubConcept:""};
120
        value.id = data.id;
121
        value.label = data.label;
122
        value.hasSubConcept = data.hasSubConcept;
123
        array.push(value);
124
      }
125
      for(var i = 0; i < data.length; i++){
126
        var value={id:"",label:"",hasSubConcept:""};
127
        value.id = data[i].id;
128
        value.label = data[i].label;
129
        value.hasSubConcept = data[i].hasSubConcept;
130
        array.push(value);
131
      }
132
133
      return array;
134
135
  }
136
  parseSubConcepts (data: any):any {
137
      var array = []
138
      if(data.length >0 && data[0].concepts){
139
        var concepts = data[0].concepts;
140
        for(var i = 0; i < concepts.length; i++){
141
          var value ={id:"",label:"",hasSubConcept:""};
142
          value.id = concepts[i].id;
143
          value.label = concepts[i].label;
144
          value.hasSubConcept = concepts[i].hasSubConcept;
145
          if(concepts[i].concepts){
146
            var subconcepts = concepts[i].concepts;
147
            for(var x = 0; x < subconcepts.length; x++){
148
              var value ={id:"",label:"",hasSubConcept:""};
149
              value.id = subconcepts[x].id;
150
              value.label = subconcepts[x].label;
151
              value.hasSubConcept = subconcepts[x].hasSubConcept;
152
              array.push(value);
153
            }
154
          }
155
          array.push(value);
156
        }
157
    }
158
      return array;
159
160
  }
161
162
  private handleError (error: any) {
163
    // in a real world app, we may send the error to some remote logging infrastructure
164
    // instead of just logging it to the console
165
    console.log(error);
166
    return observableThrowError(error  || 'Server error');
167
  }
168
}