3

I need to convert a Symbol to string in order to create a unique key in Redis, but I can't.

I've already tried to use Object.toString(obj) and String(obj) but I get errors or [Object] results¡.

This is the controller

const name = req.params.name;
let obj;
obj.data.name = {
          [Op.like]: '%' + name + '%'
        };
}

This is redis controller where I use stringify. I use obj as a parameter.

const hashed = crypto.createHmac('sha256', secretHashKey)
          .update(JSON.stringify(obj))
          .digest('hex');

I expect an output based on my parameter 'obj' but now it's not getting it so I can't create unique keys for different values.

2 Answers 2

1

Maybe a little bit too late, but I hope that somebody else find this useful.

I was looking for something exactly as you: use with Sequelize in a Redis cache.

Mine is TypeScript, convert to JavaScript just by removing the typings.

export function JsonStringifyWithSymbols(object: any, clean?: boolean): string {
    return JSON.stringify(object, (_, value) => {
        if (typeof value === 'object' && !Array.isArray(value) && value !== null) {
            const props = [...Object.getOwnPropertyNames(value), ...Object.getOwnPropertySymbols(value)];
            const replacement: Record<string, any> = {};
            for (const k of props) {
                if (typeof k === 'symbol') {
                    replacement[`Symbol:${Symbol.keyFor(k)}`] = value[k];
                } else {
                    replacement[k] = value[k];
                }
            }
            return replacement;
        }
        return value;
    });
}
Sign up to request clarification or add additional context in comments.

Comments

0

If you're meaning these Symbols you can't convert them to a string.

They're created to be unique and "unreversable", so you can use them also for keep more "secure" various properties or methods. Example:

const a = Symbol('a')

class Foobar {
  constructor (_a) {
    this[a] = _a
  }
}

const foobar = new Foobar('aaa')
console.log(foobar) // output: Foobar { [Symbol(a)]: 'aaa' }

const fake = Symbol('a')
foobar[fake] = 'fake'
console.log(foobar) // output: Foobar { [Symbol(a)]: 'aaa', [Symbol(a)]: 'fake' }

You can't corrupt the original one, unless you have the original Symbol.

Another example (info about the JSON.stringify here):

const a = Symbol('a')

const foobar = {}
foobar[a] = 'aaa'

console.log(foobar) // output: { [Symbol(a)]: 'aaa' }
console.log(JSON.stringify(foobar)) // output: {} 

const fake = Symbol('a')
foobar[fake] = 'fake'
console.log(foobar) // output: { [Symbol(a)]: 'aaa', [Symbol(a)]: 'fake' }

Hope these info will help you.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.