Files
grocy-angular/src/app/api/grocy-rest.service.ts
Marc Fokkert c48728d7cd Add basic API connection to Grocy
Add initial table to show entries
2024-11-15 16:51:15 +01:00

81 lines
2.3 KiB
TypeScript

import {inject, Injectable} from '@angular/core';
import {HttpClient, HttpHeaders, HttpResponse} from '@angular/common/http';
import {MatDialog} from '@angular/material/dialog';
import {GrocyConfigDialogComponent} from './grocy-config-dialog/grocy-config-dialog.component';
import {map, Observable, of, switchMap, tap} from 'rxjs';
import _ from 'lodash';
import {LS_GROCY_API_KEY, LS_GROCY_URI} from './grocy';
import {BatchScanRow} from '../batch-scan-table/barcode';
const GROCY_API_HEADER = 'GROCY-API-KEY'
@Injectable({
providedIn: 'root'
})
export class GrocyRestService {
readonly http = inject(HttpClient);
readonly dialog = inject(MatDialog);
private areRequiredKeysPresent(): boolean {
const requiredKeys = [LS_GROCY_API_KEY, LS_GROCY_URI]
return !!requiredKeys
.map(key => localStorage.getItem(key))
.reduce((c, a) => c && a)
}
private ensureApiKeys(): Observable<boolean> {
if (!this.areRequiredKeysPresent()) {
const dialogRef = this.dialog.open(GrocyConfigDialogComponent)
return dialogRef.afterClosed()
}
return of(true)
}
get<T>(uri: string): Observable<HttpResponse<T>> {
return this.ensureApiKeys().pipe(
switchMap(() => {
let headers = new HttpHeaders();
const baseUri = localStorage.getItem(LS_GROCY_URI);
headers = headers.set(GROCY_API_HEADER, localStorage.getItem(LS_GROCY_API_KEY)!)
return this.http.get<T>(`${baseUri}/api${uri}`, {
headers,
observe: "response"
})
})
)
}
getProductIdByBarcode(barcode: string): Observable<string | null> {
return this.get(`/stock/products/by-barcode/${barcode}`).pipe(
map(response => {
if (response.ok) {
return _.get(response.body, 'product.id') as unknown as string;
}
return null;
})
)
}
goToGrocyProductPageUri(productId: string) {
const baseUri = localStorage.getItem(LS_GROCY_URI);
if (window) {
window.open(`${baseUri}/product/${productId}`, '_blank')?.focus();
}
}
getProductId(row: BatchScanRow): Observable<string | null> {
if(row.productId) {
return of(row.productId);
}
return this.getProductIdByBarcode(row.barcode).pipe(
tap(productId => row.productId = row.productId ?? productId)
)
}
}