game-village-politics-frontend/app/utils/networking.ts

89 lines
3.1 KiB
TypeScript
Raw Permalink Normal View History

import { createApiClient, type WsClientConfig } from '@blax-software/networking'
import { createVueWsClient, type VueWsClient } from '@blax-software/networking/vue'
import type { AuthResult, GameError } from '~/types/game'
import { createMockServer } from '~/mock/server'
/** The part of the WS client the game uses. The mock server implements the same surface. */
export type GameWs = Pick<
VueWsClient,
'send' | 'listen' | 'listenWhileMounted' | 'is_setup' | 'is_opened' | 'resetConnection'
>
/** HTTP is only for getting the bearer token; everything else goes over `ws`. */
export interface GameAuth {
token(): string | null
login(email: string, password: string): Promise<AuthResult>
register(name: string, email: string, password: string, terms: boolean): Promise<AuthResult>
logout(): void
}
export interface NetworkingOptions {
serverUrl: string
wsUrl: string
appKey: string
mock: boolean
notify?: WsClientConfig['notify']
translate?: WsClientConfig['translate']
}
// The app's singletons, assigned once by plugins/networking.ts before any page runs.
export let ws: GameWs
export let gameAuth: GameAuth
export let isMockServer = false
export function setupNetworking(options: NetworkingOptions) {
if (options.mock) {
const mock = createMockServer()
ws = mock.ws
gameAuth = mock.auth
isMockServer = true
return
}
// Bearer token only, no cookies, so the API can allow any origin (web and Steam).
const api = createApiClient({ serverUrl: options.serverUrl, notify: options.notify, withCredentials: false })
api.loadBearerFromStorage()
const client = createVueWsClient({
url: options.wsUrl,
appKey: options.appKey,
getAuthToken: () => api.bearerToken || null,
notify: options.notify,
translate: options.translate,
sendTimeout: 15000,
rejectOnDisconnect: true,
})
// The WS server authenticates a socket from `authtoken` in the message data (as in
// learn-atc), so every send carries the bearer token.
const rawSend = client.send.bind(client)
client.send = ((event: string, data: object = {}, channel?: string | null, progress?: any) =>
rawSend(event, { ...data, authtoken: api.bearerToken || undefined }, channel, progress)) as typeof client.send
client.setAppReady()
ws = client
const signIn = (result: AuthResult) => {
api.setBearer(result.token)
client.resetConnection()
return result
}
// Pass the server's `{ code, message }` on, like a refused WS intent.
const refused = (e: any): never => {
throw { message: e?.response?.data?.message ?? e?.message, code: e?.response?.data?.code, field: e?.response?.data?.field ?? undefined } satisfies GameError
}
gameAuth = {
token: () => api.bearerToken || null,
login: async (email, password) =>
signIn((await api.post<AuthResult>('auth/login', { email, password }).catch(refused)).data),
register: async (name, email, password, terms) =>
signIn((await api.post<AuthResult>('auth/register', { name, email, password, terms }).catch(refused)).data),
logout() {
api.setBearer(null)
client.resetConnection()
},
}
}