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.

alvarocece
  • 41
  • 4

2 Answers2

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;
    });
}
Arsonik
  • 2,276
  • 1
  • 16
  • 24
VaioWay
  • 402
  • 1
  • 4
  • 13
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.

Andrea Franchini
  • 548
  • 4
  • 14