简体   繁体   English

沿着node-express应用程序传递和更新数据

[英]Passing and updating data along node-express app

How can I pass and update data along node-express app without using DB. 如何在不使用DB的情况下沿node-express app传递和更新数据。

So I am using passport to authenticate (consider this to be in src/google-passport.js ), 所以我使用护照进行身份验证(认为这是在src / google-passport.js中 ),

passport.use(new GoogleStrategy({
    clientID: process.env.GOOGLE_CLIENT_ID,
    clientSecret: process.env.GOOGLE_CLIENT_SECRET,
    callbackURL:  process.env.GOOGLE_CALLBACK_URL,
    userProfileURL: 'https://www.googleapis.com/oauth2/v3/userinfo',
    accessType: 'offline'
  }, (accessToken, refreshToken, params, profile, cb) => { 
        let profileSort = extractProfile(profile)
         mongooeHelperFunction.findUserByEmail(profileSort.email).then(response => {
           if (!response) {
            mongooeHelperFunction.createNewUser(profileSort)
            .then(res => {
               let newRes = {...res._doc}
                newRes["accessToken"] = accessToken
                cb(null, newRes)
            })
            .catch(error => {  throw error  })
           } else {
                let newRes = {...response._doc}
                newRes["accessToken"] = accessToken
                cb(null, newRes)
           }
        })
        .catch(error => {  throw error  })
    }
))

From Passport, I am getting an access token and refresh token . 从Passport,我获得了访问令牌和刷新令牌 Usually Google access token is valid for an hour. 通常Google访问令牌有效期为一小时。

So I want to store the time when I receive my access token and If my access token is expired, I want to use a refresh token to get a new access token and then update the time after new access token is generated. 所以我想存储收到访问令牌的时间,如果我的访问令牌已过期,我想使用刷新令牌获取新的访问令牌,然后在生成新的访问令牌后更新时间。

consider an api route 考虑api路线

app.get("/something", isTokenValid, (req, res) => {

where isTokenValid is a middleware function and inside that function I could have when my passport token was created and then i could compare it with current time. 其中isTokenValid是一个中间件函数,在我创建护照令牌我可以拥有该函数,然后我可以将它与当前时间进行比较。

Aditionally if the token have expired, I have a function which would send the refresh token to get new access token and update the previous data/time of access token to the new date/time 另外,如果令牌已过期,我有一个函数可以发送刷新令牌以获取新的访问令牌,并将访问令牌的先前数据/时间更新为新的日期/时间

Question: how can I pass and update data along node-express app 问题:如何沿node-express app传递和更新数据

Create Context Object 创建上下文对象

As in your example, we add another middleware that creates context for middleware pipeline: 在您的示例中,我们添加了另一个为中间件管道创建上下文的中间件:

const initCtx = (req,res,next) => {
    req.ctx = {};
    next();
}

Then in your middleware declaration: 然后在你的中间件声明中:

    app.get("/something", [initCtx, isTokenValid], (req, res) => {

Generally this could be done as first middleware in the pipeline, at top of your middleware declarations in whole app: 通常,这可以作为管道中的第一个中间件,在整个应用程序中的中间件声明的顶部完成:

const initCtx = (req,res,next) => {
    req.ctx = {};
    next();
}
app.use(initCtx);

Passing Value into ctx 将值传递给ctx

In isTokenValid middleware where you retrieving accessToken , and its expiration time, at end of it you can pass it through. isTokenValid中间件中,您在其中检索accessToken及其到期时间,在它结束时您可以通过它。 Where access token expiration is tokenExpiration : 访问令牌到期的地方是tokenExpiration

req.ctx.tokenExpiration = tokenExpiration; req.ctx.tokenExpiration = tokenExpiration;

Using value 使用价值

In middleware that takes care of refreshing tokens : 在处理刷新令牌的中间件中:

 app.get("/something", [initCtx, isTokenValid], (req, res) => {
       const tokenExpiration = req.ctx.tokenExpiration; // you have token expiration time that you can compare and apply required logic in refreshing token middleware

Original Reply and Explanation 原始答复和解释

You can assign property ctx (context object) to express req object and pass through it information between middlewares. 您可以指定属性ctx (上下文对象)来表达req对象,并在中间件之间传递信息。 Then you will be able to check specific keys in this object in downstream middlewares and apply required logic. 然后,您将能够在下游中间件中检查此对象中的特定键并应用所需的逻辑。

ctx object could be created by first middlewares in the pipeline (this one often also checks requestId from headers and assigns it to ctx as well, so all actions within context of same request could be easily traced ) ctx对象可以由管道中的第一个中间件创建(这个通常也会从头部检查requestId并将其分配给ctx ,因此可以轻松跟踪同一请求的上下文中的所有操作)

If token is valid you can assign req.ctx.tokenExpiration , and then in another middlewares check if there need to refresh it. 如果令牌有效,您可以分配req.ctx.tokenExpiration ,然后在另一个中间件中检查是否需要刷新它。

By the way Koa and Loopback frameworks work with ctx object out of the box. 顺便说一下,Koa和Loopback框架可以与ctx对象一起使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM