环回拦截器值被其他请求覆盖

问题描述 投票:0回答:0

我正在使用环回拦截器在控制器函数中使用它的值。

从我实现拦截器的那一刻起,我就知道每个用户请求都有不同的拦截器实例。

这是我拦截令牌的代码

`导出类 ExtractTokenInterceptor 实现 Provider { 构造函数(){}

value(): Interceptor {
    return this.intercept.bind(this);
}

async intercept<T>(
    invocationCtx: InvocationContext,
    next: () => ValueOrPromise<T>,
) {
    const req: any = await invocationCtx.get(RestBindings.Http.REQUEST, {
        optional: true,
    });
    // const req: any = await invocationCtx.parent.get(RestBindings.Http.REQUEST, { optional: true });
    const authorization = req.headers.hasOwnProperty('authorization') ? req.headers.authorization : null;
    const userName = req.headers.hasOwnProperty('x-username') ? req.headers['x-username'] : null;
    const token = authorization ? req.headers.authorization.split(' ')[1] : null;
    const referer = req.headers.referer;
    const clientIp = req.headers['x-forwarded-for'];
    invocationCtx.targetClass.prototype.token = token;
    invocationCtx.targetClass.prototype.referer = referer;
    invocationCtx.targetClass.prototype.clientIp = clientIp;
    invocationCtx.targetClass.prototype.userName = userName;
    

    if(invocationCtx.targetClass.prototype.jwt) {
        console.log('ERROR! INTERCEPTOR HAS VALUE', invocationCtx.targetClass.prototype.jwt);
    }

    if (token) {
        const decodedJwt = jwtDecode(token);
        console.log(invocationCtx.targetClass.prototype.jwt);
        invocationCtx.targetClass.prototype.jwt = decodedJwt;

        const loopCnt = 20;
        if(decodedJwt.preferred_username === 'user1') {
            let a = 0;
            const timeout = (ms) => {
                return new Promise(resolve => setTimeout(resolve, ms));
            }
            while (a < loopCnt) { // i will delay the interceptor for specific user
                await timeout(1000);
                console.log('['+a+'] user is', invocationCtx.targetClass.prototype.jwt.preferred_username);
                invocationCtx.targetClass.prototype.counter = a++;
            }
        }
    }
    

    const result = await next();
    return result;
}

}`

这里发生的事情是这样的。 我有两个名为 user1 和 user2 的用户。

两个用户都登录了。 两个用户都将触发特定端点

如果你能在我的拦截器中看到,我在 user1 拦截器中设置了延迟。

i 将根据令牌打印当前拦截器值。

然后如果 user2 将触发相同的终点,而 user1 的拦截器尚未完成,我可以看到 user1 的打印将被 user2 更改。

看看我只为 user1 延迟的代码,这样 user2 就可以继续执行控制器功能

我无法从环回中找到任何解决方案,为什么拦截器每个端点使用一个实例

interceptor loopback loopback4
© www.soinside.com 2019 - 2024. All rights reserved.