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

@midway/grpc作为独立项目添加中间件导致返回值错误 #2251

Closed
ddzyan opened this issue Aug 18, 2022 · 9 comments
Closed

@midway/grpc作为独立项目添加中间件导致返回值错误 #2251

ddzyan opened this issue Aug 18, 2022 · 9 comments

Comments

@ddzyan
Copy link
Contributor

ddzyan commented Aug 18, 2022

将 @midway/grpc 作为独立项目运行,并且在其中增加一些中间件,导致返回值错误,并且在中间件中无法获得 provider 处理的结果,查看源码并没有支持将类似koa将返回结果挂载在 ctx.body 对象上作为最后返回 ,而是将 composeFn 最终结果作为返回值
image

@czy88840616
Copy link
Member

czy88840616 commented Aug 18, 2022

grpc 不支持 ctx.body 返回,只会处理 return 的结果,中间件也必须使用 return await next() 标准方式返回。

@ddzyan
Copy link
Contributor Author

ddzyan commented Aug 18, 2022

grpc 不支持 ctx.body 返回,只会处理 return 的结果。

能不能将结果挂载在ctx其他属性上,然后在处理的时候不将 result 作为结果返回,而是从 ctx属性上获取返回值呢
image

@czy88840616
Copy link
Member

不能,ctx 属性非标。

@ddzyan
Copy link
Contributor Author

ddzyan commented Aug 18, 2022

好的,尴尬,我看这个ctx也是@grpc/grpc-js实现的,好像也没办法

@czy88840616
Copy link
Member

就算你定义了 ctx.a 这个属性返回,也仅在你这里能用,框架侧是不知道 a 这个属性的含义的,所以最好的办法是都不往 ctx 上挂,走标准行为。

@ddzyan
Copy link
Contributor Author

ddzyan commented Aug 18, 2022

好的,我想实现用中间件完成对框架请求,响应和异常日志的输出,具体代码如下,现在也可以正常实现了,但是需要完成这个pr #2249 ,有其他的建议吗

import { Middleware, App } from '@midwayjs/decorator';
import { IMiddleware } from '@midwayjs/core';

import { NextFunction, Context, Application } from '@midwayjs/grpc';

@Middleware()
export default class AccessLogMiddleware
  implements IMiddleware<Context, NextFunction>
{
  @App()
  app: Application;

  resolve() {
    return async (ctx: Context, next: NextFunction) => {
      // 输出请求日志
      ctx.logger.info('<--- requestQuery %j', ctx.request);
      try {
        const result = await next();
        ctx.logger.info('---> responseBody %j', result);
        return result;
      } catch (error) {
        ctx.logger.error('request error', error);
      }
    };
  }
}

@czy88840616
Copy link
Member

容我思考一下,似乎可以设计一种不干预业务逻辑流程的切面,只做记录使用。

@ddzyan
Copy link
Contributor Author

ddzyan commented Aug 18, 2022

我看这个 @grpc/grpc-js 中 ctx 对象上也有 request 属性,只是声明的时候没有定义,导致无法使用

@github-actions
Copy link

This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

@github-actions github-actions bot locked as resolved and limited conversation to collaborators Aug 21, 2023
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Development

No branches or pull requests

2 participants