Commit 7d53d60e by Tuukka Kivilahti

bug fixes

1 parent 4936c494
Showing with 13 additions and 987 deletions
/**
* Created by tuukka on 15/02/17.
*/
"use strict";
// vim magic: %s/^\s*\w\+\s\+\(\w\+\)\s\+\(\w\+\)\s*.*;$/ \2: \L\1;/
(function (UserGender) {
UserGender[UserGender["MALE"] = 0] = "MALE";
UserGender[UserGender["FEMALE"] = 1] = "FEMALE";
UserGender[UserGender["UNSPECIFIED"] = 2] = "UNSPECIFIED";
})(exports.UserGender || (exports.UserGender = {}));
var UserGender = exports.UserGender;
var User = (function () {
function User() {
}
return User;
}());
exports.User = User;
/**
* Created by tuukka on 15/02/17.
*/
// vim magic: %s/^\s*\w\+\s\+\(\w\+\)\s\+\(\w\+\)\s*.*;$/ \2: \L\1;/
export enum UserGender {
MALE,
FEMALE,
UNSPECIFIED
}
export class User {
nick: string;
login: string;
eventuserId: number;
userId: number;
firstname: string;
lastname: string;
password: string;
birthday: Date;
gender: UserGender;
phoneNumber: string;
email: string;
streetAddress: string;
zipCode: string;
postOffice: string;
constructor() { }
}
/**
* Created by tuukka on 04/02/17.
*/
"use strict";
var VipProductDelivery = (function () {
function VipProductDelivery() {
}
return VipProductDelivery;
}());
exports.VipProductDelivery = VipProductDelivery;
/**
* Created by tuukka on 04/02/17.
*/
export class VipProductDelivery {
/*
public Integer id;
public Integer delivererId;
public BigDecimal quantity;
public Date deliveryTime;
public String notes;
*/
id: number;
delivererId: number;
quantity: number;
deliveryTime: Date;
notes: string;
constructor() {}
}
"use strict";
/**
* Created by tuukka on 04/02/17.
*/
var VipProduct = (function () {
function VipProduct() {
}
return VipProduct;
}());
exports.VipProduct = VipProduct;
import {VipProductDelivery} from "./vip-product-delivery.model";
/**
* Created by tuukka on 04/02/17.
*/
export class VipProduct {
/*
public Integer id;
public String name;
public Integer productId;
public String notes;
public BigDecimal quantity;
public BigDecimal delivered;
public List<VipProductDeliveryPojo> deliveries = new ArrayList<>();
*/
id: number;
name: string;
productId: number;
notes: string;
quantity: number;
delivered: number;
deliveries : VipProductDelivery[];
constructor() {}
}
"use strict";
/**
* Created by tuukka on 04/02/17.
*/
var Vip = (function () {
function Vip() {
}
return Vip;
}());
exports.Vip = Vip;
import {VipProduct} from "./vip-product.model";
import {User} from "./user.model";
/**
* Created by tuukka on 04/02/17.
*/
export class Vip {
/*
public Integer id;
public String description;
public String shortdescr;
public Date created;
public Integer eventuserId;
public Integer creatorId;
public Integer hostId;
public List<VipProductPojo> products = new ArrayList<>();
*/
id: number;
description: string;
shortdescr: string;
created: Date;
eventuserId: number;
creatorId: number;
host: User;
products: VipProduct[];
constructor() {
}
}
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var core_1 = require("@angular/core");
var rxjs_1 = require("rxjs");
var DEFAULT_EXPIRE_MS = 300000; // 5min
var CachedItem = (function () {
function CachedItem(moduleName, path, value, isObservable) {
this.moduleName = moduleName;
this.path = path;
this.value = value;
this.expires = new Date();
this.expires.setTime(Date.now() + DEFAULT_EXPIRE_MS);
this.isObservable = isObservable;
}
CachedItem.prototype.isExpired = function () {
return this.expires.getTime() < Date.now();
};
return CachedItem;
}());
/**
* Basic cacheService.
*
* First this was part of moyaRestService, but I thinked that if cache is too easy to use, someone will kill this application with it.
* So let's make it litlebit harder
*/
var CacheService = (function () {
// TODO: timed clearup for cache to save memory
function CacheService(zone) {
this.zone = zone;
this.cache = new Map();
this.timerObservable = rxjs_1.Observable.timer(30000, 30000); // afther 0.5min, every 0.5min.
}
/**
* This will return observable with value from cache, or cache value from your observable and return it in observable.
*
* example: return cacheService.cacheObservable("mymodule",<url>, http.get(<url>).map(v => v.json()));
*
* @param moduleName
* @param cachePath
* @param source: {Observable<any>} Observable where the values, which are cached, is coming from
* @return {Observable<any>}: if value is in cache, this is observable made from this value. Otherwise this is source observable.
*/
CacheService.prototype.cacheObservable = function (moduleName, cachePath, source) {
var _this = this;
var cacheName = this.generateCachename(moduleName, cachePath);
if (this.cache.has(cacheName) && this.cache.get(cacheName).expires.getTime() < Date.now()) {
console.log(cacheName, " Expired version in cache");
this.cache.delete(cacheName);
}
if (!this.cache.has(cacheName)) {
/*
not in cache, let's change source to hot -observable, and return one instance from it
problem is, that before this observable is runned, there can be queries for this value from cache.
So, let's change this to hot-observable, and put that hot-observable into the cache.
And in first run, we change this hot observable to it's value.
Javascript is asynchronous, so there is no need to worry some weird things that could happen in multithreaded languages.
*/
console.log(cacheName, " not in cache");
var hotSource = source
.do(function (val) { return _this.cache.set(cacheName, new CachedItem(moduleName, cachePath, val)); })
.publishLast().refCount();
this.cache.set(cacheName, new CachedItem(moduleName, cachePath, hotSource, true));
this.checkCleanTimer();
return hotSource;
}
var cacheItem = this.cache.get(cacheName);
// if value is hotObservable, return it, otherwise create observable from value
if (cacheItem.isObservable) {
console.log(cacheName, " hot observable in cache ");
return cacheItem.value;
}
console.log(cacheName, " value in cache");
this.checkCleanTimer();
return rxjs_1.Observable.of(cacheItem.value);
};
CacheService.prototype.clean = function () {
this.cache.clear();
this.checkCleanTimer();
};
CacheService.prototype.cleanExpired = function () {
var _this = this;
this.cache.forEach(function (v, k) {
if (v.isExpired()) {
console.log(k, " Cache expired");
_this.cache.delete(k);
}
});
this.checkCleanTimer();
};
CacheService.prototype.checkCleanTimer = function () {
var _this = this;
if (this.cache.size > 0) {
if (!this.timerSubscription) {
console.log("adding clearing timer");
this.zone.runOutsideAngular(function () {
_this.timerSubscription = _this.timerObservable.subscribe(function (v) {
_this.cleanExpired();
});
});
}
}
else {
if (this.timerSubscription) {
console.log("removing clearing timer");
this.timerSubscription.unsubscribe();
}
}
};
/**
*
* @param moduleName
* @param cachePath
* @param value
*/
CacheService.prototype.set = function (moduleName, cachePath, value) {
var cacheName = this.generateCachename(moduleName, cachePath);
this.cache.set(cacheName, new CachedItem(moduleName, cachePath, value));
};
/**
* Get one value from cache.
*
* Now when there is this observablethingy. Make public afther rethinking this.
*
* @param moduleName
* @param cachePath
* @return {any|null} Null if nothing is in cache.
*/
CacheService.prototype.get = function (moduleName, cachePath) {
var cacheName = this.generateCachename(moduleName, cachePath);
if (this.cache.has(cacheName) && this.cache.get(cacheName).expires.getTime() < Date.now()) {
this.cache.delete(cacheName);
}
if (this.cache.has(cacheName)) {
return this.cache.get(cacheName);
}
return null;
};
CacheService.prototype.generateCachename = function (moduleName, cachePath) {
return moduleName + "::" + cachePath;
};
CacheService = __decorate([
core_1.Injectable()
], CacheService);
return CacheService;
}());
exports.CacheService = CacheService;
/* tslint:disable:no-unused-variable */
import { TestBed, async, inject } from '@angular/core/testing';
import { CacheService } from './cache.service';
describe('CacheService', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [CacheService]
});
});
it('should ...', inject([CacheService], (service: CacheService) => {
expect(service).toBeTruthy();
}));
});
import {Injectable, NgZone} from "@angular/core";
import {Observable} from "rxjs/Observable";
import 'rxjs/add/observable/timer';
import {forkJoin} from "rxjs/observable/forkJoin";
import "rxjs/add/operator/do";
import "rxjs/add/operator/publishLast";
import "rxjs/add/observable/of";
import {Subscription} from "rxjs/Subscription";
const DEFAULT_EXPIRE_MS = 300000; // 5min
class CachedItem {
moduleName: string;
path: string;
value: any;
expires: Date;
isObservable: boolean;
constructor(moduleName: string, path: string, value: any, isObservable? : boolean) {
this.moduleName = moduleName;
this.path = path;
this.value = value;
this.expires = new Date();
this.expires.setTime(Date.now() + DEFAULT_EXPIRE_MS);
this.isObservable = isObservable;
}
public isExpired(): boolean {
return this.expires.getTime() < Date.now();
}
}
/**
* Basic cacheService.
*
* First this was part of moyaRestService, but I thinked that if cache is too easy to use, someone will kill this application with it.
* So let's make it litlebit harder
*/
@Injectable()
export class CacheService {
private timerSubscription : Subscription;
private timerObservable: Observable<any>;
private cache: Map<string, CachedItem>;
// TODO: timed clearup for cache to save memory
constructor(private zone : NgZone) {
this.cache = new Map<string, CachedItem>();
this.timerObservable = Observable.timer(30000, 30000); // afther 0.5min, every 0.5min.
}
/**
* This will return observable with value from cache, or cache value from your observable and return it in observable.
*
* example: return cacheService.cacheObservable("mymodule",<url>, http.get(<url>).map(v => v.json()));
*
* @param moduleName
* @param cachePath
* @param source: {Observable<any>} Observable where the values, which are cached, is coming from
* @return {Observable<any>}: if value is in cache, this is observable made from this value. Otherwise this is source observable.
*/
public cacheObservable(moduleName: string, cachePath: string, source: Observable<any>): Observable<any> {
let cacheName = this.generateCachename(moduleName, cachePath);
if(this.cache.has(cacheName) && this.cache.get(cacheName).expires.getTime() < Date.now()) {
console.log(cacheName, " Expired version in cache");
this.cache.delete(cacheName);
}
if(!this.cache.has(cacheName)) {
/*
not in cache, let's change source to hot -observable, and return one instance from it
problem is, that before this observable is runned, there can be queries for this value from cache.
So, let's change this to hot-observable, and put that hot-observable into the cache.
And in first run, we change this hot observable to it's value.
Javascript is asynchronous, so there is no need to worry some weird things that could happen in multithreaded languages.
*/
console.log(cacheName," not in cache");
let hotSource = source
.do(val => this.cache.set(cacheName, new CachedItem(moduleName,cachePath, val)))
.publishLast().refCount();
this.cache.set(cacheName, new CachedItem(moduleName,cachePath, hotSource, true));
this.checkCleanTimer();
return hotSource;
}
let cacheItem = this.cache.get(cacheName);
// if value is hotObservable, return it, otherwise create observable from value
if(cacheItem.isObservable) {
console.log(cacheName, " hot observable in cache ");
return cacheItem.value;
}
console.log(cacheName, " value in cache");
this.checkCleanTimer();
return Observable.of(cacheItem.value);
}
public clean(): void {
this.cache.clear();
this.checkCleanTimer();
}
public cleanExpired(): void {
this.cache.forEach((v,k) => {
if(v.isExpired()) {
console.log(k, " Cache expired");
this.cache.delete(k);
}});
this.checkCleanTimer();
}
private checkCleanTimer() {
if(this.cache.size > 0) {
if(!this.timerSubscription) {
console.log("adding clearing timer");
this.zone.runOutsideAngular(() => {
this.timerSubscription = this.timerObservable.subscribe(v => {
this.cleanExpired();
});
});
}
} else {
if(this.timerSubscription) {
console.log("removing clearing timer");
this.timerSubscription.unsubscribe();
}
}
}
/**
*
* @param moduleName
* @param cachePath
* @param value
*/
private set(moduleName: string, cachePath: string, value: any): void {
let cacheName = this.generateCachename(moduleName, cachePath);
this.cache.set(cacheName, new CachedItem(moduleName,cachePath, value));
}
/**
* Get one value from cache.
*
* Now when there is this observablethingy. Make public afther rethinking this.
*
* @param moduleName
* @param cachePath
* @return {any|null} Null if nothing is in cache.
*/
private get(moduleName: string, cachePath: string): CachedItem {
let cacheName = this.generateCachename(moduleName, cachePath);
if(this.cache.has(cacheName) && this.cache.get(cacheName).expires.getTime() < Date.now()) {
this.cache.delete(cacheName);
}
if(this.cache.has(cacheName)) {
return this.cache.get(cacheName);
}
return null;
}
private generateCachename(moduleName: string, cachePath: string): string {
return moduleName + "::" + cachePath;
}
}
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var core_1 = require('@angular/core');
var rxjs_1 = require("rxjs");
var MoyaRestService = (function () {
function MoyaRestService(http) {
this.http = http;
}
MoyaRestService.prototype.post = function (subUrl, body, pathParameters) {
return this.http.post(this.genUrl(subUrl, pathParameters), body)
.map(this.handleResponse)
.catch(this.handleException);
};
MoyaRestService.prototype.put = function (subUrl, body, pathParameters) {
return this.http.put(this.genUrl(subUrl, pathParameters), body)
.map(this.handleResponse)
.catch(this.handleException);
};
MoyaRestService.prototype.delete = function (subUrl, pathParameters) {
return this.http.delete(this.genUrl(subUrl, pathParameters))
.map(this.handleResponse)
.catch(this.handleException);
};
MoyaRestService.prototype.get = function (subUrl, pathParameters) {
return this.http.get(this.genUrl(subUrl, pathParameters))
.map(this.handleResponse)
.catch(this.handleException);
};
MoyaRestService.prototype.genUrl = function (subUrl, urlParams) {
var suffix = "";
if (urlParams) {
urlParams.forEach(function (value, key) {
if (suffix.length <= 0) {
suffix = "?";
}
else {
suffix += "&";
}
suffix += key + "=" + value;
});
}
return "/MoyaWeb/rest/" + subUrl + suffix; // <-- TODO: kauneista
};
MoyaRestService.prototype.handleResponse = function (res) {
// basicly, 200 statuscodes means success
if (!(res.status >= 200 && res.status <= 299)) {
console.log("statuscode not between 200 and 299", res.status);
// next stop: handlerException
throw res;
}
return res;
};
MoyaRestService.prototype.handleException = function (error) {
console.log("error on jira rest connection", error);
// TODO: add handlers to 403's and other "not logged in" or "invalid permissions" -statuscodes, and route them using some nice global parameter
return rxjs_1.Observable.throw(error);
};
MoyaRestService = __decorate([
core_1.Injectable()
], MoyaRestService);
return MoyaRestService;
}());
exports.MoyaRestService = MoyaRestService;
/* tslint:disable:no-unused-variable */
import { TestBed, async, inject } from '@angular/core/testing';
import { MoyaRestService } from './moya-rest.service';
describe('MoyaRestService', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [MoyaRestService]
});
});
it('should ...', inject([MoyaRestService], (service: MoyaRestService) => {
expect(service).toBeTruthy();
}));
});
import { Injectable } from '@angular/core';
import {Observable} from "rxjs/Observable";
import "rxjs/add/operator/catch";
import {HttpClient, HttpResponse} from "@angular/common/http";
@Injectable()
export class MoyaRestService {
constructor(private http: HttpClient) { }
post(subUrl: string, body: any, pathParameters?: Map<string, string>): Observable<HttpResponse<any> > {
return this.http.post(this.genUrl(subUrl, pathParameters), body)
.map(this.handleResponse)
.catch(this.handleException);
}
put(subUrl: string, body: any, pathParameters?: Map<string, string>): Observable<HttpResponse <any>> {
return this.http.put(this.genUrl(subUrl, pathParameters), body)
.map(this.handleResponse)
.catch(this.handleException);
}
delete(subUrl: string, pathParameters?: Map<string, string>): Observable<HttpResponse<any> > {
return this.http.delete(this.genUrl(subUrl, pathParameters))
.map(this.handleResponse)
.catch(this.handleException);
}
get(subUrl: string, pathParameters?: Map<string, string>): Observable<HttpResponse<any> > {
return this.http.get(this.genUrl(subUrl, pathParameters))
.map(this.handleResponse)
.catch(this.handleException);
}
private genUrl(subUrl: string, urlParams?: Map<string, string>): string {
let suffix = "";
if(urlParams) {
urlParams.forEach(function(value: string, key: string) {
if(suffix.length <= 0) {
suffix = "?";
} else {
suffix += "&";
}
suffix += key + "=" + value;
});
}
return "/MoyaWeb/rest/" + subUrl + suffix; // <-- TODO: kauneista
}
private handleResponse(res: HttpResponse<any>) {
// basicly, 200 statuscodes means success
if(!(res.status >= 200 && res.status <= 299 )) {
console.log("statuscode not between 200 and 299", res.status);
// next stop: handlerException
throw res;
}
return res;
}
private handleException(error: HttpResponse<any> | any) {
console.log("error on jira rest connection", error);
// TODO: add handlers to 403's and other "not logged in" or "invalid permissions"
// -statuscodes, and route them using some nice global parameter
return Observable.throw(error);
}
}
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var core_1 = require("@angular/core");
var rxjs_1 = require("rxjs");
var UserService = (function () {
function UserService(moyaRest, cacheService) {
this.moyaRest = moyaRest;
this.cacheService = cacheService;
}
UserService.prototype.get = function (id) {
if (!id || id < 0) {
return rxjs_1.Observable.throw("There should be userid");
}
var path = "v2/user/" + id;
return this.cacheService.cacheObservable("moya:UserService", path, this.moyaRest.get(path)
.do(function (v) { console.log("getting user outside of cache", path); })
.map(function (res) { return (res.json()); }));
};
UserService = __decorate([
core_1.Injectable()
], UserService);
return UserService;
}());
exports.UserService = UserService;
/* tslint:disable:no-unused-variable */
import { TestBed, async, inject } from '@angular/core/testing';
import { UserService } from './user.service';
describe('UserService', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [UserService]
});
});
it('should ...', inject([UserService], (service: UserService) => {
expect(service).toBeTruthy();
}));
});
import {Injectable} from "@angular/core";
import {User} from "../models/user.model";
import {MoyaRestService} from "./moya-rest.service";
import {CacheService} from "./cache.service";
import {Observable} from "rxjs/Observable";
@Injectable()
export class UserService {
constructor(private moyaRest : MoyaRestService, private cacheService : CacheService) { }
public get(id: number): Observable<User> {
if(!id || id < 0) {
return Observable.throw("There should be userid");
}
let path = "v2/user/" + id;
return this.cacheService.cacheObservable("moya:UserService", path,
this.moyaRest.get(path)
.do(v => {console.log("getting user outside of cache", path)})
.map(res => (<User> res.body)));
}
}
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator.throw(value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments)).next());
});
};
var core_1 = require('@angular/core');
var rxjs_1 = require("rxjs");
var ViplistService = (function () {
function ViplistService(moyaRestService, userService) {
this.moyaRestService = moyaRestService;
this.userService = userService;
}
/**
* get vips
* @param searchString: searchString, skip to return all vips
*/
ViplistService.prototype.get = function (searchString) {
var _this = this;
if (!searchString) {
return this.moyaRestService.get("v3/vip/all")
.switchMap(function (res) { return rxjs_1.Observable.forkJoin.apply(rxjs_1.Observable, res.json().map(function (apiRow) { return _this.hostPopulator(apiRow); })); });
}
return this.moyaRestService.get("v3/vip/search/" + searchString)
.switchMap(function (v) { return rxjs_1.Observable.forkJoin.apply(rxjs_1.Observable, v.json().map(function (x) { return _this.hostPopulator(x); })); });
};
/**
* Delete vip.
*
* @param vip
* @return Observable
*/
ViplistService.prototype.delete = function (vip) {
return __awaiter(this, void 0, Promise, function* () {
if (!vip.id)
throw new Error("TODO: errori, tyhmä vippi");
var res = yield this.moyaRestService.delete("v3/vip/" + vip.id)
.first()
.toPromise();
return res.ok;
});
};
/*
public deleteProm(vip: Vip): Promise<boolean> {
if (!vip.id)
throw new Error("TODO: errori, tyhmä vippi");
return this.moyaRestService.delete("v3/vip/" + vip.id)
.first()
.toPromise()
.then(r => r.ok);
}
*/
ViplistService.prototype.getWithId = function (id) {
return this.moyaRestService.get("v3/vip/" + id)
.map(function (v) { return v.json(); });
};
ViplistService.prototype.create = function (vip) {
return this.moyaRestService.post("v3/vip/create", vip)
.map(function (v) { return v.json(); });
};
ViplistService.prototype.hostPopulator = function (rawVip) {
return this.userService.get(rawVip.hostId)
.map(function (u) { rawVip.host = u; return rawVip; });
};
ViplistService = __decorate([
core_1.Injectable()
], ViplistService);
return ViplistService;
}());
exports.ViplistService = ViplistService;
/* tslint:disable:no-unused-variable */
import { TestBed, async, inject } from '@angular/core/testing';
import { ViplistService } from './viplist.service';
describe('ViplistService', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [ViplistService]
});
});
it('should ...', inject([ViplistService], (service: ViplistService) => {
expect(service).toBeTruthy();
}));
});
import {Injectable} from '@angular/core';
import {MoyaRestService} from "./moya-rest.service";
import {Vip} from "../models/vip.model";
import {Response} from "@angular/http";
import {User} from "../models/user.model";
import {UserService} from "./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 {HttpResponse} from "@angular/common/http";
@Injectable()
export class ViplistService {
constructor(private moyaRestService: MoyaRestService, private userService : UserService) {
}
/**
* get vips
* @param searchString: searchString, skip to return all vips
*/
public get(searchString?: string): Observable<Array<Vip>> {
if (!searchString) {
return this.moyaRestService.get("v3/vip/all")
.switchMap(res => Observable.forkJoin(...res.body.map(apiRow => this.hostPopulator(apiRow))));
}
return this.moyaRestService.get("v3/vip/search/" + searchString)
.switchMap(v => Observable.forkJoin(...v.body.map(x => this.hostPopulator(x))));
}
/**
* Delete vip.
*
* @param vip
* @return Promise
*/
public async delete(vip: Vip): Promise<boolean> {
if (!vip.id)
throw new Error("TODO: errori, tyhmä vippi");
let res: HttpResponse<any> = await this.moyaRestService.delete("v3/vip/" + vip.id)
.first()
.toPromise();
return res.ok;
}
public getWithId(id: number): Observable<Vip> {
return this.moyaRestService.get("v3/vip/" + id)
.map(v => v.body);
}
public create(vip: Vip): Observable<Vip> {
return this.moyaRestService.post("v3/vip/create", vip)
.map(v => v.body);
}
private hostPopulator(rawVip : any): Observable<Vip> {
return this.userService.get(rawVip.hostId)
.map((u: User) => {rawVip.host = u; return <Vip> rawVip });
}
}
...@@ -12,27 +12,23 @@ export class MoyaRestService { ...@@ -12,27 +12,23 @@ export class MoyaRestService {
constructor(private http: HttpClient) { } constructor(private http: HttpClient) { }
post(subUrl: string, body: any, pathParameters?: Map<string, string>): Observable<HttpResponse<any> > { post(subUrl: string, body: any, pathParameters?: Map<string, string>): Observable<any> {
return this.http.post(this.genUrl(subUrl, pathParameters), body) return this.http.post(this.genUrl(subUrl, pathParameters), body)
.map(this.handleResponse)
.catch(this.handleException); .catch(this.handleException);
} }
put(subUrl: string, body: any, pathParameters?: Map<string, string>): Observable<HttpResponse <any>> { put(subUrl: string, body: any, pathParameters?: Map<string, string>): Observable<any> {
return this.http.put(this.genUrl(subUrl, pathParameters), body) return this.http.put(this.genUrl(subUrl, pathParameters), body)
.map(this.handleResponse)
.catch(this.handleException); .catch(this.handleException);
} }
delete(subUrl: string, pathParameters?: Map<string, string>): Observable<HttpResponse<any> > { delete(subUrl: string, pathParameters?: Map<string, string>): Observable<any> {
return this.http.delete(this.genUrl(subUrl, pathParameters)) return this.http.delete(this.genUrl(subUrl, pathParameters))
.map(this.handleResponse)
.catch(this.handleException); .catch(this.handleException);
} }
get(subUrl: string, pathParameters?: Map<string, string>): Observable<HttpResponse<any> > { get(subUrl: string, pathParameters?: Map<string, string>): Observable<any> {
return this.http.get(this.genUrl(subUrl, pathParameters)) return this.http.get(this.genUrl(subUrl, pathParameters))
.map(this.handleResponse)
.catch(this.handleException); .catch(this.handleException);
} }
...@@ -56,8 +52,12 @@ export class MoyaRestService { ...@@ -56,8 +52,12 @@ export class MoyaRestService {
return "/MoyaWeb/rest/" + subUrl + suffix; // <-- TODO: kauneista return "/MoyaWeb/rest/" + subUrl + suffix; // <-- TODO: kauneista
} }
/*
private handleResponse(res: HttpResponse<any>) { private handleResponse(res: HttpResponse<any>) {
console.log(res);
// basicly, 200 statuscodes means success // basicly, 200 statuscodes means success
if(!(res.status >= 200 && res.status <= 299 )) { if(!(res.status >= 200 && res.status <= 299 )) {
console.log("statuscode not between 200 and 299", res.status); console.log("statuscode not between 200 and 299", res.status);
...@@ -67,7 +67,7 @@ export class MoyaRestService { ...@@ -67,7 +67,7 @@ export class MoyaRestService {
} }
return res; return res;
} }*/
private handleException(error: HttpResponse<any> | any) { private handleException(error: HttpResponse<any> | any) {
......
...@@ -27,11 +27,11 @@ export class ViplistService { ...@@ -27,11 +27,11 @@ export class ViplistService {
if (!searchString) { if (!searchString) {
return this.moyaRestService.get("v3/vip/all") return this.moyaRestService.get("v3/vip/all")
.switchMap(res => Observable.forkJoin(...res.body.map(apiRow => this.hostPopulator(apiRow)))); .switchMap(res => Observable.forkJoin(...res.map(apiRow => this.hostPopulator(apiRow))));
} }
return this.moyaRestService.get("v3/vip/search/" + searchString) return this.moyaRestService.get("v3/vip/search/" + searchString)
.switchMap(v => Observable.forkJoin(...v.body.map(x => this.hostPopulator(x)))); .switchMap(v => Observable.forkJoin(...v.map(x => this.hostPopulator(x))));
} }
...@@ -56,13 +56,13 @@ export class ViplistService { ...@@ -56,13 +56,13 @@ export class ViplistService {
public getWithId(id: number): Observable<Vip> { public getWithId(id: number): Observable<Vip> {
return this.moyaRestService.get("v3/vip/" + id) return this.moyaRestService.get("v3/vip/" + id)
.map(v => v.body);
} }
public create(vip: Vip): Observable<Vip> { public create(vip: Vip): Observable<Vip> {
return this.moyaRestService.post("v3/vip/create", vip) return this.moyaRestService.post("v3/vip/create", vip)
.map(v => v.body);
} }
private hostPopulator(rawVip : any): Observable<Vip> { private hostPopulator(rawVip : any): Observable<Vip> {
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!