@cloudbase/app
Version:
cloudbase javascript sdk core
76 lines (65 loc) • 2.32 kB
text/typescript
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']
declare type MethodType = 'request' | 'post' | 'get' | 'head' | 'patch' | 'delete' | 'put'
export function generateCallApis(apiName: string): { [method in MethodType]: typeof callApi } {
return new Proxy({} as any, {
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]: { [method in MethodType]: typeof callApi } } {
return new Proxy(
{},
{
get: (_, apiName) => {
if (typeof apiName === 'string') {
return generateCallApis.call(this, apiName)
}
},
},
)
}