2017-06-20 51 views
5

我正在使用Flow構建nodeJS應用程序,我需要擴展快速$ Request的默認快速註釋以適應其他字段,例如.user和.session。在流程中擴展快速請求類

不幸的是,當我試圖做到這一點,並創建接受這種新的請求類型的中間件時,Flow嚇了一跳,我不知道我做錯了什麼。

從流量類型的快遞原來的代碼是:

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); 

,所以我想我只是延長明示$請求,然後我所有的中間件應與新屬性的作用,對不對?

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'); 
} 

不幸的是,這會產生超級複雜的錯誤:

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 

誰能解釋一下是怎麼回事,如何解決?

謝謝!

回答

3

錯誤提示參數/參數類型express$Request(成員1)或null(成員2)是預期的,但看到web$Request

不幸的是,流量不支持擴展/覆蓋流量/ lib目錄類型:

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

我已經開始做的是:

  1. flow-typed install [email protected]
  2. 移動express_v4.x.x.js從流-type/npm/to flow-typed /(外部流量類型/ npm /所以它不會被未來流程型安裝覆蓋,並且內部流量型/流量會自動生成declare blah點聲明全局)
  3. 的正下方declare class express$Request...(所以很容易找到,所以它的上面它裏面declare module...用,我就把:

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

我做到這一點,而不是把我的自定義道具的原始類,這樣很容易看到哪些道具是自定義的。

+1

錢幣,殘酷的 - 希望流將支持這更好的。謝謝! – user358829

0

如果您只是想將字段添加到請求類中,您可以像這樣擴展它。工程於[email protected]後來(我不知道這是介紹的時候):

declare class session$Request extends express$Request { 
    product: ProductDoc; 
    ip: number; // this will not work - error: [flow] number (This type is incompatible with string) 
} 

/** 
* GET /api/products/:uuid - Get product 
* 
* @property {string} req.params.uuid - The unique id of the product. 
*/ 
function get(req: session$Request, res: express$Response) { 
    // retrieve product from DB ... 
    return res.json({ data: req.product }); 
} 
+0

是的,請注意@ user358829已經用他們的'web $ Request'試過了。問題在於快遞中間件的Flow def期望'快速$ Request',而不是'web $ Request' –