midwayjs / hooks

"Zero" Api / Type Safe / Fullstack Kit / Powerful Backend

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

一体化场景下使用中间件封装返回结果,前端调用API函数返回类型没有发生相应改变?

RobertChaw opened this issue · comments

项目中全局使用 responseWrapper 中间件封装一层带执行结果的对象返回给前端。
image

但在一体化中,前端调用 API 函数返回类型没有发生相应改变,导致前端获取返回结果时的类型是错误的。
image

除了每次调用时 as 关键词让其正常工作以外,有没有一种更优雅的方式让其正常工作?

commented

前端可以使用中间件拆包。参考:https://midwayjs.org/docs/hooks/client#middleware-middleware

import { setupHttpClient } from '@midwayjs/rpc';
import type { Middleware } from '@midwayjs/rpc';

const unwrap: Middleware = async (
  ctx,
  next
) => {
  await next();
  ctx.res = ctx.res.data
};

setupHttpClient({
  middleware: [unwrap],
});

前端可以使用中间件拆包。参考:https://midwayjs.org/docs/hooks/client#middleware-middleware

import { setupHttpClient } from '@midwayjs/rpc';
import type { Middleware } from '@midwayjs/rpc';

const unwrap: Middleware = async (
  ctx,
  next
) => {
  await next();
  ctx.res = ctx.res.data
};

setupHttpClient({
  middleware: [unwrap],
});

好的!谢谢您帮我解决了这个小问题。 🌷🌷