@alova/adapter-taro
TypeScript icon, indicating that this package has built-in type declarations

1.2.1 • Public • Published

@alova/adapter-taro

alova 的 taro 适配器

npm build coverage status typescript license

官网 | 核心库 alova

使用方法

创建 alova

调用 AdapterTaro 将返回请求适配器存储适配器,以及ReactHook,因此你不再需要设置这三个项,使用方法完全一致。

import { createAlova } from 'alova';
import AdapterTaro from '@alova/adapter-taro';

const alovaInst = createAlova(
  baseURL: 'https://api.alovajs.org',
  ...AdapterTaro()
);

请求

请求的使用方法与 web 环境中使用完全一致。已经完全兼容Taro.request,你可以在创建 method 实例的config中指定Taro.request支持的全部配置项

const list = () =>
  alovaInst.Get('/list', {
    // 设置的参数将传递给Taro.request
    enableHttp2: true
  });

const App = () => {
  const { loading, data } = useRequest(list);

  return (
    { loading ? <View>加载中...</View> : null }
    <View>请求数据为:{ JSON.stringify(data) }</View>
  )
};

上传

在 method 实例的config中设置requestType: 'upload'时表示上传文件,请求适配器将会调用Taro.uploadFile,上传的文件数据放在 method 实例的 data 中,你需要在 data 中指定namefilePath,这 2 个参数将传到Taro.uploadFile中,同时,你还可以在 data 中指定这 2 个参数外的其他参数,请求适配器会将它们传入到formData参数中。

同样的,已经完全兼容Taro.uploadFile,你可以在创建 method 实例的config中指定Taro.uploadFile支持的全部配置项,如果还有额外的参数需要设置,请在 method 实例的config中指定。

const uploadFile = (name, filePath, formData) =>
  alovaInst.Post(
    '/uploadImg',
    {
      name,
      filePath,

      // 额外数据将传入uni.uploadFile的formData中
      ...formData
    },
    {
      // 设置请求方式为上传,适配器内将调用uni.uploadFile
      requestType: 'upload',

      // 开启上传进度
      enableUpload: true
    }
  );

const App = () => {
  const { loading, data, uploading, send } = useRequest(uploadFile, {
    immediate: false
  });

  const handleImageChoose = () => {
    Taro.chooseImage({
      success: chooseImageRes => {
        const tempFilePaths = chooseImageRes.tempFilePaths;
        send('fileName', tempFilePaths[0], {
          extra1: 'a',
          extra2: 'b'
        });
      }
    });
  };

  return (
    { loading ? <View>上传中...</View> : null }
    <View>上传进度:{ uploading.loaded }/{ uploading.total }</View>
    <Button onClick={handleImageChoose}>上传图片</Button>
    {/* ... */}
  )
}

下载

在 method 实例的config中设置requestType: 'download'时表示下载文件,请求适配器将会调用Taro.downloadFile

同样的,已经完全兼容Taro.downloadFile,你可以在创建 method 实例的config中指定Taro.downloadFile支持的全部配置项,如果还有额外的参数需要设置,请在 method 实例的config中指定。

const downloadFile = filePath =>
  alovaInst.Get('/bigImage.jpg', {
    // 设置请求方式为下载,适配器内将调用uni.downloadFile
    requestType: 'download',
    filePath,

    // 开启下载进度
    enableDownload: true
  });

const App = () => {
  const { loading, data, downloading, send } = useRequest(downloadFile, {
    immediate: false
  });
  const handleImageDownload = () => {
    send('file_save_path');
  };

  return (
    { loading ? <View>下载中...</View> : null }
    <View>下载进度:{ downloading.loaded }/{ downloading.total }</View>
    <Button onClick={handleImageDownload}>下载图片</Button>
    {/* ... */}
  );
}

模拟请求适配器兼容

在使用 Taro 开发应用时,我们仍然可能需要用到模拟请求,只是默认情况下,模拟请求适配器(@alova/mock)的响应数据是一个Response实例,即默认兼容GlobalFetch请求适配器,当在 Taro 环境下使用时,我们需要让模拟请求适配器的响应数据是兼容 Taro 适配器的,因此你需要使用**@alova/adapter-taro**包中导出的taroMockResponse作为响应适配器。

import { defineMock, createAlovaMockAdapter } from '@alova/mock';
import AdapterTaro, { taroRequestAdapter, taroMockResponse } from '@alova/adapter-taro';

const mocks = defineMock({
	// ...
});

// 模拟数据请求适配器
export default createAlovaMockAdapter([mocks], {
	// 指定taro请求适配器后,未匹配模拟接口的请求将使用这个适配器发送请求
	httpAdapter: taroRequestAdapter,

	//  模拟响应适配器,指定后响应数据将转换为taro兼容的数据格式
	onMockResponse: taroMockResponse
});

export const alovaInst = createAlova({
	baseURL: 'https://api.alovajs.org',
	timeout: 5000,
	...AdapterTaro({
		// 通过环境变量控制是否使用模拟请求适配器
		mockRequest: process.env.NODE_ENV === 'development' ? mockAdapter : undefined
	})
	// ...
});

Package Sidebar

Install

npm i @alova/adapter-taro

Homepage

alova.js.org

Weekly Downloads

13

Version

1.2.1

License

MIT

Unpacked Size

40.5 kB

Total Files

11

Last publish

Collaborators

  • zz4780452