Question

For my model I want to have an enumeration as a datatype, but I don't know how to do that. I couldn't find anything helpful in the documentation from geddyjs.org or with google.

A model could be defined like this:

var fooModel= function () {
  this.defineProperties({
    fooField: {type: 'datatype'},
    .............................
   });
}

Where and how should I define the enumeration and how do I use it?

Était-ce utile?

La solution

Remember that Node is just javascript, and javascript does not (to the best of my knowledge) have enums. You can however fake it, which is discussed here: Enums in JavaScript?

Autres conseils

You should use objects like;

const kindOf = {
    TYPE1: 'type1',
    TYPE2: 'type2',
    TYPE3: 'type3'
}

let object_type = kindOf.TYPE1;

My preferred Enum package for node is https://www.npmjs.com/package/enum.

Here is a basic usage (copied from documentation):

// use it as module
var Enum = require('enum');

// or extend node.js with this new type
require('enum').// define an enum with own values

var myEnum = new Enum({'A': 1, 'B': 2, 'C': 4});

And then you can use for example a simple switch case statement like:

let typeId = 2;

switch (typeId) {
    case myEnum.A.value:
        //Do something related to A.
    break;
    case myEnum.B.value:
        //Do something related to B.
    break;
    case myEnum.C.value:
        //Do something related to C.
    break;
    default:
       //Throw error
    break;
}

There are modules out there that do this, one of which is https://npmjs.org/package/simple-enum (simple one I created)

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top