59 lines
1.6 KiB
TypeScript
59 lines
1.6 KiB
TypeScript
/**
|
|
* Staff (admin-ui) and user (app) sessions.
|
|
*
|
|
* Logs in once per suite and caches the token, so a bad credential fails once
|
|
* with a clear message rather than on every request.
|
|
*/
|
|
|
|
import { apiClient, assertServerUp } from './api'
|
|
import { adminCredentials, userCredentials } from './env'
|
|
|
|
export interface StaffSession {
|
|
token: string
|
|
staffId: number
|
|
name: string
|
|
}
|
|
|
|
export interface UserSession {
|
|
token: string
|
|
userId: number
|
|
}
|
|
|
|
let staffPromise: Promise<StaffSession> | null = null
|
|
let userPromise: Promise<UserSession> | null = null
|
|
|
|
export function staffSession(): Promise<StaffSession> {
|
|
staffPromise ??= loginStaff()
|
|
return staffPromise
|
|
}
|
|
|
|
export function userSession(): Promise<UserSession> {
|
|
userPromise ??= loginUser()
|
|
return userPromise
|
|
}
|
|
|
|
async function loginStaff(): Promise<StaffSession> {
|
|
await assertServerUp()
|
|
const { name, password } = adminCredentials()
|
|
|
|
const res = await apiClient().admin.staffUser.login.mutate({ name, password })
|
|
if (!res?.token || !res?.staff?.id) {
|
|
throw new Error('[api-tests] admin.staffUser.login returned no token/staff id')
|
|
}
|
|
|
|
return { token: res.token, staffId: res.staff.id, name: res.staff.name }
|
|
}
|
|
|
|
async function loginUser(): Promise<UserSession> {
|
|
await assertServerUp()
|
|
const { identifier, password } = userCredentials()
|
|
|
|
const res = await apiClient().user.auth.login.mutate({ identifier, password })
|
|
const token = res?.data?.token
|
|
const userId = res?.data?.user?.id
|
|
if (!token || !userId) {
|
|
throw new Error('[api-tests] user.auth.login returned no token/user id')
|
|
}
|
|
|
|
return { token, userId: Number(userId) }
|
|
}
|