{"id":17880601,"url":"https://github.com/a7650/wx-axios-graphql","last_synced_at":"2025-03-22T08:31:01.556Z","repository":{"id":57400358,"uuid":"264618836","full_name":"a7650/wx-axios-graphql","owner":"a7650","description":"微信小程序上的axios和graphQL","archived":false,"fork":false,"pushed_at":"2020-09-10T06:02:58.000Z","size":25,"stargazers_count":5,"open_issues_count":0,"forks_count":3,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-03-18T10:01:38.131Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/a7650.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2020-05-17T08:44:31.000Z","updated_at":"2022-04-27T07:05:34.000Z","dependencies_parsed_at":"2022-09-05T03:42:03.952Z","dependency_job_id":null,"html_url":"https://github.com/a7650/wx-axios-graphql","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/a7650%2Fwx-axios-graphql","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/a7650%2Fwx-axios-graphql/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/a7650%2Fwx-axios-graphql/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/a7650%2Fwx-axios-graphql/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/a7650","download_url":"https://codeload.github.com/a7650/wx-axios-graphql/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":244931457,"owners_count":20534007,"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":[],"created_at":"2024-10-28T12:26:27.593Z","updated_at":"2025-03-22T08:31:01.245Z","avatar_url":"https://github.com/a7650.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# 🛸wx-axios-graphql\n### 可以在微信小程序上使用的axios，同时支持graphQL\n\n[npm v1.1.2][npm-url] \u0026emsp; [git地址][git-url]\n\n\n[npm-url]: https://www.npmjs.com/package/wx-axios-graphql\n[git-url]: https://github.com/a7650/wx-axios-graphql.git\n\n### 如果该项目对你有用的话，麻烦在git上点个star⭐，我将会有更多动力去维护\n### 如果你在使用过程碰到了问题或者bug，欢迎在issue里提\n\n## 使用方法\n\n### 安装\n\n`npm install wx-axios-graphql`\n\n或者把request文件拷贝下来，放在你的项目中，然后`import request from \"./request/index.js\"`\n\n\n### 用法\n\n该js库是对微信上的wx.request的封装，参考axios的功能和语法，同时加入了graphQL的支持\n\n#### 1: axios部分\n\n支持以下请求语法\n\n```\n//和axios语法保持一致\n\nget(url, config)\n\npost(url, data, config)\n\nput(url, data, config)\n\ndelete(url, config)\n\nhead(url, config)\n\noptions(url, config) \n\npatch(url, data, config)\n```\n\n还支持以下扩展功能\n\n（1）配置defaults\n\n配置可通过`request.defaults[propertyName]`配置，propertyName有以下几项\n\n```\nconst defaults = {\n\tmethod: 'GET', // 配置默认的请求方法，大写\n\n\ttimeout: 0, // 请求超时时间 ms\n\n\theaders: { // 默认的请求头\n\t\tcommon: {\n\t\t\tAccept: 'application/json, text/plain, */*'\n\t\t}\n\t},\n\n\tbaseURL: \"\", // baseURL\n\n\tauth: null, // {null | String | Function} // 配置Authorization请求头的value,function类型时需要返回一个字符串\n\n\tauthKey: \"Authorization\", // 配置Authorization请求头的key\n\n\tauthURL: {\n\t\tinclusive: null, // 如果配置了inclusive数组，则只有inclusive中包含的url才会被添加auth\n\t\texclusive: null // exclusive中包含的url不会被添加auth\n\t} // {null | String[]} \n}\n```\n\n（2）请求拦截器和响应拦截器\n\n使用方式和axios一样\n\n```\n//以下是请求和响应拦截器简单的配置\n\nrequest.interceptors.request.use(\n    res =\u003e {\n        return Promise.resolve(\"success\")\n    },\n    err =\u003e {\n        return Promise.reject(\"error\")\n    }\n)\n\nrequest.interceptors.response.use(\n    res =\u003e {\n        return Promise.resolve(\"success\")\n    },\n    err =\u003e {\n        return Promise.reject(\"error\")\n    }\n)\n```\n\n（3）取消请求\n\n取消请求支持cancelToken形式\n\n```\n// 以下是一个简单的示例\n\nconst url = '/api/hello'\n\nconst data = { msg : 1 }\n\nconst cancelFn = null\n\nrequest.post(url, data, {\n      cancelToken: new request.CancelToken(_c =\u003e cancelFn = _c)\n      })\n\n// 该请求将会在1s后被取消\nsetTimeout(() =\u003e {\n      cancelFn \u0026\u0026 cancelFn()\n}, 1000)\n```\n\n（4）创建axios实例\n\n可以使用`request.create(defaultConfig)`创建一个新的实例\n\n\n#### 2:graphQL部分\n\n该request插件提供了一个简单的解析器，你只需要写简单的语法，就可以帮你生成graphQL那些繁琐的查询语句。\n\ngraphQL挂载在request上，你可以通过`request.graphQL`获得grapgQL类\n\n\n```\nconst gql = new request.graphQL({\n    url: \"https://dev.test.cn/graphql\", // url是请求的地址\n    custom: false // custom表示是否自定义查询语句，后面会介绍\n})\n\n// 可以通过gql.client获得client实例\nconst client = gql.client\n\n// graph.client和request一样，可以配置defaults以及请求/响应拦截器，支持request的所有配置\n// 所以如果你想对graphQL做一些全局的响应拦截，比如验证token，拦截错误，对返回结果封装等，可以在这里设置\n\n// 用法和request一模一样\ngql.client.interceptors.response.use(\n    res =\u003e {\n        let { statusCode, data, config } = res\n        if (statusCode \u003e= 500) {\n            return Promise.reject(\"服务器错误，请稍后再试\")\n        }\n        return Promise.resolve(data)\n    },\n    err =\u003e {\n        return Promise.reject(err)\n    }\n)\n\n```\n\n创建完gql后，就可以使用了,以下通过几个demo来说明如何使用\n\n```\n/**\n * 完整的graphQL方法示例，包含目前gql方法支持的所有的属性\n * gql拥有query方法和mutate方法\n */\n\n/**\n * query操作\n * 使用模板语法\n */\nfunction demoQuery1() {\n      //gql就是刚才用 new request.graphQL 创建的实例\n    gql.query({ //通过gql.query执行query操作\n        //custom属性设置是否自定义查询语法，同graphQL初始化时候的custom属性，该属性会覆盖初始化时候的custom且仅对本次请求有效\n        custom: false, //可选\n        //query操作需要传入query属性\n        //custom为false时候需要按照模板格式传入即 operationName(key1: type1, key2: type2)\n        //只要按照规定格式写query，都会自动编译为正确的graphQL查询语句\n        //如传入session(appId: ID!, code: String!) 和 responseNode：session\n        //在请求时会编译为query session($appId:ID!,$code:String!){session(appId:$appId,code:$code){↵id↵name↵token}}\n        query: `session(appId: ID!, code: String!)`, // 必填\n        //定义返回的节点信息 \n        responseNode: fragment.session, //可选, 本demo中，session就是`↵id↵name↵token`字符串\n        variables: { //可选\n            appId: APPID,\n            code: code\n        }\n    }).then(res =\u003e {\n        if (res.errors) {\n            //也可以在相应拦截器里面设置\n            console.log('error')\n            reject(errors)\n        } else {\n            resolve(res.data)\n        }\n    }, err =\u003e {\n        reject(err)\n    })\n}\n\n\n/**\n * query操作\n * 自定义查询语法\n */\nfunction demoQuery1() {\n    gql.query({\n        //custom为true时，使用自定义查询语法\n        custom: true,\n        //自定义查询语法时，需要手动写完整的查询语句，不会进行编译过程，会原封不动的使用query进行请求\n        query: `query sessionByWechat($appId: ID!, $code: String!){\n                    sessionByWechat(appId: $appId, code:$code){\n                        ${fragment.session}\n                    }\n                }`,\n        variables: {\n            appId: APPID,\n            authCode: code\n        }\n    }).then(res =\u003e {\n        if (res.errors) {\n            console.log('error')\n        } else {\n            resolve(res.data)\n        }\n    }, err =\u003e {\n        reject(err)\n    })\n}\n\n/**\n * mutate操作\n * mutate操作的使用方式和query相同\n */\nfunction demoMutate() {\n    gql.mutate({\n        //mutate操作时不传query，而是传mutation，其他使用方式和query一模一样\n        mutation: `query sessionByWechat(appId: ID!, authCode: String!)`,\n        responseNode: fragment.session,\n        custom: false,\n        variables: {\n            appId: APPID,\n            authCode: code\n        }\n    }).then(res =\u003e {\n        resolve(res.data.sessionByWechat)\n    }, err =\u003e {\n        reject(err)\n    })\n}\n```\n\n### 新增 同时进行多个查询\n```\nfunction demoQuery1() {\n    gql.query({\n        custom: false, //可选\n        //同时查询多个时，query需要传入数组\n        query: [`session(appId: ID!, code: String!)`,`userInfo(id: $id)`]， // 会同时查询session和userInfo\n        // 此时responseNode需要为一个对象，分别定义不同查询的返回节点\n        responseNode:{\n            session: `token`,\n            userInfo: `name`\n        },\n        // variables也要为对象，分别传入不同查询的参数\n        variables: { \n            session: {\n                appId: \"test123\",\n                code: \"test456\"\n            },\n            userInfo:{\n                id: \"userid\"\n            }\n        }\n    }).then(res =\u003e {\n        if (res.errors) {\n            //也可以在相应拦截器里面设置\n            console.log('error')\n            reject(errors)\n        } else {\n            resolve(res.data)\n        }\n    }, err =\u003e {\n        reject(err)\n    })\n}\n```\n\n#### 如果使用方法有不明白的欢迎在issue里和我交流\n#### 如果对你有帮助欢迎点个star\n\n\n\n\n    \n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fa7650%2Fwx-axios-graphql","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fa7650%2Fwx-axios-graphql","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fa7650%2Fwx-axios-graphql/lists"}