Files
doneit-web/src/app/services/http.service.ts
T
Peter Maquiran bf1457417d add contacts
2024-06-10 16:34:43 +01:00

56 lines
1.4 KiB
TypeScript

import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { ok, err, Result } from 'neverthrow';
@Injectable({
providedIn: 'root'
})
export class HttpService {
constructor(private http:HttpClient) { }
async post<T>(url: string, body: any): Promise<Result<T, HttpErrorResponse>> {
try {
const result = await this.http.post(url, body).toPromise()
return ok (result as T)
} catch (e) {
return err(e as HttpErrorResponse)
}
}
async get<T>(url: string): Promise<Result<T, HttpErrorResponse>> {
try {
const result = await this.http.get<T>(url).toPromise()
return ok (result as T)
} catch (e) {
return err(e as HttpErrorResponse)
}
}
async put<T>(url: string, body: any): Promise<Result<T, HttpErrorResponse>> {
try {
const result = await this.http.put<T>(url, body).toPromise()
return ok (result as T)
} catch (e) {
return err(e as HttpErrorResponse)
}
}
async delete<T>(url: string, body = {}): Promise<Result<T, HttpErrorResponse>> {
const options = {
body: body // Pass payload as the body of the request
};
try {
const result = await this.http.delete<T>(url, options).toPromise()
return ok (result as T)
} catch (e) {
return err(e as HttpErrorResponse)
}
}
}