File: /var/dev/nowruzgan/admin/src/app/services/word.service.ts
import { Injectable } from '@angular/core';
import { GenericService } from './generic.service';
import { Batch, Word } from '../data.types';
import { environment } from '../../environments/environment';
@Injectable()
export class WordService extends GenericService {
async list(wordsBatch: Batch<Word>) {
wordsBatch.meta.busy = true;
let more: string[] = [];
more.push(`skip=${wordsBatch.offset || 0}`);
more.push(`limit=${wordsBatch.limit || 30}`);
more.push(`sort=${wordsBatch.sort}`);
more.push(wordsBatch.filter ? `filter=${wordsBatch.filter}` : '');
for(let key of Object.keys(wordsBatch.constraints))
more.push(`${key}=${wordsBatch.constraints[key]}`);
let response = await this.http
.get(`${environment.apiBase}/lexicon/word?${more.join('&')}`, this.headers)
.toPromise().catch(e => {
this.handleError(e);
return {sum: 0, limit: 0, list: []};
});
wordsBatch.absorb(response);
wordsBatch.meta.busy = false;
}
async create(word: Word): Promise<Word | null> {
word.meta.busySave = true;
word.meta.errorSave = false;
try {
let wordData = await this.http
.post(`${environment.apiBase}/lexicon/word`, word.trans, this.headers)
.toPromise();
word.meta.busySave = false;
return new Word(wordData);
}catch(e) {
this.handleError(e);
word.meta.busySave = false;
word.meta.errorSave = true;
return null;
}
}
async save(word: Word): Promise<boolean> {
word.meta.busySave = true;
word.meta.errorSave = false;
try {
let wordData = await this.http
.patch(`${environment.apiBase}/lexicon/word/${word.id}`, word.trans, this.headers)
.toPromise();
word.meta.busySave = false;
word.meta.errorSave = !wordData;
return !!wordData;
}catch(e) {
this.handleError(e);
word.meta.busySave = false;
word.meta.errorSave = true;
return false;
}
}
async load(id: number): Promise<Word | null> {
let wordData = await this.http
.get(`${environment.apiBase}/lexicon/word/${id}`, this.headers)
.toPromise()
.catch(error => false);
if(!wordData) return null;
return new Word(wordData);
}
async remove(word: Word): Promise<boolean> {
word.meta.busyDelete = true;
word.meta.errorDelete = false;
try {
let result: any = await this.http
.delete(`${environment.apiBase}/lexicon/word/${word.id}`, this.headers)
.toPromise();
word.meta.busyDelete = false;
return true;
}catch(e) {
this.handleError(e);
word.meta.busyDelete = false;
word.meta.errorDelete = true;
return false;
}
}
async search(term: string, lang?: string): Promise<Word[]> {
lang = lang ? `lang=${lang}` : '';
let response: any = await this.http
.get(`${environment.apiBase}/lexicon/word?filter=${term}&${lang}`, this.headers)
.toPromise().catch(e => {this.handleError(e); return{list: []};});
return response.list.map((record: any) => new Word(record));
}
}