import { HttpResponse, readSuccessResponseJsonOrThrow, readTalerErrorResponse } from "./http-common.js";
import { Codec, HttpStatusCode, TalerError, TalerErrorCode, TalerErrorDetail } from "./index.js";
export type OperationResult
=
| OperationOk
| OperationAlternative
| OperationFail;
export function isOperationOk(c: OperationResult): c is OperationOk {
return c.type === "ok"
}
export function isOperationFail(c: OperationResult): c is OperationFail {
return c.type === "fail"
}
/**
* succesful operation
*/
export interface OperationOk {
type: "ok",
body: T;
}
/**
* unsuccesful operation, see details
*/
export interface OperationFail {
type: "fail",
case: T,
detail: TalerErrorDetail,
}
/**
* unsuccesful operation, see body
*/
export interface OperationAlternative {
type: "fail",
case: T,
body: B,
}
export async function opSuccess(resp: HttpResponse, codec: Codec): Promise> {
const body = await readSuccessResponseJsonOrThrow(resp, codec)
return { type: "ok" as const, body }
}
export function opFixedSuccess(body: T): OperationOk {
return { type: "ok" as const, body }
}
export function opEmptySuccess(): OperationOk {
return { type: "ok" as const, body: void 0 }
}
export async function opKnownAlternativeFailure(resp: HttpResponse, s: T, codec: Codec): Promise> {
const body = await readSuccessResponseJsonOrThrow(resp, codec)
return { type: "fail", case: s, body }
}
export async function opKnownHttpFailure(s: T, resp: HttpResponse): Promise> {
const detail = await readTalerErrorResponse(resp)
return { type: "fail", case: s, detail }
}
export async function opKnownTalerFailure(s: T, resp: HttpResponse): Promise> {
const detail = await readTalerErrorResponse(resp)
return { type: "fail", case: s, detail }
}
export async function opKnownFailure(s: T, resp: HttpResponse): Promise> {
const detail = await readTalerErrorResponse(resp)
return { type: "fail", case: s, detail }
}
export function opUnknownFailure(resp: HttpResponse, text: string): never {
throw TalerError.fromDetail(
TalerErrorCode.WALLET_UNEXPECTED_REQUEST_ERROR,
{
requestUrl: resp.requestUrl,
requestMethod: resp.requestMethod,
httpStatusCode: resp.status,
errorResponse: text,
},
`Unexpected HTTP status ${resp.status} in response`,
);
}
export type ResultByMethod = TT[p] extends (...args: any[]) => infer Ret ?
Ret extends Promise ?
Result extends OperationResult ? Result : never :
never : //api always use Promises
never; //error cases just for functions
export type FailCasesByMethod = Exclude, OperationOk>