koa会话从上下文访问存储客户端连接

xxhby3vn  于 2021-06-09  发布在  Redis
关注(0)|答案(1)|浏览(355)

我使用nodejs和koa作为框架,加上koa会话和koa redis。

import Koa from 'koa';
...
import session from 'koa-session';
import redisStore from 'koa-redis';

const app = new Koa();
app.keys = ["cookieKeys"];
app.use(session({
  maxAge: 5184000000,
  store: redisStore({url: 'redis://localhost:6379'})
}, app));

...
const server = app.listen(1339, () => {
  console.log(`Server listening on port: 1339`);
});

export default server;

现在可以设置 ctx.session.key = "value"; 然后得到 ctx.sessios.key; 因为连接已经建立。
如何访问其他模块中koa会话存储上使用的相同redis客户端?现在我正在创建一个新连接:

import { Context, Next, Middleware } from 'koa';
import redis from 'koa-redis';

export default async (ctx: Context, next: Next): Promise<Middleware> => {
    try {
        return await next();
    } catch (err) {
        if (err.status !== 401) {
            throw err;
        }
        const redisClient = await redis({url: 'redis://localhost:6379'}).client;
        const tokenAccess = ctx.cookies.get('tokenAccess', {signed: true});
        const tokenRefresh = ctx.session.tokenRefresh;
        ...

        const isRefreshTokenRevoked = Number.isInteger(await redisClient.zrank('blacklist', tokenRefresh));
        await redisClient.quit();
        if (isRefreshTokenRevoked) {
            throw err;
        }
        ...
    }
}

我在上下文中找到了这个属性 ctx.session._sessCtx.store.client . 为此目的使用此属性是否正确?

mbzjlibv

mbzjlibv1#

我想我的问题跳过了一步。我用一个 db.js 文件并将我的redis连接放在那里,比如:

import { redisURI } from './config';
import Redis from 'koa-redis';

export const redisStore = Redis({url: redisURI});

所以现在我可以导入这个连接并在上重新使用 index.js :

import Koa from 'koa';
...
import session from 'koa-session';
import { redisStore } from './db';
//import redisStore from 'koa-redis';

const app = new Koa();
app.keys = ["cookieKeys"];
app.use(session({
  maxAge: 5184000000,
  store: redisStore
//store: redisStore({url: 'redis://localhost:6379'})
}, app));

...
const server = app.listen(1339, () => {
  console.log(`Server listening on port: 1339`);
});

export default server;

在另一个模块上导入:

import { Context, Next, Middleware } from 'koa';
import { redisStore } from './db';

export default async (ctx: Context, next: Next): Promise<Middleware> => {
    try {
        return await next();
    } catch (err) {
        if (err.status !== 401) {
            throw err;
        }
        //const redisClient = await redis({url: 'redis://localhost:6379'}).client;
        const tokenAccess = ctx.cookies.get('tokenAccess', {signed: true});
        const tokenRefresh = ctx.session.tokenRefresh;
        ...
        const isRefreshTokenRevoked = Number.isInteger(await redisStore.client.zrank('blacklist', tokenRefresh));
        //const isRefreshTokenRevoked = Number.isInteger(await redisClient.zrank('blacklist', tokenRefresh));
        //await redisClient.quit();
        if (isRefreshTokenRevoked) {
            throw err;
        }
        ...
    }
}

相关问题