{"id":19974413,"url":"https://github.com/alanchenchen/apimodule","last_synced_at":"2025-07-01T01:38:34.041Z","repository":{"id":32774969,"uuid":"142230221","full_name":"alanchenchen/ApiModule","owner":"alanchenchen","description":"A solution to use axios with configs separated to modules","archived":false,"fork":false,"pushed_at":"2023-03-06T12:28:09.000Z","size":774,"stargazers_count":15,"open_issues_count":10,"forks_count":1,"subscribers_count":1,"default_branch":"master","last_synced_at":"2024-11-11T01:42:31.494Z","etag":null,"topics":["api","axios","config","dynamicrouter","modules"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/alanchenchen.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-07-25T01:18:16.000Z","updated_at":"2022-09-05T10:08:47.000Z","dependencies_parsed_at":"2023-01-14T22:11:36.604Z","dependency_job_id":null,"html_url":"https://github.com/alanchenchen/ApiModule","commit_stats":null,"previous_names":[],"tags_count":4,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/alanchenchen%2FApiModule","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/alanchenchen%2FApiModule/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/alanchenchen%2FApiModule/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/alanchenchen%2FApiModule/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/alanchenchen","download_url":"https://codeload.github.com/alanchenchen/ApiModule/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":224379845,"owners_count":17301525,"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","axios","config","dynamicrouter","modules"],"created_at":"2024-11-13T03:14:57.304Z","updated_at":"2024-11-13T03:14:57.439Z","avatar_url":"https://github.com/alanchenchen.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# ApiModule\n\n![](https://img.shields.io/npm/v/api-module.svg)\n![](https://img.shields.io/npm/dt/api-module.svg)\n[![LICENSE](https://img.shields.io/badge/license-Anti%20996-blue.svg)](https://github.com/996icu/996.ICU/blob/master/LICENSE)\n\n\u003e 基于axios二次封装，为了解决RESTFUL接口冗余问题的一种前端工程化尝试\n\n\u003e version:  1.0.0\n\n\u003e lastDate: 2021/10/03\n\n\u003e Author:  Alan Chen\n\n## Features\n1. 以axios作为基础库，完全基于axios的api使用方法。\n2. 模块化管理各个RESTFUL接口的配置。\n3. 预先提供全局配置，也可以在每个RESTFUL接口具体配置，出现重复配置时以具体接口配置优先处理。\n4. 统一请求参数的格式，支持请求后台动态路由，支持多个路由参数动态传入。`任何请求方式都支持动态路由参数!`\n5. 每个接口除了data以外，支持axios的config所有配置。新增一个dynamicRouter配置项作为是否启用动态路由接口的标识。\n\n## Why\n* 在开发前端页面过程中，势必会因为一堆RESTFUL接口的管理带来麻烦，举个例子，目前一个项目已经存在30个接口，如果需要更改a接口的timeout或者method，大家肯定会直接去具体的api调用函数里更改，但是假设api函数所在页面的代码量过于多，定位到准确位置怕是会耗费不少时间。\n* 目前axios使用大概分成两种：\n    1. 直接使用`axios.get(url, configs)`或者`axios.post(url, data, configs)`这类方法，这样会存在很大的问题，给具体接口配置request headers和timeout会非常麻烦\n    2. 使用`axios(url, confings)`或者`axios.defaults`搭配`axios.create(configs)`来预设全局配置，这种比第一种要好很多，但是还是会遇到具体接口配置的问题\n### ApiModule是怎么做的\nApiModule是在第二种使用方法上进行优化，在`new ApiModule(configs)`的同时会调用`axios(url, configs)`生成一个全局配置后的axios方法。然后所有的具体接口会写在另外一个模块里，每个接口都可以配置自己的request headers和timeout等等。导入接口模块后，再调用实例的`createApi()`方法，就会返回一个函数，只需要在需要请求接口的地方调用该函数即可。对具体接口所有的配置，与该函数无关，只在接口模块里进行修改即可。\n\n## Installatiom\n1. npm安装 \n```js\n    npm install api-module axios --save\n```\n2. yarn安装 \n```js \n    yarn add api-module axios\n```\n\n## Usage Help\n1. npm包默认导出ApiModule核心类。命名导出CONSTANT，是插件内部的所有常量，可以用来配置。\n2. ApiModule构造函数必选一个参数，可选两个参数，参数一是axios方法，参数二是对象globalConfig，作为接口的全局配置传入。参数三是对象preConfigs，目前支持一个dynamicRouterPattern的key，用作动态路由的占位符规则。。格式如下：\n    ```js\n    import axios from \"axios\";\n    import ApiModule, { CONSTANT } from \"api-module\";\n\n    new ApiModule(\n        axios,\n        // 与axios的原有config完全一致\n        {\n            baseURL: 'http://127.0.0.1:7070',\n            timeout: 5000\n        },\n        {\n            dynamicRouterPattern: `:${CONSTANT.DYNAMICROUTER_PATTERN_FLAG}` // 插件的动态路由url参数默认以：开头\n        }\n    );\n    ```\n3. ApiModule实例有4个方法：\n    * registerModule({name, module})，注册模块作用域config。name为string，module格式与config一致，均必选。如果调用了该方法，则表示module内的config存入自己模块的作用域内，这样就避免了命名冲突。函数返回ApiModule实例。支持链式调用。\n    * registerGlobal(config)，注册全局作用域cofnig。config格式与globalConfig一致，可选，如果传入了config，则当前config会存入插件的全局作用域。支持链式调用。\n    * setHeader(headers)，更新全局配置的请求头，更新后，所有的请求都会合并新的全局请求头信息。参数最多有两个，当只有一个参数时，必须为Object，当有两个参数时，参数一是key，参数二是value。函数返回ApiModule实例，setHeader支持链式调用。\n    * request(config)，发出请求，返回axios的结果。config是个对象，格式如下：\n        * url `[String]`，必选，config中的key名，不是config中的url\n        * data `[Object]`，可选，axios的data参数，作为请求头query或请求体\n        * dynamicRouterParams `[Object]`，可选，当config中dynamicRouter为true时必选。动态路由的参数，插件为了更好的使用动态路由，提供了路由参数选项。格式见下文\n        * module `[String]`，可选，指定使用哪个模块的config\n5. 使用如下：\n    * api.js\n    ``` javascript\n        // 必选要导入axios\n        import axios from \"axios\";\n        import ApiModule from \"api-module\";\n         //导入全局作用域接口\n        import { apiConfig, globalConfig } from \"config\";\n         //导入模块作用域接口\n        import moduleA from \"moduleA\";\n         //导入模块作用域接口\n        import moduleB from \"moduleB\";\n\n        const api = new ApiModule(axios, globalConfig);\n        api.registerModule({name: 'A', module: moduleA})\n           .registerModule({name: 'B', module: moduleB})\n           .registerGlobal(apiConfig);\n        //导出api函数\n        export default api.request;\n    ```\n    * 业务模块，例如 login.js。直接使用api({url, data, dynamicRouterParams}即可)\n    ``` javascript\n         //get请求无参数\n        api({\n            url: 'login',\n        })\n        .then(res =\u003e {\n            console.log(res)\n        })\n        .catch(err =\u003e {\n            console.log(err)\n        })\n\n        //get请求有参数\n        api({\n            url: 'login',\n            data: { username: 'alan' } //参数直接以对象传入,已对axios做过处理，不需要加入params的key。无参数可以不填\n        })\n        .then(res =\u003e {\n            console.log(res)\n        })\n        .catch(err =\u003e {\n            console.log(err)\n        })\n\n        //PUT请求，且是动态路由接口。最终的url路径为'sign/logout/name/alan/date/2018-12-4',请求体是{username: 'alan'},格式为form表单编码\n        api({\n            url: 'logout',\n            data: { username: 'alan' }, //参数直接以对象传入。无参数可以不填\n            dynamicRouterParams: { name: 'alan', date: '2018-12-4' } //路由参数必须是Object类型，不能忽略参数，否则会抛出异常\n        })\n        .then(res =\u003e {\n            console.log(res)\n        })\n        .catch(err =\u003e {\n            console.log(err)\n        })\n            \n        //POST请求有参数\n        api({\n            url: 'setRoleAccess',\n            data: { username: 'alan', access: 'admin' } //参数直接以对象传入。无参数可以不填\n        })\n        .then(res =\u003e {\n            console.log(res)\n        })\n        .catch(err =\u003e {\n            console.log(err)\n        })\n    ```\n\n6. 插件使用axios自带的拦截器功能。\n```javascript\n    import axios from \"axios\";\n\n    // 原生axios的拦截器\n    axios.interceptors.request.use(function (config) {\n        // 在发送请求之前做些什么\n        console.log('你被拦截啦！！')\n        return config\n    }, function (error) {\n        // 对请求错误做些什么\n        return Promise.reject(error)\n    })\n```\n\n## Example\n[example](./example/client.ts)\n\n\n## Attentions\n\n1. 插件本身预设了几个配置项，如果不做任何设置，默认是get请求，Content-Type默认是application/x-www-form-urlencoded编码。\n2. 使用此插件可以最大程度解耦RESTFUL接口和具体业务，开发者只需要用接口地址别名请求，而需要更改接口配置时，不用知道在哪个页面调用了此接口，只需要将注意点放在apiConfig。\n3. 此插件可以在任何框架中使用，必须安装axios，在vue框架内使用时，如果觉得在每个组件内引入api模块比繁琐，可以在`main.js`导入，然后挂载在`vue.prototype`上。\n4. 至于插件接口的配置项，直接去看axios文档，与axios函数的第二个参数config完全一致。\n5. 构造器函数的第二参数dynamicRouterPattern支持自定义占位符重写，但是必须是字符串，而且必须要包含`CONSTANT.DYNAMICROUTER_PATTERN_FLAG`。比如： `{CONSTANT.DYNAMICROUTER_PATTERN_FLAG}`、`@CONSTANT.DYNAMICROUTER_PATTERN_FLAG`。注意字符串内不允许出现正则表达式的特定符号，比如$、^等。\n\n## license\n* Anti 996(996.ICU)","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Falanchenchen%2Fapimodule","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Falanchenchen%2Fapimodule","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Falanchenchen%2Fapimodule/lists"}