Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declare and use an enum in Node.js with Geddy

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?

like image 450
Sorin Adrian Carbunaru Avatar asked Mar 08 '13 19:03

Sorin Adrian Carbunaru


3 Answers

You should use objects like;

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

let object_type = kindOf.TYPE1;
like image 58
Phd. Burak Öztürk Avatar answered Oct 29 '22 11:10

Phd. Burak Öztürk


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?

like image 18
Nick Mitchinson Avatar answered Oct 29 '22 09:10

Nick Mitchinson


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;
}
like image 7
Shahar Shokrani Avatar answered Oct 29 '22 09:10

Shahar Shokrani