|
| 1 | +/// <reference types="@dcloudio/types" /> |
| 2 | +import type { OpenapiClientAdapter } from '../lib/adapter'; |
| 3 | + |
| 4 | +/** |
| 5 | + * uni-app适配器 |
| 6 | + * ```typescript |
| 7 | + * import { OpenapiClient } from 'foca-openapi'; |
| 8 | + * import { uniappAdapter } from 'foca-openapi/adapters/uniapp'; |
| 9 | + * |
| 10 | + * const adapter = uniappAdapter({ request: uni.request, baseURL: 'http://api.com' }); |
| 11 | + * const client = new OpenapiClient(adapter); |
| 12 | + * ``` |
| 13 | + */ |
| 14 | +export const uniappAdapter = (opts: { |
| 15 | + request: typeof uni.request; |
| 16 | + /** |
| 17 | + * 包含域名的地址,每次请求前都会拼接 |
| 18 | + */ |
| 19 | + baseURL?: string; |
| 20 | + /** |
| 21 | + * 返回最终数据。默认值:`(res) => res.data` |
| 22 | + */ |
| 23 | + returningData?: (response: UniApp.RequestSuccessCallbackResult) => any; |
| 24 | + /** |
| 25 | + * uni.request()的默认参数,每次请求前都会合并对象 |
| 26 | + */ |
| 27 | + requestOptions?: UniApp.RequestOptions; |
| 28 | +}): OpenapiClientAdapter => { |
| 29 | + const { |
| 30 | + returningData = (response) => response.data, |
| 31 | + request, |
| 32 | + baseURL = '', |
| 33 | + requestOptions, |
| 34 | + } = opts; |
| 35 | + |
| 36 | + return { |
| 37 | + async request(opts, utils) { |
| 38 | + const body = utils.formatBody(opts.requestBodyType, opts.body); |
| 39 | + const credentials = |
| 40 | + opts.credentials === 'omit' || opts.credentials === false |
| 41 | + ? false |
| 42 | + : typeof opts.credentials === 'string' || opts.credentials === true |
| 43 | + ? true |
| 44 | + : undefined; |
| 45 | + |
| 46 | + const result = await request({ |
| 47 | + ...requestOptions, |
| 48 | + url: baseURL + utils.uriConcatQuery(opts.uri, opts.query), |
| 49 | + method: opts.method.toUpperCase() as any, |
| 50 | + data: body, |
| 51 | + header: { ...requestOptions?.header, ...opts.headers }, |
| 52 | + timeout: opts.timeout, |
| 53 | + withCredentials: credentials, |
| 54 | + dataType: opts.responseType === 'json' ? 'json' : undefined, |
| 55 | + responseType: opts.responseType === 'text' ? 'text' : undefined, |
| 56 | + }); |
| 57 | + |
| 58 | + return returningData(result); |
| 59 | + }, |
| 60 | + }; |
| 61 | +}; |
| 62 | + |
| 63 | +uniappAdapter(uni); |
0 commit comments