UNPKG

@cloudbase/model

Version:
108 lines (88 loc) 2.88 kB
import { ICloudbase } from '@cloudbase/types' import { ICloudbaseComponent } from '@cloudbase/types/component' import { generateHTTPClient } from '@cloudbase/wx-cloud-client-sdk' import { events } from '@cloudbase/utilities' const { CloudbaseEventEmitter } = events declare const cloudbase: ICloudbase type IFetchOptions = Parameters<ICloudbase['request']['fetch']>[0] const COMPONENT_NAME = 'models' function getEntity(cloudbase: any) { const callFunction = cloudbase.callFunction.bind(cloudbase) const cloudbaseFetch = cloudbase.request.fetch.bind(cloudbase.request) const fetch = async (fetchOptions: IFetchOptions) => { const res = await cloudbaseFetch({ ...fetchOptions, headers: { 'Content-Type': 'application/json', ...fetchOptions.headers, }, }) return await res.data } const { BASE_URL, PROTOCOL } = cloudbase.getEndPointWithKey('GATEWAY') as { BASE_URL: string PROTOCOL: string } const baseUrl = `${PROTOCOL}${BASE_URL}/model` const sqlBaseUrl = `${PROTOCOL}${BASE_URL}/sql` const entity = generateHTTPClient(callFunction, fetch, baseUrl, { sqlBaseUrl }) return entity } const cloudbaseModelMap = new WeakMap() /** * 创建 models entity 时,需要 baseUrl、fetch,而这两个参数都需要在 cloudbase.init 之后才能获取。 * 因此需要在 cloudbase.init 之后执行。 * 此函数将创建 entity 的步骤延后到第一次读取 models 上的属性时执行。 */ export function lazyGetEntity(cloudbase: ICloudbase): ReturnType<typeof getEntity> { return new Proxy( {}, { get: (_, prop: string) => { const { BASE_URL, PROTOCOL } = cloudbase.getEndPointWithKey('GATEWAY') const key = { ...cloudbase, BASE_URL, PROTOCOL } let entity = cloudbaseModelMap.get(key) if (!entity) { entity = getEntity(cloudbase) cloudbaseModelMap.set(key, entity) } return entity[prop] }, }, ) } const CLOUDBASE_INIT_EVENT = 'cloudbase_init' const bus = new CloudbaseEventEmitter() bus.on(CLOUDBASE_INIT_EVENT, ({ data: cloudbase }: { data: ICloudbase }) => { Object.assign(cloudbase, { models: lazyGetEntity(cloudbase) }) }) const component: ICloudbaseComponent = { name: COMPONENT_NAME, namespace: COMPONENT_NAME, entity: new Proxy( {}, { get: (_, prop: string) => { console.warn(`【deprecated】Accessing Cloudbase.prototype.models.${prop}.`) }, }, ), injectEvents: { bus, events: [CLOUDBASE_INIT_EVENT], }, } try { cloudbase.registerComponent(component) } catch (e) {} export function registerModel(app: ICloudbase) { try { app.registerComponent(component) } catch (e) { console.warn(e) } } try { (window as any).registerModel = registerModel } catch (e) {} export * from '@cloudbase/wx-cloud-client-sdk'