import { ICloudbase } from '@cloudbase/types' import { ICloudbaseComponent } from '@cloudbase/types/component' import { ICallFunctionOptions, ICustomReqOpts } from '@cloudbase/types/functions' import { constants } from '@cloudbase/utilities' declare const cloudbase: ICloudbase const { ERRORS } = constants const COMPONENT_NAME = 'cloudrun' class CloudbaseRun { public async callContainer(options: ICallFunctionOptions, customReqOpts?: ICustomReqOpts) { const { name, data } = options if (!name) { throw new Error(JSON.stringify({ code: ERRORS.INVALID_PARAMS, msg: `[${COMPONENT_NAME}.callContainer] invalid name`, }),) } let jsonData try { jsonData = data ? JSON.stringify(data) : '' } catch (e) { throw new Error(JSON.stringify({ code: ERRORS.INVALID_PARAMS, msg: `[${COMPONENT_NAME}.callContainer] invalid data`, }),) } return await requestContainer.call(this, { ...options, data: jsonData }, customReqOpts) } } export async function requestContainer(this: any, options: ICallFunctionOptions, customReqOpts?: ICustomReqOpts) { const { name, data, path = '', method, header = {} } = options const { BASE_URL, PROTOCOL } = this.getEndPointWithKey('GATEWAY') const endpoint = `${PROTOCOL}${BASE_URL}/cloudrun/${name}` let reqPath = path.startsWith('/') ? path : `/${path}` const isGetAndHead = ['GET', 'HEAD'].includes(method?.toUpperCase?.()) if (isGetAndHead) { try { let dataParse = {} try { dataParse = JSON.parse(data as any) } catch (error) { dataParse = data || {} } reqPath = `${reqPath}${reqPath.includes('?') ? '&' : '?'}${Object.keys(dataParse) .map(key => `${key}=${dataParse[key]}`) .join('&')}` } catch (error) { // } } // @ts-ignore const response = await this.request.fetch({ method: method || 'POST', headers: Object.assign( {}, { 'Content-Type': 'application/json; charset=utf-8', }, header, ), // Request with GET/HEAD method cannot have body ...(isGetAndHead ? {} : { body: data }), url: `${endpoint}${reqPath}`, customReqOpts, }) if (customReqOpts?.from === 'node-sdk') { return response } return await response.data } const cloudbaseRun = new CloudbaseRun() const component: ICloudbaseComponent = { name: COMPONENT_NAME, entity: { callContainer: cloudbaseRun.callContainer, }, } try { cloudbase.registerComponent(component) } catch (e) {} export function registerCloudrun(app: Pick) { try { app.registerComponent(component) } catch (e) { console.warn(e) } } try { (window as any).registerCloudrun = registerCloudrun } catch (e) {}