首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在流中扩展快速请求类

在流中扩展快速请求类
EN

Stack Overflow用户
提问于 2017-06-20 23:30:30
回答 2查看 1.6K关注 0票数 6

我正在使用Flow构建一个nodeJS应用程序,我需要扩展快递$请求的默认快速注释,以适应我所连接的其他字段,如.user和.session。

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

流类型速递的原始代码是:

代码语言:javascript
复制
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,然后我的所有中间件都应该使用新的属性,对吗?

代码语言:javascript
复制
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');
}

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

代码语言:javascript
复制
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

有人能解释一下这是怎么回事吗?怎么解决?

谢谢!

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-09-28 21:53:41

错误表示,需要使用express$Request (成员1)或null (成员2)类型的参数/参数,但可以看到web$Request

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

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

我开始做的是:

  1. flow-typed install express@4.x.x
  2. express_v4.x.x.js从流类型/npm/移动到流类型/(外部流类型/npm/这样它就不会被未来的流类型安装覆盖,内部流类型/ so流将自动使declare blah语句成为全局的)
  3. 就在declare class express$Request...下面(所以很容易找到,在declare module...内部使用它的位置),我说: declare class express$Request extends express$Request { user: any; isAuthenticated(): boolean; session: { loginForwardUrl: ?string; }; }

我这样做,而不是把我的自定义道具放在原来的类,以便很容易看出哪些道具是自定义的。

票数 5
EN

Stack Overflow用户

发布于 2020-12-01 10:17:53

如果您不喜欢修改原始的流类型/npm/express_v4.x.x.js,则可以使用flow 相交类型

代码语言:javascript
复制
import type {$Request} from 'express';

type MyType = {
  foo: string
}:

export type CustomRequest = $Request & {
  foo: MyType | void;
  bar: string | void
};

我喜欢这种方法,因为我可以将自己的类型定义添加到CustomRequest中。在类型化/npm/express_v4.x.x.js文件中扩展$Request时,这可能比较棘手。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44664555

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档