1
votes

I have an existing MySQL database table userdo that has a column userType of type integer, such that an administrator user is represented as value 0, and so on.

When I work with my TypeORM userdo entity object, I wish for its JSON form to represent the userType property in a string enumeration form. For example, if the userType is 0 in the table, then when serializing/deserializing to JSON (say, when getting a userdo instance as a result of a findOne() and sending it via res.json()), I want:

{
...
    userType: 'ADMIN',
...
}

There are several ways I have considered trying to do this:

  1. Using the entity enum type. This doesn't seem to solve my problem because at runtime the enum is just a normal JavaScript integer and so it is printed in the JSON as such.

  2. Use a ValueTransformer. I haven't investigated this much yet, but I believe this would entail writing some code to marshal between a set of strings ('ADMIN', ...) and respective integer values.

  3. Use the library https://github.com/typestack/class-transformer. I am not certain yet if this will achieve what I want.

1

1 Answers

0
votes

From what I know of SQL, I don't think there is a way of doing that with SQL. Which means I wouldn't think that TypeORM can do that.

Anyway, the way I would do it is to declare a const object that can do the translation for you. If you're using numbers, then maybe even an array:

const typeToWord = { 
     0: "ADMIN",
     1: "SUPERADMIN",
     /*... and so on*/
}; 
// or: ["ADMIN", "SUPERADMIN"]

const typeToNumber = {
     "ADMIN": 0,
     "SUPERADMIN": 1,
     /* ... */
};

And the idea is to use that right after the query, so the rest of your code uses the "translation", i.e "ADMIN"