wechat-miniprogram / wechat-miniprogram/api-typings

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

Open
#322 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
TypeScript
Stars
803
Forks
117
Avg merge
24m
Merged PRs (30d)
1

Description

注意看代码中的 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)
			}
		});
	})
}

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start at the wx.request type declaration and inspect the related ResponseCallback and PostTempOptions definitions shown in the issue. Confirm how request-body and response types are currently represented, then ensure both can be supplied as generics so callers do not need additional as casts.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
api
Issue type
Feature
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.