koishijs / koishi

Cross-platform chatbot framework made with love
https://koishi.chat
MIT License
4.54k stars 249 forks source link

Feature: ctx.http需要暴露interceptors或者提供拦截器功能 #1266

Open mzzsfy opened 1 year ago

mzzsfy commented 1 year ago

Describe the problem related to the feature request

检查到特定返回值自动重新登陆,

Describe the solution you'd like

ctx.http需要暴露interceptors或者提供拦截器功能

Describe alternatives you've considered

创建新的http

Additional context

No response

shigma commented 1 year ago

之后可能会迁移到 fetch API,迁移之后再做考虑(我也不知道 fetch 有没有 interceptor 对应的实现)

ref: https://github.com/koishijs/koishi/issues/1181

MaikoTan commented 1 year ago

In paticular your case, I think you could just catch the exception and then resolve the re-login process.

try {
  const res = ctx.http.get(url)
  // ...
} catch (e) {
  if (Quester.isAxiosError(e) {
    if (e.statusCode === 401) {
      // re-login and re-request
    }
  }
}

Well, there're no RAII or something in JS, the code might be ugly but usable for now.

Hieuzest commented 1 year ago

我倾向于在目前的实现上直接提供一套api来做。因为其实并不需要使用axios的interceptor,只需要我们wrap一些东西

mzzsfy commented 1 year ago

In paticular your case, I think you could just catch the exception and then resolve the re-login process.

try {
  const res = ctx.http.get(url)
  // ...
} catch (e) {
  if (Quester.isAxiosError(e) {
    if (e.statusCode === 401) {
      // re-login and re-request
    }
  }
}

Well, there're no RAII or something in JS, the code might be ugly but usable for now.

目前我也是这样实现的,但这开发起来很不友好

shigma commented 9 months ago

请问能提供一些使用 axios interceptor 的示例代码吗?我有意实现相关的功能,不过想深入了解你的需求。

mzzsfy commented 9 months ago

请问能提供一些使用 axios interceptor 的示例代码吗?我有意实现相关的功能,不过想深入了解你的需求。

我尝试在github上搜索了一些刷新token的例子: https://github.com/chengpeiquan/refresh-token/blob/27bfcbbfd531d99777a5cec003ac47adc4326447/src/libs/axios/index.ts

https://github.com/collieZ/axios-refreshatoken/blob/f72ab22d78f1fba1fcc1905eaf0db8c34887f4c0/request.js

https://github.com/Jacky-Summer/personal-blog/blob/8de2d6601a58b30e7f02fa936c713327026e9da1/%E5%BC%80%E5%8F%91%E9%81%87%E5%88%B0%E7%9A%84%E5%B0%8F%E9%97%AE%E9%A2%98%E5%90%88%E9%9B%86/%E5%B0%81%E8%A3%85%20axios%20%E6%8B%A6%E6%88%AA%E5%99%A8%E5%AE%9E%E7%8E%B0%E7%94%A8%E6%88%B7%E6%97%A0%E6%84%9F%E5%88%B7%E6%96%B0%20access_token.md