node.js - 在 Flow 中扩展快速请求类

标签 node.js flowtype flow-typed

我正在使用 Flow 构建一个 nodeJS 应用程序,我需要扩展 express$Request 的默认 express 注释以适应我添加的其他字段,例如 .user 和 .session。

不幸的是,当我尝试这样做并创建接受这种新请求类型的中间件时,Flow 崩溃了,我不确定我做错了什么。

来自流式的 express 的原始代码是:

declare class express$Request extends http$IncomingMessage mixins express$RequestResponseBase {
    ....
}

declare type express$Middleware = 
    ((req: express$Request, res: express$Response, next: express$NextFunction) => mixed) |
    ((error: ?Error, req: express$Request, res: express$Response, next: express$NextFunction) => mixed);

所以我想我会扩展 express$Request 然后我所有的中间件都应该使用新属性,对吧?

declare class web$Request extends express$Request {
    user: any,
    isAuthenticated(): boolean,
    session: {
      loginForwardUrl: ?string,
    },
}

const authenticationMiddleware: express$Middleware = (
  req: web$Request, res, next
): mixed => {
  if (req.isAuthenticated()) {
    return next();
  }

  req.session.loginForwardUrl = req.originalUrl;
  return res.redirect('/auth/login/google');
}

不幸的是,这会产生 super 复杂的错误:

function
This type is incompatible with
union: function type(s): web/src/index.js:113
Member 1:
function type: flow-typed/npm/express_v4.x.x.js:97
Error:
web$Request: web/src/index.js:114
This type is incompatible with the expected param type of
express$Request: flow-typed/npm/express_v4.x.x.js:97
Member 2:
function type: flow-typed/npm/express_v4.x.x.js:98
Error:
web$Request: web/src/index.js:114
This type is incompatible with an argument type of
null: flow-typed/npm/express_v4.x.x.js:98

谁能解释这里发生了什么以及如何解决它?

谢谢!

最佳答案

错误表明类型为 express$Request(成员 1)或 null(成员 2)的参数/参数是预期的,但是 web$Request 被看见了。

不幸的是,Flow 不支持扩展/覆盖流/lib 类型:

https://github.com/facebook/flow/issues/396

我开始做的是:

  1. 流式安装 express@4.x.x
  2. express_v4.x.x.js 从 flow-typed/npm/移动到 flow-typed/(在 flow-typed/npm/之外,这样它就不会被 future 的 flow-typed 安装覆盖,并且在 flow-typed/中,因此 flow 会自动使 declare blah 语句成为全局的)
  3. declare class express$Request... 的正下方(因此很容易找到,所以它在 declare module... 中使用的位置之上,我把:

    声明类 express$Request extends express$Request { 用户:任何; isAuthenticated(): bool 值; session : { loginForwardUrl: ?string; }; }

我这样做而不是将我的自定义 Prop 放在原始类上,以便很容易看出哪些 Prop 是自定义的。

关于node.js - 在 Flow 中扩展快速请求类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44664555/

相关文章:

javascript - fs.readFile 函数响应未定义...有什么想法吗?

javascript - 如何导出从另一个文件导入的流类型定义?

reactjs - 扩展流 `type Props` 以包含来自另一个组件的 prop 类型?

javascript - Flow Error Out 中的 Webpack 路径

javascript - 在现有项目中设置流程

javascript - 将对象解构与流类型相结合

flowtype - 错误 : react-navigation_v1. x.x/CONTRIBUTING.md:意外的文件名

node.js - 如何在 Typescript 的方法装饰器上创建编译错误?

javascript - $lookup 之后的 Mongodb $near

javascript - 从 HTTP POST 请求中检索 JSON