lifeto-shop/src/state/auth.atoms.ts
2025-06-24 00:37:47 -05:00

92 lines
2.5 KiB
TypeScript

import { AxiosError } from 'axios'
import { atomWithStorage } from 'jotai/utils'
import { atomWithQuery } from 'jotai-tanstack-query'
import { LTOApiv0 } from '../lib/lifeto'
import { LoginHelper, TokenSession } from '../lib/session'
import { TricksterCharacter } from '../lib/trickster'
export const LTOApi = new LTOApiv0(new TokenSession())
export const loginStatusAtom = atomWithQuery((_get) => {
return {
queryKey: ['login_status'],
enabled: true,
placeholderData: {
logged_in: false,
community_name: '...',
code: 102,
},
queryFn: async () => {
return LoginHelper.info()
.then(info => {
return {
logged_in: true,
community_name: info.community_name,
code: 200,
}
})
.catch(e => {
if (e instanceof AxiosError) {
return {
logged_in: false,
community_name: '...',
code: e.response?.status || 500,
}
}
throw e
})
},
}
})
export const charactersAtom = atomWithQuery((get) => {
const { data: loginStatus } = get(loginStatusAtom)
return {
queryKey: ['characters', loginStatus?.community_name || '...'],
enabled: !!loginStatus?.logged_in,
refetchOnMount: true,
queryFn: async () => {
return LTOApi.GetAccounts().then(x => {
if (!x) {
return undefined
}
const rawCharacters = x.flatMap(x => {
return x?.characters
})
const characterPairs: Record<
string,
{ bank?: TricksterCharacter; character?: TricksterCharacter }
> = {}
rawCharacters.forEach(
x => {
let item = characterPairs[x.account_name]
if (!item) {
item = {}
}
if (x.class === -8) {
item.bank = x
} else {
item.character = x
}
characterPairs[x.account_name] = item
},
[rawCharacters],
)
const cleanCharacterPairs = Object.values(characterPairs).filter(x => {
if (!(!!x.bank && !!x.character)) {
return false
}
return true
}) as Array<{ bank: TricksterCharacter; character: TricksterCharacter }>
return cleanCharacterPairs
})
},
}
})
export const selectedCharacterAtom = atomWithStorage<TricksterCharacter | undefined>(
'lto_state.selected_character',
undefined,
)