import Fly from 'flyio/dist/npm/fly' import EventEmitter from './event-emitter' import sign from './sign.js' const http: any = new Fly() http.interceptors.response.use( (response: any) => response.data, (error: any) => error, ) interface Config { mode: 'cloud' | 'local' clientSecret: string spaceId: string imagePrefix: string imagesUpload: string localIp?: string interceptResponse?: (e: never) => never } type Intercept = 'response' | 'request' class uniCloudSimple { // 密钥 clientSecret?: string // 云空间ID spaceId?: string // 图片前缀 imagePrefix?: string // 上次图片路径 imagesUpload?: string // 本地IP localIp?: string = 'http://127.0.0.1:7000' // 远程IP remoteIp?: string = 'https://api.next.bspapp.com' // 签名 signature?: (data: any) => string // 凭证 token?: string // 凭证过期时间 tokenExpired?: number // 模式 mode?: 'cloud' | 'local' // 是否正在获取凭证 getTokenLoading?: boolean // 事件订阅 emitter = new EventEmitter() // 劫持响应 interceptResponse: (e: any) => any = (e) => e // 劫持请求 interceptRequest: (e: any) => any = (e) => e init(args: Config): void { Object.entries(args).forEach(([key, value]) => { Object.assign(this, { [key]: value }) }) // 生成签名 this.signature = sign(args.clientSecret) if (this.mode === 'cloud') this.createToken().then() } // 创建凭证 async createToken() { if (this.getTokenLoading) { await (() => new Promise((resolve) => { this.emitter.on('getTokenLoading', resolve) }))() return } this.getTokenLoading = true const data = { method: 'serverless.auth.user.anonymousAuthorize', params: '{}', spaceId: this.spaceId, timestamp: new Date().getTime(), } const { data: result, success } = await http.post('https://api.next.bspapp.com/client', data, { headers: { 'X-Serverless-Sign': this.signature?.(data) }, }) if (success === true) { this.token = result.accessToken this.getTokenLoading = false this.emitter.emit('getTokenLoading') } } // 请求云对象 importObject(name: string): any { return new Proxy( {}, { get: (target, property: any) => { return async (...args: never[]) => { try { const object = this.interceptRequest({ name, property, args }) const result = await this[this.mode === 'cloud' ? 'cloudObject' : 'localObject']( object.name, object.property, object.args, ) return this.interceptResponse(result) } catch (e: any) { throw new Error(this.interceptResponse?.(e.message)) } } }, }, ) } // 云端对象处理 async cloudObject(name: string, method: string, args: any[]) { if (this.getTokenLoading) { await (() => new Promise((resolve) => { this.emitter.on('getTokenLoading', resolve) }))() } const data = { method: 'serverless.function.runtime.invoke', params: JSON.stringify({ functionTarget: name, functionArgs: { clientInfo: { token: this.token }, method, params: args, }, }), spaceId: this.spaceId, timestamp: new Date().getTime(), token: this.token, } let result = await http.post(`${this.remoteIp}/client`, data, { headers: { 'x-Basement-Token': this.token, 'X-Serverless-Sign': this.signature?.(data), }, }) const { error, success } = result if (success === false) { // 过期 if (error.message === 'session_expired') { // 凭证过期 await this.createToken() result = await this.cloudObject(name, method, args) } // 报错 else { throw new Error(JSON.stringify(error)) } } return result } // 本地端对象处理 async localObject(name: string, method: string, args: never[]) { try { const res = await http.post(`${this.localIp}/cloudfunctions/${name}`, { param: { clientInfo: { token: this.token }, method, params: args, }, platform: 'web', provider: 'aliyun', }) return { data: res, success: true, headers: {}, } } catch (e: any) { const { data: error } = e.response throw new Error(JSON.stringify(error)) } } // 上传图片 async uploadImage(file: File) { const data = { method: 'serverless.file.resource.generateProximalSign', params: JSON.stringify({ env: 'public', filename: file.name }), spaceId: this.spaceId, timestamp: new Date().getTime(), token: this.token, } const { data: res, success } = await http.post(`${this.remoteIp}/client`, data, { headers: { 'x-Basement-Token': this.token, 'X-Serverless-Sign': this.signature?.(data), }, }) if (!success) throw new Error('获取云存储上传凭证报错') // 构造云存储参数 const cloudPrams = { 'Cache-Control': 'max-age=2592000', 'Content-Disposition:': 'attachment', OSSAccessKeyId: res.accessKeyId, Signature: res.signature, host: res.host, id: res.id, key: res.ossPath, policy: res.policy, success_action_status: 200, 'x-oss-security-token': res.securityToken, callback: window.btoa( JSON.stringify({ callbackUrl: res.ossCallbackUrl, callbackBody: JSON.stringify({ fileId: res.id, spaceId: this.spaceId, }), callbackBodyType: 'application/json', }), ), } const formData = new FormData() Object.entries(cloudPrams).forEach(([field, value]) => { formData.append(field, value) }) formData.append('file', file) const uRes = await http.post(this.imagesUpload, formData, { headers: { 'X-Oss-Server-Side-Encrpytion': 'AES256', Accept: '*/*', 'Sec-Ch-Ua-Mobile': '?1', 'Sec-Ch-Ua-Platform': 'Android', }, }) if (!uRes.success) throw new Error('图片上传报错') return res.ossPath } // 绑定响应拦截 interceptors(intercept: Intercept, callback: (response: any) => any) { const func = intercept === 'response' ? 'interceptResponse' : 'interceptRequest' this[func] = callback } } const instance = new uniCloudSimple() export { // 构造器 uniCloudSimple as CreateUniCloudSimple, // 实例 instance as default, }