Update server.service.ts

This commit is contained in:
piotrpekala7 2020-06-12 12:05:27 +02:00
parent d6808ba1d7
commit 84212c0c33

View File

@ -3,26 +3,51 @@ import { IndexedDbService } from './indexed-db.service';
import { Server } from '../models/server';
import { Observable } from 'rxjs';
import { HttpServer } from './http-server.service';
import { ToasterService } from './toaster.service';
@Injectable()
export class ServerService {
private tablename = 'servers';
private ready: Promise<any>;
private isIncognitoMode: boolean = false;
private serverIdsInIncognitoMode: string[] = [];
constructor(
private indexedDbService: IndexedDbService,
private httpServer: HttpServer
private httpServer: HttpServer,
private toasterService: ToasterService
) {
this.ready = indexedDbService.get().openDatabase(1, evt => {
evt.currentTarget.result.createObjectStore(this.tablename, { keyPath: 'id', autoIncrement: true });
});
this.ready.then(() => {}).catch(() => {
this.isIncognitoMode = true;
})
}
public get(id: number): Promise<Server> {
if (this.isIncognitoMode) {
let server: Server = JSON.parse(localStorage.getItem(`server-${id}`));
let promise = new Promise<Server>(resolve => {
return server;
});
return promise;
}
return this.onReady(() => this.indexedDbService.get().getByKey(this.tablename, id)) as Promise<Server>;
}
public create(server: Server) {
if (this.isIncognitoMode) {
server.id = this.serverIdsInIncognitoMode.length + 1;
localStorage.setItem(`server-${server.id}`, JSON.stringify(server));
let promise = new Promise<Server>(resolve => {
return server;
});
return promise;
}
return this.onReady(() => {
const promise = new Promise((resolve, reject) => {
this.indexedDbService
@ -38,6 +63,13 @@ export class ServerService {
}
public update(server: Server) {
if (this.isIncognitoMode) {
let promise = new Promise<Server>(resolve => {
return [];
});
return promise;
}
return this.onReady(() => {
const promise = new Promise((resolve, reject) => {
this.indexedDbService
@ -52,10 +84,24 @@ export class ServerService {
}
public findAll() {
if (this.isIncognitoMode) {
let promise = new Promise<Server[]>(resolve => {
return [];
});
return promise;
}
return this.onReady(() => this.indexedDbService.get().getAll(this.tablename)) as Promise<Server[]>;
}
public delete(server: Server) {
if (this.isIncognitoMode) {
let promise = new Promise(resolve => {
return [];
});
return promise;
}
return this.onReady(() => this.indexedDbService.get().delete(this.tablename, server.id));
}
@ -68,6 +114,13 @@ export class ServerService {
}
public getLocalServer(host: string, port: number) {
if (this.isIncognitoMode) {
let promise = new Promise(resolve => {
return [];
});
return promise;
}
const promise = new Promise((resolve, reject) => {
this.findAll().then((servers: Server[]) => {
const local = servers.find(server => server.location === 'bundled');