Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

wx.request 请求体和返回增加泛型 #322

Open
Locter9001 opened this issue May 15, 2024 · 1 comment
Open

wx.request 请求体和返回增加泛型 #322

Locter9001 opened this issue May 15, 2024 · 1 comment

Comments

@Locter9001
Copy link

注意看代码中的 OUTIN,这样做的好处是不需要额外的使用 as 语句了

async function CustomRequest<

	OUT extends string | WechatMiniprogram.IAnyObject | ArrayBuffer =
	| string
	| WechatMiniprogram.IAnyObject
	| ArrayBuffer,

	IN extends string | WechatMiniprogram.IAnyObject | ArrayBuffer =
	| string
	| WechatMiniprogram.IAnyObject
	| ArrayBuffer

>({ data, url, method }: PostTempOptions<IN>, options?: API.IRequestOptions): Promise<OUT> {
	// 没有token就赋值,避免每次都从缓存中获取,缓存获取数据非常消耗时间

	if (!token || options?.refreshToken) {
		token = wx.getStorageSync('token');
	}

	return new Promise((resolve, reject) => {
                // NOTE: 主要看这里,OUT请求回调,IN则是附带数据
		wx.request<ResponseCallback<OUT>, IN>({
			url: PREFIX + url,
			header: { Authorization: 'Bearer ' + token },
			method: method ?? 'POST',
			data: data,
			timeout: 2000,
			success: (res) => {
				if (res.data.error_code === 401) {
					reject(new RequestError('请登录', 401))
				}

				if (!res.data.success) {
					reject(new RequestError(res.data.error_message!, res.data.error_code!))
				}

				resolve(res.data.data)
			},
			fail: (err) => {
				reject(err)
			}
		});
	})
}
@Locter9001
Copy link
Author

我目前是直接改的声明文件,用了很长时间没有什么问题,我看自述文件说不同意任何有关 api 的 PR 就没有提交了

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant