webextension: introduce typesafe wallet-core API client

This commit is contained in:
Florian Dold 2022-10-16 23:11:34 +02:00
parent ea1aff81df
commit e4f2587cab
No known key found for this signature in database
GPG Key ID: D2E4F00F29D02A4B
2 changed files with 42 additions and 11 deletions

View File

@ -707,17 +707,19 @@ export type WalletOperations = {
[WalletApiOperation.SetDevMode]: SetDevModeOp;
};
export type RequestType<
export type WalletCoreRequestType<
Op extends WalletApiOperation & keyof WalletOperations,
> = WalletOperations[Op] extends { request: infer T } ? T : never;
export type ResponseType<
export type WalletCoreResponseType<
Op extends WalletApiOperation & keyof WalletOperations,
> = WalletOperations[Op] extends { response: infer T } ? T : never;
export type WalletCoreOpKeys = WalletApiOperation & keyof WalletOperations;
export interface WalletCoreApiClient {
call<Op extends WalletApiOperation & keyof WalletOperations>(
call<Op extends WalletCoreOpKeys>(
operation: Op,
payload: RequestType<Op>,
): Promise<ResponseType<Op>>;
payload: WalletCoreRequestType<Op>,
): Promise<WalletCoreResponseType<Op>>;
}

View File

@ -85,7 +85,12 @@ import {
PendingOperationsResponse,
RemoveBackupProviderRequest,
TalerError,
WalletApiOperation,
WalletContractData,
WalletCoreApiClient,
WalletCoreOpKeys,
WalletCoreRequestType,
WalletCoreResponseType,
} from "@gnu-taler/taler-wallet-core";
import { MessageFromBackend, platform } from "./platform/api.js";
@ -121,6 +126,9 @@ export interface UpgradeResponse {
oldDbVersion: string;
}
/**
* @deprecated Use {@link WxWalletCoreApiClient} instead.
*/
async function callBackend(operation: string, payload: any): Promise<any> {
let response: CoreApiResponse;
try {
@ -136,13 +144,31 @@ async function callBackend(operation: string, payload: any): Promise<any> {
return response.result;
}
/**
* Start refreshing a coin.
*/
export function refresh(coinPub: string): Promise<void> {
return callBackend("refresh-coin", { coinPub });
export class WxWalletCoreApiClient implements WalletCoreApiClient {
async call<Op extends WalletCoreOpKeys>(
operation: Op,
payload: WalletCoreRequestType<Op>,
): Promise<WalletCoreResponseType<Op>> {
let response: CoreApiResponse;
try {
response = await platform.sendMessageToWalletBackground(
operation,
payload,
);
} catch (e) {
console.log("Error calling backend");
throw new Error(`Error contacting backend: ${e}`);
}
logger.info("got response", response);
if (response.type === "error") {
throw TalerError.fromUncheckedDetail(response.error);
}
return response.result as any;
}
}
const wxClient = new WxWalletCoreApiClient();
/**
* Pay for a proposal.
*/
@ -150,7 +176,10 @@ export function confirmPay(
proposalId: string,
sessionId: string | undefined,
): Promise<ConfirmPayResult> {
return callBackend("confirmPay", { proposalId, sessionId });
return wxClient.call(WalletApiOperation.ConfirmPay, {
proposalId,
sessionId,
});
}
/**