UNPKG

@cloudbase/app

Version:
68 lines (57 loc) 2.13 kB
import { ERRORS } from '@cloudbase/utilities/dist/cjs/constants' import { ICallApiOptions, KV } from '@cloudbase/types' import { ResponseObject } from '@cloudbase/adapter-interface' export async function callApi(callApiOptions: ICallApiOptions, opts: KV<any>): Promise<ResponseObject['data']> { const { name, body, path = '', method = 'POST', headers = {}, token } = callApiOptions || {} if (!name) { throw new Error(JSON.stringify({ code: ERRORS.INVALID_PARAMS, msg: '[apis] invalid api name', }),) } // @ts-ignore const { BASE_URL, PROTOCOL } = this.getEndPointWithKey('GATEWAY') const endpoint = `${PROTOCOL}${BASE_URL}/apis/${name}` const reqPath = path.startsWith('/') ? path : `/${path}` // @ts-ignore const response = await this.request.fetch({ url: `${endpoint}${reqPath}`, method: method || 'POST', headers: { 'Content-Type': 'application/json; charset=utf-8', ...headers, }, body, token: token?.trim?.() || headers.Authorization?.replace?.(/^Bearer /, '') || null, ...opts, }) return await response.data } const SUPPORT_METHODS = ['GET', 'POST', 'PUT', 'DELETE', 'HEAD', 'OPTIONS', 'PATCH', 'REQUEST'] export function generateCallApis(apiName: string): { [method: string]: typeof callApi} { return new Proxy({}, { get: (_, method) => { if (typeof method !== 'string') { throw new Error('[apis] method must be string') } const upMethod = method.toLocaleUpperCase() if (!SUPPORT_METHODS.includes(upMethod)) { throw new Error(`[apis] invalid method: ${method}`) } return async (callApiOptions: ICallApiOptions, opts: KV<any>) => await callApi.call(this, { name: apiName, method: (upMethod === 'REQUEST' ? callApiOptions.method : upMethod) || 'POST', ...callApiOptions, }, opts) }, }) } export function generateApis(): { [apiName: string]: typeof generateCallApis} { return new Proxy({}, { get: (_, apiName) => { if (typeof apiName === 'string') { return generateCallApis.call(this, apiName) } }, }) }