Files
doneit-web/src/app/services/http.service.ts
T
Peter Maquiran d7eb6a552b upload attachment
2024-08-13 17:05:46 +01:00

74 lines
1.8 KiB
TypeScript

import { HttpClient, HttpErrorResponse, HttpResponse } 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, options ={}): Promise<Result<T, HttpErrorResponse>> {
try {
const result = await this.http.get<T>(url, options).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 patch<T>(url: string, body: any = {}): Promise<Result<T, HttpErrorResponse>> {
try {
const result = await this.http.patch<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)
}
}
}
export function isHttpResponse(data: any): data is HttpResponse<any> {
return typeof data.status == 'number';
}