Files
doneit-web/src/app/services/http.service.ts
T

74 lines
1.8 KiB
TypeScript
Raw Normal View History

2024-06-13 12:11:17 +01:00
import { HttpClient, HttpErrorResponse, HttpResponse } from '@angular/common/http';
2020-10-30 15:22:35 +01:00
import { Injectable } from '@angular/core';
2024-06-04 09:31:37 +01:00
import { ok, err, Result } from 'neverthrow';
2020-10-30 15:22:35 +01:00
@Injectable({
providedIn: 'root'
})
export class HttpService {
constructor(private http:HttpClient) { }
2024-06-04 09:31:37 +01:00
async post<T>(url: string, body: any): Promise<Result<T, HttpErrorResponse>> {
2020-10-30 15:22:35 +01:00
2024-06-04 09:31:37 +01:00
try {
const result = await this.http.post(url, body).toPromise()
return ok (result as T)
} catch (e) {
return err(e as HttpErrorResponse)
}
2020-10-30 15:22:35 +01:00
}
2024-08-13 17:05:46 +01:00
async get<T>(url: string, options ={}): Promise<Result<T, HttpErrorResponse>> {
2024-06-04 09:31:37 +01:00
try {
2024-08-13 17:05:46 +01:00
const result = await this.http.get<T>(url, options).toPromise()
2024-06-04 09:31:37 +01:00
return ok (result as T)
} catch (e) {
return err(e as HttpErrorResponse)
}
2020-10-30 15:22:35 +01:00
}
2024-06-04 09:31:37 +01:00
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)
}
}
2024-08-06 11:24:00 +01:00
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)
}
}
2024-06-10 16:34:43 +01:00
async delete<T>(url: string, body = {}): Promise<Result<T, HttpErrorResponse>> {
const options = {
body: body // Pass payload as the body of the request
};
2024-06-04 09:31:37 +01:00
try {
2024-06-10 16:34:43 +01:00
const result = await this.http.delete<T>(url, options).toPromise()
2024-06-04 09:31:37 +01:00
return ok (result as T)
} catch (e) {
return err(e as HttpErrorResponse)
}
}
}
2024-06-13 12:11:17 +01:00
export function isHttpResponse(data: any): data is HttpResponse<any> {
return typeof data.status == 'number';
}