我正在使用 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
我开始做的是:
流式安装 express@4.x.x
- 将
express_v4.x.x.js
从 flow-typed/npm/移动到 flow-typed/(在 flow-typed/npm/之外,这样它就不会被 future 的 flow-typed 安装覆盖,并且在 flow-typed/中,因此 flow 会自动使declare blah
语句成为全局的) 在
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/