game-village-politics-frontend/app/composables/useWorld.ts

29 lines
861 B
TypeScript
Raw Normal View History

import type { WorldSummary } from '~/types/game'
export function useWorld() {
const worlds = useState<WorldSummary[] | null>('worlds', () => null)
const error = ref<string | null>(null)
const busy = ref(false)
const errorText = useErrorText()
async function run<T>(fn: () => Promise<T>) {
busy.value = true
error.value = null
try {
return await fn()
} catch (e) {
error.value = errorText(e)
} finally {
busy.value = false
}
}
const refresh = () => run(async () => (worlds.value = await ws.send<WorldSummary[]>('world.index')))
/** Joins (or re-enters) a world and returns the player's village there. */
const join = (worldId: number) =>
run(async () => (await ws.send<{ village_id: number }>('world.join', { world_id: worldId })).village_id)
return { worlds, error, busy, refresh, join }
}