Coder Social home page Coder Social logo

xdoer / prequest Goto Github PK

View Code? Open in Web Editor NEW
84.0 2.0 13.0 1.69 MB

A Modular And Pluggable Solution For HTTP Request.

Home Page: https://pre-quest.vercel.app

License: MIT License

TypeScript 99.05% Shell 0.11% JavaScript 0.84%
http xhr fetch miniprogram request interceptor middleware

prequest's Introduction

PreQuest

一套模块化,可插拔的 JS 运行时 HTTP 请求解决方案。

npm Minzipped size NPM Downloads code style: prettier Codacy Badge GitHub license

简介

PreQuest 是一套 JS 运行时的 HTTP 解决方案。

它包含了一些针对不同 JS 运行平台的封装的请求库,并为这些请求库提供了一致的中间件、拦截器、全局配置等功能的体验

还针对诸如 Token 的添加,失效处理,无感知更新、接口缓存、错误重试等常见业务场景,提供了解决方案。

当这些功能不满足你的需求、或者你想定制化时,也可以基于 @prequest/core 快速封装一个实现你需求的请求库。

支持平台

Web、小程序、ReactNative、快应用等

使用示例

下面以 @prequest/xhr 为例,介绍使用方法

import { PreQuest, create } from '@prequest/xhr'
import timeoutMiddleware from '@prequest/timeout'

// 全局配置
PreQuest.defaults.baseURL = 'http://locahost:8080'
// 项目中如果有设置 header 的需求,建议先初始化有个空对象
PreQuest.defaults.headers = {}

// 全局中间件
PreQuest.use((ctx, next) => {
  // 在这里,你可以全局修改请求参数
  console.log(ctx.request)

  await next()

  // 这里,你可以全局修改响应数据
  console.log(ctx.response)
})

// 创建实例
const prequest = create({
  headers: {
    'Content-Type': 'application/json; charset=utf-8',
  },
})

// 实例中间件
prequest.use(timeoutMiddleware)

// 请求调用
prequest('/user')
prequest('/user', { method: 'POST' })
prequest.get('/user', { params: { a: 1 } })
prequest.post('/user', { data: { a: 1 } })

// 响应类型注入
interface User {}
const user = await prequest<User>('/user', { params: { id: 1 } })
const user2 = await prequest.get<User>('/user', { params: { id: 1 } })

文档

website: https://pre-quest.vercel.app

贡献

Contributing Guide

License

MIT License

prequest's People

Contributors

bingtsingw avatar xdoer avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

prequest's Issues

await 如何获取promise rejection ?

代码示例

// 发起请求
const req = await req.get("any")
// 如果断网的情况下 永远不会进入到下一步
if (req.statusCode === 200) { .... }

想要的结果

能够永远获取response 不管是成功与失败 能够走到最后而不会被半途break !

基本环境

  • 微信小程序 taro react

1.3.6 bugs?

xhr库:
如果不设置 responseType 会显示警告 The provided value 'undefined' is not a valid enum value of type XMLHttpRequestResponseType.
如果设置了 responseType: 'json' 则返回结果仍是文本。
如果请求被CancelToken中断,则会报错 Uncaught TypeError: Cannot destructure property responseText of 'undefined' or 'null'.

fetch库: config必须设置一个 header: {} ,才能设置 headers,否则会卡请求。

cache中间件:文档描述和测试用例不符,到底如何使用?

cache 插件的 缺陷

插件内部缓存数据的变量没有提供可清理的功能,那么随着缓存数据的增加,这个岂不是会内存溢出?
根据现在的设计,至少应提供一个可手动释放的方法,或者在内部设置一个最后请求的时间戳,因为现在的缓存有效期是全局的而不是跟随单个请求记录的,那么你完全可以在下一次发起请求时,判断当前缓存的数据是否过期,过期了就应该 Map.clear() 清理整个缓存,连计时器都用不上,您觉得呢。 :)

about xhr responseType...

xhr.esm.js:19 Uncaught DOMException: Failed to read the 'responseText' property from 'XMLHttpRequest': The value is only accessible if the object's 'responseType' is '' or 'text' (was 'blob').

xhr.esm.js:19 Uncaught DOMException: Failed to read the 'responseText' property from 'XMLHttpRequest': The value is only accessible if the object's 'responseType' is '' or 'text' (was 'arraybuffer').

我该如何使用它来进行二进制数据的下载???

`useRequest`类型定义

使用const useRequest = queryHook.useRequest.bind(queryHook) 定义 useRequest之后, useRequestany类型, 没有代码提示了, 不知道怎么去定义useRequest的类型, 麻烦大佬帮忙看下

还是uniapp 缓存的问题,

缓存控制器这样来写

cacheKernel() {
return {
get:function(key) {
let resq = uni.getStorageSync(key)
if(!resq) return false;
return resq;
},
// set: uni.setStorageSync,
set: function(key,resq){
uni.setStorageSync(key,resq);
},
delete: function(key){
return uni.removeStorageSync(key)
}
}
},

但是返回的是空
`
prequest.post(url, args).then(res => {
console.log(res); // {} 这里是空

}).then(res => {

})
`

Taro v3.2.10 请求锁报错

图片
图片
请求token接口获取到token,赋值给ctx.request.headers['Authorization'] 时报Unhandled promise rejection TypeError: Cannot set property 'Authorization' of undefined

请求payload 序列化问题?

`
import { create, PreQuest } from '@prequest/xhr';

const $http = create();

$http.post('test', {
data: { a: 1 },
});

`
为啥请求参数会变成 [object Object] 呢? (content-type是application json)
@xdoer 老哥 帮看看呗

[bug] use-request 返回data错误

有两个小bug

  1. fetchData 函数中, 应该取res.data传给defaultUpdate
  2. defaultUpdate 应该接收两个参数, 默认忽略prevData, 返回新的data
return {
  loading: false,
  data: onUpdate(data!, res.data as any),
  error: null,
}
export function defaultUpdate<Q>(_, data) {
  return data;
}

在Taro 3.4.2 版本编译报错

[email protected] build:weapp
taro build --type weapp

👽 Taro v3.4.2

启动 开发者工具-项目目录 D:\Demo\myApp\dist
生成 工具配置 D:\Demo\myApp\dist/project.config.json

编译 发现入口 src/app.ts
编译 发现页面 src/pages/index/index.tsx
🙅 编译失败. 2022/9/10 10:55:15

./node_modules/@xdoer/x/lib/esm/asyncPromise.js 3:10
Module parse failed: Unexpected token (3:10)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| // @ts-nocheck
| export class AsyncPromise {

loading = false;
|
| constructor() {

Taro v3.2.12 使用ErrorRetryMiddleware 报错

prequest
.use(cacheMiddleware.run)
.use(errorRetryMiddleware.run)
.use(lockMiddleware)
.use(parseResponse)

使用use(errorRetryMiddleware.run)报错信息如下:

./node_modules/@prequest/error-retry/dist/errorretrymiddleware.cjs.development.js 28:34
Module parse failed: Unexpected token (28:34)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
|
| return {

  retryCount: opt.retryCount ?? (ctx.request.retryCount || ((_this$opt = this.opt) == null ? void 0 : _this$opt.retryCount) || 1),

| retryControl: ctx.request.retryControl || ((_this$opt2 = this.opt) == null ? void 0 : _this$opt2.retryControl) || defaultRetryControl
| };

./node_modules/@prequest/error-retry/dist/errorretrymiddleware.cjs.development.js 28:34
Module parse failed: Unexpected token (28:34)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
|
| return {

  retryCount: opt.retryCount ?? (ctx.request.retryCount || ((_this$opt = this.opt) == null ? void 0 : _this$opt.retryCount) || 1),

| retryControl: ctx.request.retryControl || ((_this$opt2 = this.opt) == null ? void 0 : _this$opt2.retryControl) || defaultRetryControl
| };
@ ./node_modules/@prequest/error-retry/dist/index.js 7:19-71
@ ./src/utils/error-retry.ts
@ ./src/utils/http.ts
@ ./node_modules/babel-loader/lib!./src/pages/common/index.tsx
@ ./src/pages/common/index.tsx

lock的getValue使用 undefined判断

在小程序上, 后端可能会采用“静默登陆”, 当用户没有注册的时候, token返回 '', 这时候, lock会在每次request都尝试获取token

文档不详细

大哥,能不能详细写下入门文档,看了文档,我发一个post请求都要猜,method参数放在哪里

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.