@@ -5,30 +5,43 @@ import { useCache } from '@/utils/useCache'
55
66const { wsCache } = useCache ( )
77const flagKey = 'sqlbit-assistant-flag'
8+ type Resolver < T = any > = ( value : T | PromiseLike < T > ) => void
9+ type Rejecter = ( reason ?: any ) => void
10+ interface PendingRequest < T = any > {
11+ resolve : Resolver < T >
12+ reject : Rejecter
13+ }
814interface AssistantState {
15+ id : string
916 token : string
1017 assistant : boolean
1118 flag : number
1219 type : number
1320 certificate : string
1421 online : boolean
22+ requestPromiseMap : Map < string , PendingRequest >
1523}
1624
1725export const AssistantStore = defineStore ( 'assistant' , {
1826 state : ( ) : AssistantState => {
1927 return {
28+ id : '' ,
2029 token : '' ,
2130 assistant : false ,
2231 flag : 0 ,
2332 type : 0 ,
2433 certificate : '' ,
2534 online : false ,
35+ requestPromiseMap : new Map < string , PendingRequest > ( ) ,
2636 }
2737 } ,
2838 getters : {
2939 getCertificate ( ) : string {
3040 return this . certificate
3141 } ,
42+ getId ( ) : string {
43+ return this . id
44+ } ,
3245 getToken ( ) : string {
3346 return this . token
3447 } ,
@@ -46,6 +59,43 @@ export const AssistantStore = defineStore('assistant', {
4659 } ,
4760 } ,
4861 actions : {
62+ refreshCertificate < T > ( ) {
63+ const timeout = 5000
64+ return new Promise ( ( resolve , reject ) => {
65+ const timeoutId = setTimeout ( ( ) => {
66+ this . requestPromiseMap . delete ( this . id )
67+ reject ( new Error ( `Request ${ this . id } timed out after ${ timeout } ms` ) )
68+ } , timeout )
69+ this . requestPromiseMap . set ( this . id , {
70+ resolve : ( value : T ) => {
71+ clearTimeout ( timeoutId )
72+ this . requestPromiseMap . delete ( this . id )
73+ resolve ( value )
74+ } ,
75+ reject : ( reason ) => {
76+ clearTimeout ( timeoutId )
77+ this . requestPromiseMap . delete ( this . id )
78+ reject ( reason )
79+ } ,
80+ } )
81+ const readyData = {
82+ eventName : 'sqlbot_assistant_event' ,
83+ busi : 'ready' ,
84+ ready : true ,
85+ messageId : this . id ,
86+ }
87+ window . parent . postMessage ( readyData , '*' )
88+ } )
89+ } ,
90+ resolveCertificate ( data ?: any ) {
91+ const peddingRequest = this . requestPromiseMap . get ( this . id )
92+ if ( peddingRequest ) {
93+ peddingRequest . resolve ( data )
94+ }
95+ } ,
96+ setId ( id : string ) {
97+ this . id = id
98+ } ,
4999 setCertificate ( certificate : string ) {
50100 this . certificate = certificate
51101 } ,
0 commit comments