accountant-ui/src/operations/operation.service.ts

72 lines
1.6 KiB
TypeScript

// vim: set tw=80 ts=2 sw=2 sts=2 :
import * as moment from 'moment';
import { Injectable } from '@angular/core';
import { HttpClient, HttpParams } from '@angular/common/http';
import { Observable } from 'rxjs/Rx';
import { Operation } from './operation';
@Injectable()
export class OperationService {
constructor(
private http: HttpClient,
) {}
formatDate(date: Date|string) {
if(date instanceof Date) {
return moment(date).format('YYYY-MM-DD');
}
return date;
}
private url(id?: Number): string {
if(id) {
return `/api/operation/${id}`;
}
return `/api/operation`;
}
query(
accountId: number,
minDate: Date|string = null,
maxDate: Date|string = null
): Observable<Operation[]> {
let params = new HttpParams();
params = params.set('account_id', `${accountId}`);
if(minDate) {
params = params.set('begin', this.formatDate(minDate));
}
if(maxDate) {
params = params.set('end', this.formatDate(maxDate));
}
return this.http.get<Operation[]>(this.url(), {
params: params
});
}
get(id: number): Observable<Operation> {
return this.http.get<Operation>(this.url(id));
}
create(operation: Operation): Observable<Operation> {
return this.http.post<Operation>(this.url(), operation);
}
update(operation: Operation): Observable<Operation> {
return this.http.post<Operation>(this.url(operation.id), operation);
}
delete(operation: Operation): Observable<Operation> {
return this.http.delete<Operation>(this.url(operation.id));
}
}