ai-voicebot/client/src/api-usage-examples.ts
James Ketrenos bd94741a82 Improved API generation
Signed-off-by: James Ketrenos <james_git@ketrenos.com>
2025-09-08 10:20:04 -07:00

97 lines
2.5 KiB
TypeScript

/**
* Example: How to update App.tsx to use the generated API types
*
* This demonstrates how to replace local type definitions with the
* generated TypeScript types from your Pydantic models.
*/
// BEFORE (local type definitions):
// type Lobby = {
// id: string;
// name: string;
// private: boolean;
// };
// AFTER (using generated types):
import {
apiClient,
lobbyApi,
sessionApi,
healthApi,
adminApi,
ApiError,
type LobbyModel, // Use this instead of local Lobby type
type LobbyCreateRequest,
type AdminSetPassword,
} from "./api-client";
// Example usage in a React component:
// 1. Fetching data with type safety
const fetchLobbies = async (setLobbies: (lobbies: any[]) => void, setError: (error: string) => void) => {
try {
const response = await lobbyApi.getAll();
// response.lobbies is properly typed as LobbyListItem[]
setLobbies(response.lobbies);
} catch (error) {
if (error instanceof ApiError) {
console.error(`API Error ${error.status}: ${error.statusText}`, error.data);
}
setError("Failed to fetch lobbies");
}
};
// 2. Creating a lobby with typed request
const createNewLobby = async (
sessionId: string,
lobbyName: string,
isPrivate: boolean,
setError: (error: string) => void
) => {
const lobbyRequest: LobbyCreateRequest = {
type: "lobby_create",
data: {
name: lobbyName,
private: isPrivate,
},
};
try {
const newLobby = await sessionApi.createLobby(sessionId, lobbyRequest);
// newLobby.data is properly typed as LobbyModel
console.log("Created lobby:", newLobby.data);
} catch (error) {
if (error instanceof ApiError) {
setError(`Failed to create lobby: ${error.message}`);
}
}
};
// 3. Health check with typing
const checkServerHealth = async () => {
try {
const health = await healthApi.check();
// health.status is properly typed as string
console.log('Server status:', health.status);
} catch (error) {
console.error('Server health check failed:', error);
}
};
// 4. Admin operations with type safety
const setAdminPassword = async (name: string, password: string) => {
const passwordData: AdminSetPassword = { name, password };
try {
const result = await adminApi.setPassword(passwordData);
// result.status is typed as "ok" | "not_found"
if (result.status === "ok") {
console.log('Password set successfully');
}
} catch (error) {
console.error('Failed to set password:', error);
}
};
export { fetchLobbies, createNewLobby, checkServerHealth, setAdminPassword };