Files
ppc_amnet/amnet-shared/src/api.ts
T
2025-01-14 18:52:08 +00:00

95 lines
2.5 KiB
TypeScript

/**
* The latest version of the AMNet API this library supports
*/
export const AMNET_API_VERSION = 1;
/**
* The minimum version of the AMNet API this library supports
*/
export const MIN_AMNET_API_VERSION = 1;
export interface AMCardInRequest {
cardId: string;
physicalCardIDm?: string;
}
/**
* Server connection info (api version, address, etc.)
*/
export interface AMServerConnectionInfo {
apiVersion: number;
serverAddress: string;
}
/**
* User-definable server metadata
*/
export interface AMServerMetadata {
serverName: string;
gameId?: string | null | undefined;
}
/**
* Metrics about the current game session
*/
export interface AMServerInstanceMetrics {
timeSinceLastPoll?: number;
sessionUptime?: number;
}
/**
* The response from an AMNet server's info endpoint
*/
export type AMServerInfo = AMServerMetadata & AMServerConnectionInfo & AMServerInstanceMetrics;
/**
* Performs the card-in request to the specified server
* @param server The server to perform the request against
* @param request The card-in request to send
* @param signal The abort signal to use for the request
*/
export async function performCardIn(server: AMServerConnectionInfo, request: AMCardInRequest, signal: AbortSignal): Promise<boolean> {
if (server.apiVersion < MIN_AMNET_API_VERSION || server.apiVersion > AMNET_API_VERSION) {
throw new Error("Unsupported server API version");
}
try {
const response = await fetch(`${new URL(server.serverAddress).origin}/amnet/signin`, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(request),
signal: signal
});
return response.ok;
} catch {
return false;
}
}
/**
* Attempts to connect to the specified server and fetch its info
* @param serverAddress The origin address of the server to connect to
* @param abort The abort signal to use for the request (for cancellation)
*/
export async function fetchServerInfo(serverAddress: string, abort: AbortSignal): Promise<AMServerInfo | null> {
try {
const response = await fetch(`${new URL(serverAddress).origin}/amnet/info`, {
signal: abort
});
if (!response.ok) {
return null;
}
return {
...await response.json(),
serverAddress: serverAddress
} satisfies AMServerMetadata;
} catch {
return null;
}
}