Repository: hatedMe/wechat-request
Branch: master
Commit: eda5fc562e34
Files: 17
Total size: 16.0 KB
Directory structure:
gitextract_u5nvn7o1/
├── .editorconfig
├── .eslintrc.js
├── .gitignore
├── .prettierrc
├── LICENSE
├── README.md
├── example/
│ └── defaultConfig/
│ └── request.js
├── index.d.ts
├── package.json
├── rollup.config.js
└── src/
├── InterceptorManager.js
├── class.js
├── core/
│ └── dispatchRequest.js
├── defaults.js
├── helpers/
│ └── util.js
├── index.js
└── request.js
================================================
FILE CONTENTS
================================================
================================================
FILE: .editorconfig
================================================
root = true
[*]
charset = utf-8
indent_style = space
indent_size = 4
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true
================================================
FILE: .eslintrc.js
================================================
module.exports = {
"env": {
"browser": true,
"es2021": true,
"node": true,
},
globals : {
wx:true,
},
"extends": "eslint:recommended",
"parserOptions": {
"ecmaVersion": 12,
"sourceType": "module"
},
"rules": {
semi: [2, "always"],
quotes: [2, "double"],
indent: ["error", 4],
"no-mixed-spaces-and-tabs": ["error", "smart-tabs"],
camelcase: 0,
"no-irregular-whitespace": ["error", { "skipComments": true }],
"no-tabs" : 0
}
};
================================================
FILE: .gitignore
================================================
.DS_Store
node_modules/
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# Editor directories and files
.idea
*.suo
*.ntvs*
*.njsproj
*.sln
/dist
*.tgz
================================================
FILE: .prettierrc
================================================
{
"tabWidth": 4,
"singleQuote": false,
"printWidth": 100,
"semi": true,
"useTabs": false
}
================================================
FILE: LICENSE
================================================
MIT License
Copyright (c) 2018
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
================================================
FILE: README.md
================================================
# wechat-request
<p align="center">
<img src="https://img.shields.io/npm/dm/wechat-request.svg?style=flat-square" />
<img src="https://img.shields.io/npm/v/wechat-request.svg?style=flat-square" />
<img src="https://img.shields.io/badge/license-MIT-blue.svg?style=flat-square" />
</p>
> 基于Promise微信小程序http请求,轻便,小巧,api友好,功能丰富
## 特别之处
- 支持Promise API
- 拦截请求和响应
- 转换请求和响应数据
- 取消请求
- 自动转换为JSON数据
- 超时请求
- 告别callback
- 支持默认请求前缀
- 支持并发请求
## 使用方式
```yarn add wechat-request``` <br />
```npm install wechat-request --save ```<br />
```import wxRequest from 'wechat-request';```<br />
## 一步上手
首先来一个简单的```get```请求
```js
// 向具有给定ID的用户发出请求
wxRequest.get('/user?id=12345')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
// 可选地,上面的请求也可以按照
wxRequest.get('/user', {
params: {
id: 'number'
}
}).then(function (response) {
console.log(response);
}).catch(function (error) {
console.log(error);
});
// 想要使用 async/await? 将`async`关键字添加到外部函数/method
async function getUser() {
try {
const response = await wxRequest.get('/user?ID=12345');
console.log(response);
} catch (error) {
console.error(error);
}
}
```
> 多种方法使用async/waait,开启代码便捷、畅快之旅
接着再来一个```post```请求
```js
wxRequest.post('/user', {
firstname : 'firstname',
lastname : 'lastname'
}).then(function (response) {
console.log(response);
}).catch(function (error) {
console.log(error);
});
```
执行多并发请求例子
```js
function getUserAccount() {
return wxRequest.get('/user/12345');
}
function getUserPermissions() {
return wxRequest.get('/user/12345/permissions');
}
wxRequest.all([getUserAccount(), getUserPermissions()])
.then(response =>{
// dosoming ...
});
```
## 请求方法别名
当然除了常见的```get```,```post```其他的请求也统一封装
- ```wxRequest.request(config)```
- ```wxRequest.get(url[, config])```
- ```wxRequest.delete(url[, config])```
- ```wxRequest.head(url[, config])```
- ```wxRequest.options(url[, config])```
- ```wxRequest.post(url[, data[, config]])```
- ```wxRequest.put(url[, data[, config]])```
- ```wxRequest.patch(url[, data[, config]])```
> note: 当使用别名方法`url`时,`method`和`data`属性不需要在config中指定。
### 全局配置
使用场景用户请求需要token,或者地址前缀,一次配置,省时省心。
```js
wxRequest.defaults.baseURL = 'https://api.example.com';
wxRequest.defaults.headers['Authorization'] = AUTH_TOKEN;
wxRequest.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
```
## 致谢 && 参考
* [axios](https://github.com/axios/axios)
## License
MIT
================================================
FILE: example/defaultConfig/request.js
================================================
import wxRequest from 'wechat-request';
// 针对post请求增加token
wxRequest.interceptors.request.use(
config => {
if (config.method === 'post') {
config.headers.common['Authorization'] = AUTH_TOKEN;
}
return config;
},
err => {
return Promise.reject(err);
});
export default wxRequest;
================================================
FILE: index.d.ts
================================================
export interface BaseData {
[key: string]: any;
}
export interface RequestPromise<T = any> extends Promise<Response<T>> {
}
export type Method =
| 'get' | 'GET'
| 'delete' | 'DELETE'
| 'head' | 'HEAD'
| 'options' | 'OPTIONS'
| 'post' | 'POST'
| 'put' | 'PUT'
| 'patch' | 'PATCH'
| 'link' | 'LINK'
| 'unlink' | 'UNLINK'
export interface RequestConfig {
url?: string;
method?: Method;
baseURL?: string;
headers?: BaseData;
params?: BaseData;
data?: BaseData;
timeout?: number;
}
export interface InterceptorManager<V> {
use(onFulfilled?: (value: V) => V | Promise<V>, onRejected?: (error: any) => any): number;
eject(id: number): void;
}
export interface Response<T = BaseData> {
data: T,
status: number,
statusText: string,
headers: T,
config: RequestConfig
}
export interface RequestError<T = any> extends Error {
}
export interface Instance {
(config: RequestConfig): RequestPromise;
(url: string, config?: RequestConfig): RequestPromise;
interceptors: {
request: InterceptorManager<RequestConfig>;
response: InterceptorManager<Response>;
};
request<T = any, R = Response<T>>(config: RequestConfig): Promise<R>;
get<T = any, R = Response<T>>(url: string, config?: RequestConfig): Promise<R>;
delete<T = any, R = Response<T>>(url: string, config?: RequestConfig): Promise<R>;
head<T = any, R = Response<T>>(url: string, config?: RequestConfig): Promise<R>;
post<T = any, R = Response<T>>(url: string, data?: any, config?: RequestConfig): Promise<R>;
put<T = any, R = Response<T>>(url: string, data?: any, config?: RequestConfig): Promise<R>;
patch<T = any, R = Response<T>>(url: string, data?: any, config?: RequestConfig): Promise<R>;
}
export interface RequestStatic extends Instance {
create(config?: RequestConfig): Instance;
all<T>(values: (T | Promise<T>)[]): Promise<T[]>;
}
declare const wechatRequest: RequestStatic
export default wechatRequest;
================================================
FILE: package.json
================================================
{
"name": "wechat-request",
"version": "2.7.0",
"description": "基于Promise微信小程序http请求,轻便,小巧,api友好,功能丰富",
"main": "dist/index.js",
"scripts": {
"dev": "rollup -c -w",
"build": "rollup -c",
"lint": "eslint -c ./.eslintrc.js --ext .js src/ --fix",
"lint-prettire": "prettier --write src/**/*.{vue,js,jsx,less}"
},
"keywords": [
"request",
"wechat",
"promise",
"http",
"微信小程序"
],
"repository": {
"type": "git",
"url": "https://github.com/hatedMe/wechat-request.git"
},
"bugs": {
"url": "https://github.com/hatedMe/wechat-request/issues"
},
"license": "ISC",
"author": "Atom <7548764@qq.com>",
"files": [
"dist",
"index.d.ts"
],
"types": "index.d.ts",
"devDependencies": {}
}
================================================
FILE: rollup.config.js
================================================
export default {
input: "src/index.js",
output: {
file: "dist/index.js",
format: "umd",
name: "wechatRequest",
},
watch: {
include: "src/**",
},
};
================================================
FILE: src/InterceptorManager.js
================================================
export default class InterceptorManager {
constructor() {
this.handlers = [];
}
use(fulfilled, rejected) {
this.handlers.push({
fulfilled,
rejected,
});
return this.handlers.length - 1;
}
eject(id) {
if (this.handlers[id]) {
this.handlers[id] = null;
}
}
forEach(fn) {
this.handlers.forEach((e) => {
if (e !== null) {
fn(e);
}
});
}
}
================================================
FILE: src/class.js
================================================
import * as util from "./helpers/util";
import InterceptorManager from "./InterceptorManager";
import { dispatchRequest } from "./core/dispatchRequest";
class Request {
constructor(config) {
this.defaults = config;
this.interceptors = {
request: new InterceptorManager(),
response: new InterceptorManager(),
};
}
request(config) {
if (typeof config === "string") {
config = util.merge({ url: arguments[0] }, arguments[1]);
}
config = util.deepMerge(this.defaults, config);
config.method = config.method ? config.method.toLowerCase() : "get";
let chain = [dispatchRequest, undefined];
let promise = Promise.resolve(config);
this.interceptors.request.forEach(function (interceptor) {
chain.unshift(interceptor.fulfilled, interceptor.rejected);
});
this.interceptors.response.forEach(function (interceptor) {
chain.push(interceptor.fulfilled, interceptor.rejected);
});
while (chain.length) {
promise = promise.then(chain.shift(), chain.shift());
}
return promise;
}
all(promises) {
return Promise.all(promises);
}
}
["delete", "get", "head", "options", "trace"].forEach((method) => {
Request.prototype[method] = function (url, config) {
return this.request(
util.merge(config || {}, {
method,
url,
})
);
};
});
["post", "put", "patch"].forEach((method) => {
Request.prototype[method] = function (url, data, config) {
return this.request(
util.merge(config || {}, {
method,
url,
data,
})
);
};
});
export default Request;
================================================
FILE: src/core/dispatchRequest.js
================================================
import * as util from "../helpers/util";
export const dispatchRequest = function (config) {
if (config.baseURL && !util.isAbsoluteURL(config.url)) {
config.url = util.combineURLs(config.baseURL, config.url);
}
config.url = util.buildURL(config.url, config.params);
config.data = util.merge(config.data, config.transformRequest(config.data));
config.headers = util.merge(
config.headers.common || {},
config.headers[config.method] || {},
config.headers || {}
);
let methods = ["delete", "get", "head", "post", "put", "patch", "common"];
methods.forEach((method) => {
delete config.headers[method];
});
let promise = Promise.resolve(config);
promise = promise.then((config) => {
return new Promise(function (resolve, reject) {
let requestTask = wx.request({
url: config.url,
data: util.buildData(config.data),
header: config.headers,
method: config.method,
dataType: config.dataType,
success: function (res) {
resolve({
data: res.data,
headers: res.header,
status: res.statusCode,
statusText: "ok",
});
},
fail: function (err) {
reject(err);
},
complete: function () {
config.complete && config.complete();
},
});
if (config.timeout && typeof config.timeout === "number" && config.timeout > 1000) {
setTimeout(() => {
requestTask.abort();
resolve({
status: "canceled",
});
}, config.timeout);
}
});
});
return promise;
};
================================================
FILE: src/defaults.js
================================================
import * as util from "./helpers/util";
let DEFAULT_CONTENT_TYPE = {
"Content-Type": "application/x-www-form-urlencoded",
};
const defaults = {
method: "get", // default
// baseURL: '',
dataType: "json",
responseType: "text",
// timeout: 0,
headers: {},
// params : {},
transformRequest(data) {
return data;
},
// transformResponse (data) {
// return data;
// },
// validateStatus ( status ) {
// return status >= 200 && status < 300
// }
};
defaults.headers = {
common: {
Accept: "application/json, text/plain, */*",
},
};
["delete", "get", "head", "post", "put", "patch"].map((e) => {
defaults.headers[e] = util.merge(defaults.headers, DEFAULT_CONTENT_TYPE);
});
export default defaults;
================================================
FILE: src/helpers/util.js
================================================
export const bind = function (fn, thisArg) {
return function warp() {
return fn.apply(thisArg, Array.from(arguments));
};
};
export const extend = function (a, b, thisArg) {
let o = Object.getOwnPropertyNames(b);
o.forEach((attr) => {
if (thisArg && typeof b[attr] === "function") {
a[attr] = bind(b[attr], thisArg);
} else {
a[attr] = b[attr];
}
});
return a;
};
export const copyobj = function (a, b) {
return Object.assign({}, a, b);
};
export const merge = function () {
var result = {};
Array.from(arguments).forEach((e) => {
for (let key in e) {
if (e[key] && typeof e[key] === "object" && !isEmptyObject(e[key])) {
merge(result[key], e[key]);
}
result[key] = e[key];
}
});
return result;
};
export const deepMerge = function () {
let result = {};
Array.from(arguments).forEach((e) => {
if (e && typeof e === "object" && !isEmptyObject(e)) {
Object.keys(e).forEach((key) => {
if (e[key] && typeof e[key] === "object") {
result[key] = deepMerge(result[key], e[key]);
}
result[key] = e[key];
});
}
});
return result;
};
export const isEmptyObject = (obj) => {
return Object.getOwnPropertyNames(obj).length === 0;
};
export const isObject = (obj) => {
return obj !== null && typeof obj === "object";
};
export const combineURLs = function (baseURL, relativeURL) {
return relativeURL
? baseURL.replace(/\/+$/, "") + "/" + relativeURL.replace(/^\/+/, "")
: baseURL;
};
function encode(val) {
return encodeURIComponent(val)
.replace(/%40/gi, "@")
.replace(/%3A/gi, ":")
.replace(/%24/g, "$")
.replace(/%2C/gi, ",")
.replace(/%20/g, "+")
.replace(/%5B/gi, "[")
.replace(/%5D/gi, "]");
}
export const buildURL = function (url, paramsObject) {
if (!paramsObject || isEmptyObject(paramsObject)) return url;
let parts = [];
Object.keys(paramsObject).forEach((key) => {
parts.push(encode(key) + "=" + encode(paramsObject[key]));
});
return (url += (url.indexOf("?") === -1 ? "?" : "&") + parts.join("&"));
};
export const isAbsoluteURL = function (url) {
return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url);
};
export const buildData = (data) => {
if (!isObject(data) || isEmptyObject(data)) return {};
const result = {};
Object.keys(data).forEach((key) => {
if (data[key] !== null && typeof data[key] !== "undefined") {
result[key] = data[key];
}
});
return result;
};
================================================
FILE: src/index.js
================================================
import request from "./request";
export default request;
================================================
FILE: src/request.js
================================================
import Request from "./class";
import * as util from "./helpers/util";
import defaults from "./defaults";
function createInstance(config) {
let context = new Request(config);
let instance = util.bind(Request.prototype.request, context);
util.extend(instance, Request.prototype, context);
util.extend(instance, context);
// 用于创建多个实例
instance.create = function (config) {
return createInstance(util.merge(defaults, config));
};
return instance;
}
const request = createInstance(defaults);
// 并发请求数据处理
request.spread = function (callback) {
return function (...arg) {
return callback.apply(null, [...arg]);
};
};
export default request;
gitextract_u5nvn7o1/
├── .editorconfig
├── .eslintrc.js
├── .gitignore
├── .prettierrc
├── LICENSE
├── README.md
├── example/
│ └── defaultConfig/
│ └── request.js
├── index.d.ts
├── package.json
├── rollup.config.js
└── src/
├── InterceptorManager.js
├── class.js
├── core/
│ └── dispatchRequest.js
├── defaults.js
├── helpers/
│ └── util.js
├── index.js
└── request.js
SYMBOL INDEX (22 symbols across 6 files)
FILE: index.d.ts
type BaseData (line 1) | interface BaseData {
type RequestPromise (line 5) | interface RequestPromise<T = any> extends Promise<Response<T>> {
type Method (line 9) | type Method =
type RequestConfig (line 20) | interface RequestConfig {
type InterceptorManager (line 30) | interface InterceptorManager<V> {
type Response (line 35) | interface Response<T = BaseData> {
type RequestError (line 43) | interface RequestError<T = any> extends Error {
type Instance (line 47) | interface Instance {
type RequestStatic (line 62) | interface RequestStatic extends Instance {
FILE: src/InterceptorManager.js
class InterceptorManager (line 1) | class InterceptorManager {
method constructor (line 2) | constructor() {
method use (line 6) | use(fulfilled, rejected) {
method eject (line 14) | eject(id) {
method forEach (line 20) | forEach(fn) {
FILE: src/class.js
class Request (line 5) | class Request {
method constructor (line 6) | constructor(config) {
method request (line 13) | request(config) {
method all (line 38) | all(promises) {
FILE: src/defaults.js
constant DEFAULT_CONTENT_TYPE (line 3) | let DEFAULT_CONTENT_TYPE = {
method transformRequest (line 17) | transformRequest(data) {
FILE: src/helpers/util.js
function encode (line 65) | function encode(val) {
FILE: src/request.js
function createInstance (line 5) | function createInstance(config) {
Condensed preview — 17 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (19K chars).
[
{
"path": ".editorconfig",
"chars": 147,
"preview": "root = true\n\n[*]\ncharset = utf-8\nindent_style = space\nindent_size = 4\nend_of_line = lf\ninsert_final_newline = true\ntrim_"
},
{
"path": ".eslintrc.js",
"chars": 566,
"preview": "module.exports = {\n \"env\": {\n \"browser\": true,\n \"es2021\": true,\n \"node\": true,\n },\n global"
},
{
"path": ".gitignore",
"chars": 151,
"preview": ".DS_Store\nnode_modules/\nnpm-debug.log*\nyarn-debug.log*\nyarn-error.log*\n\n# Editor directories and files\n.idea\n*.suo\n*.ntv"
},
{
"path": ".prettierrc",
"chars": 100,
"preview": "{\n \"tabWidth\": 4,\n \"singleQuote\": false,\n \"printWidth\": 100,\n \"semi\": true,\n \"useTabs\": false\n}"
},
{
"path": "LICENSE",
"chars": 1057,
"preview": "MIT License\n\nCopyright (c) 2018 \n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this s"
},
{
"path": "README.md",
"chars": 2484,
"preview": "\n\n\n\n# wechat-request\n\n<p align=\"center\">\n <img src=\"https://img.shields.io/npm/dm/wechat-request.svg?style=flat-squar"
},
{
"path": "example/defaultConfig/request.js",
"chars": 349,
"preview": "\n\nimport wxRequest from 'wechat-request';\n\n\n// 针对post请求增加token\nwxRequest.interceptors.request.use(\n config => {\n "
},
{
"path": "index.d.ts",
"chars": 2029,
"preview": "export interface BaseData {\n [key: string]: any;\n}\n\nexport interface RequestPromise<T = any> extends Promise<Response"
},
{
"path": "package.json",
"chars": 761,
"preview": "{\n \"name\": \"wechat-request\",\n \"version\": \"2.7.0\",\n \"description\": \"基于Promise微信小程序http请求,轻便,小巧,api友好,功能丰富\",\n \"main\": "
},
{
"path": "rollup.config.js",
"chars": 200,
"preview": "export default {\n input: \"src/index.js\",\n output: {\n file: \"dist/index.js\",\n format: \"umd\",\n "
},
{
"path": "src/InterceptorManager.js",
"chars": 510,
"preview": "export default class InterceptorManager {\n constructor() {\n this.handlers = [];\n }\n\n use(fulfilled, reje"
},
{
"path": "src/class.js",
"chars": 1837,
"preview": "import * as util from \"./helpers/util\";\nimport InterceptorManager from \"./InterceptorManager\";\nimport { dispatchRequest "
},
{
"path": "src/core/dispatchRequest.js",
"chars": 1951,
"preview": "import * as util from \"../helpers/util\";\nexport const dispatchRequest = function (config) {\n if (config.baseURL && !u"
},
{
"path": "src/defaults.js",
"chars": 799,
"preview": "import * as util from \"./helpers/util\";\n\nlet DEFAULT_CONTENT_TYPE = {\n \"Content-Type\": \"application/x-www-form-urlenc"
},
{
"path": "src/helpers/util.js",
"chars": 2729,
"preview": "export const bind = function (fn, thisArg) {\n return function warp() {\n return fn.apply(thisArg, Array.from(ar"
},
{
"path": "src/index.js",
"chars": 57,
"preview": "import request from \"./request\";\nexport default request;\n"
},
{
"path": "src/request.js",
"chars": 693,
"preview": "import Request from \"./class\";\nimport * as util from \"./helpers/util\";\nimport defaults from \"./defaults\";\n\nfunction crea"
}
]
About this extraction
This page contains the full source code of the hatedMe/wechat-request GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 17 files (16.0 KB), approximately 4.5k tokens, and a symbol index with 22 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.