2017-09-14 1 views
1

を呼び出し、速達ミドルウェアでそれを確認しますgraphqlのためのミドルウェアの書き方私はトークン送信するすべての要求では、すべてのリゾルバの前

app.use(async (req, res, next) => { 
    const authorization = req.headers.authorization; 
    let token = null; 
    let user; 

    if (authorization) { 
    try { 
     token = jwt.verify(authorization, config.secret); 
    } catch (e) { 
    // dont work 
     throw new GraphQLError({ message: 'token damaged' }); 
    } 

    if (token) { 
     const { _id } = token; 

     user = await User.findOne({ _id }); 
    } 

    if (user) { 
     req.user = user; 
    } 
    } 

    next(); 
}); 

トークンが破損することができ、私はチェックを実行します。

try { 
     token = jwt.verify(authorization, config.secret); 
    } catch (e) { 
     throw new GraphQLError({ message: 'token damaged' }); 
    } 

クライアントアプリケーションExpressエラーに送信する必要がありますが、期待どおりに動作しません すべてのリゾルバを呼び出す前に要求引数を取るgraphqlミドルウェアを作成するオプションはありますか?今私は破損したトークンのエラーをスローしたい場合は、すべてのリゾルバでチェックを書く必要がありますか?

+0

多分これはあなたを助けることができますhttps://stackoverflow.com/questions/18700729/how-to-use-the-middleware-入国審査の前に各ルートへの確認を –

+0

https://github.com/DubFriend/graphql-resolve –

答えて

0

あなたは、単に応答し返す、次のミドルウェアを呼び出さずにすることができます

try { 
    token = jwt.verify(authorization, config.secret); 
} catch (e) { 
    res.statusCode = 401; 
    return res.end('{"errors": [{"message": "token damaged"}]}'); 
} 
関連する問題