{"id":18832269,"url":"https://github.com/tuax/tua-api","last_synced_at":"2025-04-14T04:23:58.099Z","repository":{"id":52437818,"uuid":"150717224","full_name":"tuax/tua-api","owner":"tuax","description":"🏗 一款可配置的通用 api 请求函数生成工具(A common tool helps converting configs to api functions)","archived":false,"fork":false,"pushed_at":"2022-02-25T02:39:25.000Z","size":1235,"stargazers_count":35,"open_issues_count":3,"forks_count":4,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-03-27T18:21:20.389Z","etag":null,"topics":["api","api-configuration","axios","jsonp","tua-api"],"latest_commit_sha":null,"homepage":"https://tuax.github.io/tua-api/","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/tuax.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2018-09-28T09:28:45.000Z","updated_at":"2023-12-26T15:34:08.000Z","dependencies_parsed_at":"2022-08-18T03:05:43.549Z","dependency_job_id":null,"html_url":"https://github.com/tuax/tua-api","commit_stats":null,"previous_names":["tuateam/tua-api"],"tags_count":31,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tuax%2Ftua-api","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tuax%2Ftua-api/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tuax%2Ftua-api/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tuax%2Ftua-api/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/tuax","download_url":"https://codeload.github.com/tuax/tua-api/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248820077,"owners_count":21166597,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["api","api-configuration","axios","jsonp","tua-api"],"created_at":"2024-11-08T01:57:19.913Z","updated_at":"2025-04-14T04:23:58.070Z","avatar_url":"https://github.com/tuax.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"\u003ch1 align=\"center\"\u003etua-api\u003c/h1\u003e\n\n\u003ch4 align=\"center\"\u003e让我们优雅地调用 api~\u003c/h4\u003e\n\n\u003cp align=\"center\"\u003e\n    \u003ca href=\"https://tuateam.github.io/tua-api/\"\u003e👉完整文档地址点这里👈\u003c/a\u003e\n\u003c/p\u003e\n\n\u003cp align=\"center\"\u003e\n    \u003ca href=\"https://circleci.com/gh/tuateam/tua-api/tree/master\" target=\"_blank\"\u003e\n        \u003cimg src=\"https://img.shields.io/circleci/project/github/tuateam/tua-api/master.svg\" alt=\"Build Status\"\u003e\n    \u003c/a\u003e\n    \u003ca href=\"https://codecov.io/github/tuateam/tua-api?branch=master\" target=\"_blank\"\u003e\n        \u003cimg src=\"https://img.shields.io/codecov/c/github/tuateam/tua-api/master.svg\" alt=\"Coverage Status\"\u003e\n    \u003c/a\u003e\n    \u003ca href=\"https://david-dm.org/tuateam/tua-api\" target=\"_blank\"\u003e\n        \u003cimg src=\"https://david-dm.org/tuateam/tua-api.svg\" alt=\"dependencies\"\u003e\n    \u003c/a\u003e\n    \u003ca href=\"https://www.npmjs.com/package/tua-api\" target=\"_blank\"\u003e\n        \u003cimg src=\"https://badgen.net/npm/dm/tua-api\" alt=\"Downloads per month\"\u003e\n        \u003cimg src=\"https://img.shields.io/npm/v/tua-api.svg\" alt=\"Version\"\u003e\n        \u003cimg src=\"https://img.shields.io/npm/v/tua-api/next.svg\" alt=\"Next Version\"\u003e\n        \u003cimg src=\"https://img.shields.io/npm/l/tua-api.svg\" alt=\"License\"\u003e\n    \u003c/a\u003e\n\u003c/p\u003e\n\n## `tua-api` 是什么？\n`tua-api` 是一个针对发起 api 请求提供辅助功能的库。采用 ES6+ 语法，并采用 jest 进行了完整的单元测试。\n\n目前已适配：\n\n* web 端：axios, fetch-jsonp\n* Node 端：axios\n* 小程序端：wx.request\n\n\u003ca href=\"https://codesandbox.io/s/2o24xn0750\" target=\"_blank\"\u003e\n    \u003cimg alt=\"Edit tua-api github example\" src=\"https://codesandbox.io/static/img/play-codesandbox.svg\"\u003e\n\u003c/a\u003e\n\n## 安装\n### web 端\n#### 安装本体\n\n```bash\n$ npm i -S tua-api\n# OR\n$ yarn add tua-api\n```\n\n然后直接导入即可\n\n```js\nimport TuaApi from 'tua-api'\n```\n\n#### 配置武器\n配置“武器”分为两种情况:\n\n* [已配置 CORS 跨域请求头](https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Access_control_CORS)，或是没有跨域需求时，无需任何操作（默认采用的就是 `axios`）。\n\n* 若是用不了 CORS，那么就需要设置 `reqType: 'jsonp'` 借助 jsonp 实现跨域\n\n但是 jsonp 只支持使用 get 的方式请求，所以如果需要发送 post 或其他方式的请求，还是需要使用 `axios`（服务端还是需要配置 CORS）。\n\n### 小程序端\n#### 安装本体即可\n\n```bash\n$ npm i -S tua-api\n# OR\n$ yarn add tua-api\n```\n\n```js\nimport TuaApi from 'tua-api'\n```\n\n\u003e 小程序还用不了 npm？[@tua-mp/service](https://tuateam.github.io/tua-mp/tua-mp-service/) 了解一下？\n\n## `tua-api` 能干什么？\n`tua-api` 能实现统一管理 api 配置（例如一般放在 `src/apis/` 下）。经过处理后，业务侧代码只需要这样写即可：\n\n```js\nimport { fooApi } from '@/apis/'\n\nfooApi\n    .bar({ a: '1', b: '2' }) // 发起请求，a、b 是请求参数\n    .then(console.log)       // 收到响应\n    .catch(console.error)    // 处理错误\n```\n\n不仅如此，还有一些其他功能：\n\n* 参数校验\n* 默认参数\n* 中间件（koa 风格）\n* ...\n\n```js\n// 甚至可以更进一步和 tua-storage 配合使用\nimport TuaStorage from 'tua-storage'\nimport { getSyncFnMapByApis } from 'tua-api'\n\n// 本地写好的各种接口配置\nimport * as apis from '@/apis'\n\nconst tuaStorage = new TuaStorage({\n    syncFnMap: getSyncFnMapByApis(apis),\n})\n\nconst fetchParam = {\n    key: fooApi.bar.key,\n    syncParams: { a: 'a', b: 'b' },\n\n    // 过期时间，默认值为实例化时的值，以秒为单位\n    expires: 10,\n\n    // 是否直接调用同步函数更新数据，默认为 false\n    // 适用于需要强制更新数据的场景，例如小程序中的下拉刷新\n    isForceUpdate: true,\n\n    // ...\n}\n\ntuaStorage\n    .load(fetchParam)\n    .then(console.log)\n    .catch(console.error)\n```\n\n## 怎么写 `api` 配置？\n拿以下 api 地址举例：\n\n* `https://example-base.com/foo/bar/something/create`\n* `https://example-base.com/foo/bar/something/modify`\n* `https://example-base.com/foo/bar/something/delete`\n\n### 地址结构划分\n以上地址，一般将其分为`3`部分：\n\n* baseUrl: `'https://example-base.com/foo/bar'`\n* prefix: `'something'`\n* pathList: `[ 'create', 'modify', 'delete' ]`\n\n### 文件结构\n`api/` 一般是这样的文件结构：\n\n```\n.\n└── apis\n    ├── prefix-1.js\n    ├── prefix-2.js\n    ├── something.js // \u003c-- 以上的 api 地址会放在这里，名字随意\n    └── index.js\n```\n\n### 基础配置内容\n```js\n// src/apis/something.js\n\nexport default {\n    // 接口基础地址\n    baseUrl: 'https://example-base.com/foo/bar',\n\n    // 接口的中间路径\n    prefix: 'something',\n\n    // 接口地址数组\n    pathList: [\n        { path: 'create' },\n        { path: 'modify' },\n        { path: 'delete' },\n    ],\n}\n```\n\n[更多配置请点击这里查看](https://tuateam.github.io/tua-api/config/common.html)\n\n### 配置导出\n最后来看一下 `apis/index.js` 该怎么写：\n\n```js\nimport TuaApi from 'tua-api'\n\n// 初始化\nconst tuaApi = new TuaApi({ ... })\n\n// 使用中间件\ntuaApi\n    .use(async (ctx, next) =\u003e {\n        // 请求发起前\n        console.log('before: ', ctx)\n\n        await next()\n\n        // 响应返回后\n        console.log('after: ', ctx)\n    })\n    // 链式调用\n    .use(...)\n\nexport const fakeGet = tuaApi.getApi(require('./fake-get').default)\nexport const fakePost = tuaApi.getApi(require('./fake-post').default)\n```\n\n小程序端建议使用 [@tua-mp/cli](https://tuateam.github.io/tua-mp/tua-mp-cli/) 一键生成 api。\n\n```bash\n$ tuamp add api \u003capi-name\u003e\n```\n\n### 配置的构成\n在 `tua-api` 中配置分为四种：\n\n* [默认配置（调用 `new TuaApi({ ... })` 时传递的）](https://tuateam.github.io/tua-api/config/default.html)\n* [公共配置（和 `pathList` 同级的配置）](https://tuateam.github.io/tua-api/config/common.html)\n* [自身配置（`pathList` 数组中的对象上的配置）](https://tuateam.github.io/tua-api/config/self.html)\n* [运行配置（在实际调用接口时传递的配置）](https://tuateam.github.io/tua-api/config/runtime.html)\n\n其中优先级自然是:\n\n`默认配置 \u003c 公共配置 \u003c 自身配置 \u003c 运行配置`\n\n\u003cp align=\"center\"\u003e\n    \u003ca href=\"https://tuateam.github.io/tua-api/config/\"\u003e👉更多配置点击这里👈\u003c/a\u003e\n\u003c/p\u003e\n\n## Contributors ✨\n\nThanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)):\n\n\u003c!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section --\u003e\n\u003c!-- prettier-ignore-start --\u003e\n\u003c!-- markdownlint-disable --\u003e\n\u003ctable\u003e\n  \u003ctr\u003e\n    \u003ctd align=\"center\"\u003e\u003ca href=\"https://buptsteve.github.io\"\u003e\u003cimg src=\"https://avatars2.githubusercontent.com/u/11501493?v=4\" width=\"100px;\" alt=\"StEve Young\"/\u003e\u003cbr /\u003e\u003csub\u003e\u003cb\u003eStEve Young\u003c/b\u003e\u003c/sub\u003e\u003c/a\u003e\u003cbr /\u003e\u003ca href=\"https://github.com/tuateam/tua-api/commits?author=BuptStEve\" title=\"Code\"\u003e💻\u003c/a\u003e \u003ca href=\"https://github.com/tuateam/tua-api/commits?author=BuptStEve\" title=\"Documentation\"\u003e📖\u003c/a\u003e \u003ca href=\"#infra-BuptStEve\" title=\"Infrastructure (Hosting, Build-Tools, etc)\"\u003e🚇\u003c/a\u003e\u003c/td\u003e\n    \u003ctd align=\"center\"\u003e\u003ca href=\"https://github.com/evinma\"\u003e\u003cimg src=\"https://avatars2.githubusercontent.com/u/16096567?v=4\" width=\"100px;\" alt=\"evinma\"/\u003e\u003cbr /\u003e\u003csub\u003e\u003cb\u003eevinma\u003c/b\u003e\u003c/sub\u003e\u003c/a\u003e\u003cbr /\u003e\u003ca href=\"https://github.com/tuateam/tua-api/commits?author=evinma\" title=\"Code\"\u003e💻\u003c/a\u003e\u003c/td\u003e\n  \u003c/tr\u003e\n\u003c/table\u003e\n\n\u003c!-- markdownlint-enable --\u003e\n\u003c!-- prettier-ignore-end --\u003e\n\u003c!-- ALL-CONTRIBUTORS-LIST:END --\u003e\n\nThis project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind welcome!\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftuax%2Ftua-api","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ftuax%2Ftua-api","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftuax%2Ftua-api/lists"}