mirror of
https://code.equilibrium.co.ao/ITO/doneit-web.git
synced 2026-04-20 13:26:08 +00:00
74 lines
1.8 KiB
TypeScript
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';
|
|
}
|
|
|