viplist.service.ts 2.56 KB
import {Injectable} from '@angular/core';
import {Vip, VipFragmentsCombined} from './models/vip.model';
import {User} from '../../shared/models/user.model';
import {UserService} from '../../shared/services/user.service';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/switchMap';
import 'rxjs/add/observable/forkJoin';
import 'rxjs/add/operator/first';
import {HttpClient} from '@angular/common/http';
import {MOYA_REST_URL} from "../../shared/config/moya.config";
import gql from 'graphql-tag';
import {EventUser} from "../../shared/models/event-user.model";
import {Apollo} from "apollo-angular";
import "rxjs-compat/add/operator/map";


export const Q_VIPS_N_DATA = gql`
    query Vips() {
      vips {
        ...vipPrimitives
        products {
           ...vipProductPrimitives
           deliveries {
           ...vipProductDeliveryPrimitives
           }
        }
        creator {
           ...eventUserPrimitives
           user {
              ...userPrimitives
           }
        }
      }
    }
    
    ${VipFragmentsCombined}
    ${EventUser.fragments}
    ${User.fragments}
    
  
  `;



@Injectable()
export class ViplistService {



  constructor(private apollo: Apollo, private http: HttpClient, private userService: UserService) {

  }


  /**
   * get vips
   * @param searchString: searchString, skip to return all vips
   */
  public get(): Observable<Array<Vip>> {



    return this.apollo.watchQuery<Array<Vip>>({query: Q_VIPS_N_DATA}).valueChanges.map(x => x.data);
    //Vip .map(x => x as Vip);



    if (!searchString) {
      return this.http.get(MOYA_REST_URL + 'v3/vip/all')
        .switchMap(res => Observable.forkJoin(...(res as Array<any>).map(apiRow => this.hostPopulator(apiRow))));
    }
  }


  /**
   * Delete vip.
   *
   * @param vip
   * @return Promise
   */
  public async delete(vip: Vip): Promise<boolean> {

    if (!vip.id) {
      throw new Error('TODO: errori, tyhmä vippi');
    }

    const res: any = await this.http.delete(MOYA_REST_URL + 'v3/vip/' + vip.id)
      .first()
      .toPromise();

    return res.ok;
  }


  public getWithId(id: number): Observable<Vip> {
    return this.http.get(MOYA_REST_URL + 'v3/vip/' + id).map(x => x as Vip);

  }


  public create(vip: Vip): Observable<Vip> {
    return this.http.post(MOYA_REST_URL + 'v3/vip/create', vip).map(x => x as Vip);

  }

  private hostPopulator(rawVip: any): Observable<Vip> {
    return this.userService.get(rawVip.hostId)
      .map((u: User) => {rawVip.host = u; return <Vip> rawVip; }).map(x => x as Vip);
  }


}