Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Singleton not keeping parity in node

Tags:

node.js

Having a very very peculiar issue happening:

When i start my node application, i set my access tokens to an instance of a model like so:

index.js

    const token = new Tokens();
    token.setTokens(access_token, refresh_token);
    console.log(token.getTokens()) // WORKS

I then call the getter functions in my instance in different files.

RunSchedular.js

const tokens = Tokens.getInstance();
console.log('sched',tokens.getTokens()) //WORKS

API.js

export const POSTRequest = () => {
    const currentTokens = Tokens.getInstance();
    const refreshToken = currentTokens.getRefreshToken(); // DOES NOT WORK
    const body = {
        method: 'POST',
        headers: 
        {
            "Content-Type": "application/x-www-form-urlencoded",
            "Cache-Control": "no-cache"
        },
        body: qs.stringify({
            client_secret: clientSecret,
            client_id: clientId,
            refresh_token: refreshToken,
            grant_type: 'refresh_token',
            redirect_uri: redirectUri
        })
    };
    return body;
}

My model is like so:

let instance = null;
export default class Tokens {
    constructor() {
        if(!instance) {
            instance = this;
        }
        this.accessToken = '';
        this.refreshToken = '';
    }

    getAccessToken() {
        return this.accessToken;
    }

    setAccessToken(value) {
        this.accessToken = value;
    }

    getRefreshToken() {
        return this.refreshToken;
    }

    setRefreshToken(value) {
        this.refreshToken = value;
    }

    getTokens() {
        return { 
            accessToken: this.accessToken, 
            refreshToken: this.refreshToken
            }
        }

    setTokens(accessToken,refreshToken) {
        this.accessToken = accessToken;
        this.refreshToken = refreshToken;
    }

    static getInstance() {
        console.log('instance', instance)
        if(!instance) {
            instance = new Tokens();
        }
        return instance;
    }
};

Any ideas why this could be happening? The instance in the API.js does not return my access tokens (access token = '' as per the constructor) where as the schedular.js and index.js returns my access token fine?

Is my Model not correct?

like image 384
Mubeen Hussain Avatar asked Apr 15 '26 09:04

Mubeen Hussain


1 Answers

How are you importing the Tokens module? If the path is different, 2 different modules will be imported.

E.G.:

import { Tokens } from 'src/singletons/Tokens';

Will be a different object than:

import { Tokens } from './../singletons/Tokens';

More information about singletons in javascript.

More information about module caching in NodeJS.

like image 75
Titulum Avatar answered Apr 16 '26 23:04

Titulum