utils.ts 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import { CONVERSATION_ID_INFO } from '../base/chat/constants'
  2. import { fetchAccessToken } from '@/service/share'
  3. export const checkOrSetAccessToken = async () => {
  4. const sharedToken = globalThis.location.pathname.split('/').slice(-1)[0]
  5. const accessToken = localStorage.getItem('token') || JSON.stringify({ [sharedToken]: '' })
  6. let accessTokenJson = { [sharedToken]: '' }
  7. try {
  8. accessTokenJson = JSON.parse(accessToken)
  9. }
  10. catch (e) {
  11. }
  12. if (!accessTokenJson[sharedToken]) {
  13. const res = await fetchAccessToken(sharedToken)
  14. accessTokenJson[sharedToken] = res.access_token
  15. localStorage.setItem('token', JSON.stringify(accessTokenJson))
  16. }
  17. }
  18. export const setAccessToken = async (sharedToken: string, token: string) => {
  19. const accessToken = localStorage.getItem('token') || JSON.stringify({ [sharedToken]: '' })
  20. let accessTokenJson = { [sharedToken]: '' }
  21. try {
  22. accessTokenJson = JSON.parse(accessToken)
  23. }
  24. catch (e) {
  25. }
  26. localStorage.removeItem(CONVERSATION_ID_INFO)
  27. accessTokenJson[sharedToken] = token
  28. localStorage.setItem('token', JSON.stringify(accessTokenJson))
  29. }
  30. export const removeAccessToken = () => {
  31. const sharedToken = globalThis.location.pathname.split('/').slice(-1)[0]
  32. const accessToken = localStorage.getItem('token') || JSON.stringify({ [sharedToken]: '' })
  33. let accessTokenJson = { [sharedToken]: '' }
  34. try {
  35. accessTokenJson = JSON.parse(accessToken)
  36. }
  37. catch (e) {
  38. }
  39. localStorage.removeItem(CONVERSATION_ID_INFO)
  40. delete accessTokenJson[sharedToken]
  41. localStorage.setItem('token', JSON.stringify(accessTokenJson))
  42. }