mirror of https://github.com/nocodb/nocodb
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
69 lines
1.9 KiB
69 lines
1.9 KiB
2 years ago
|
import type { Socket } from 'socket.io-client'
|
||
|
import io from 'socket.io-client'
|
||
|
import { defineNuxtPlugin, useGlobal, watch } from '#imports'
|
||
|
|
||
|
export default defineNuxtPlugin(async (nuxtApp) => {
|
||
|
const { appInfo } = $(useGlobal())
|
||
|
|
||
|
let socket: Socket | null = null
|
||
|
|
||
|
const init = async (token: string) => {
|
||
|
try {
|
||
|
if (socket) socket.disconnect()
|
||
|
|
||
|
const url = new URL(appInfo.ncSiteUrl, window.location.href.split(/[?#]/)[0])
|
||
|
|
||
|
socket = io(`${url.href}jobs`, {
|
||
|
extraHeaders: { 'xc-auth': token },
|
||
|
})
|
||
|
|
||
|
socket.on('connect_error', (e) => {
|
||
|
console.error(e)
|
||
|
socket?.disconnect()
|
||
|
})
|
||
|
} catch {}
|
||
|
}
|
||
|
|
||
|
if (nuxtApp.$state.signedIn.value) {
|
||
|
await init(nuxtApp.$state.token.value)
|
||
|
}
|
||
|
|
||
2 years ago
|
const jobs = {
|
||
2 years ago
|
subscribe(name: string, id: string, cb: (data: any) => void) {
|
||
2 years ago
|
if (socket) {
|
||
2 years ago
|
socket.emit('subscribe', { name, id })
|
||
2 years ago
|
const tempFn = (data: any) => {
|
||
2 years ago
|
if (data.id === id && data.name === name) {
|
||
2 years ago
|
cb(data)
|
||
|
if (data.status === 'completed' || data.status === 'failed') {
|
||
|
socket?.off('status', tempFn)
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
socket.on('status', tempFn)
|
||
|
}
|
||
|
},
|
||
2 years ago
|
getStatus(name: string, id: string): Promise<string> {
|
||
2 years ago
|
return new Promise((resolve) => {
|
||
|
if (socket) {
|
||
2 years ago
|
socket.emit('status', { name, id })
|
||
2 years ago
|
const tempFn = (data: any) => {
|
||
2 years ago
|
if (data.id === id && data.name === name) {
|
||
2 years ago
|
resolve(data.status)
|
||
|
socket?.off('status', tempFn)
|
||
|
}
|
||
|
}
|
||
|
socket.on('status', tempFn)
|
||
|
}
|
||
|
})
|
||
|
},
|
||
|
}
|
||
|
|
||
|
watch((nuxtApp.$state as ReturnType<typeof useGlobal>).token, (newToken, oldToken) => {
|
||
|
if (newToken && newToken !== oldToken) init(newToken)
|
||
|
else if (!newToken) socket?.disconnect()
|
||
|
})
|
||
|
|
||
2 years ago
|
nuxtApp.provide('jobs', jobs)
|
||
2 years ago
|
})
|