Declare and use an enum in Node.js with Geddy
Asked Answered
H

4

15

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?

Heelandtoe answered 8/3, 2013 at 19:23 Comment(0)
H
19

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?

Harbard answered 8/3, 2013 at 19:36 Comment(0)
B
18

You should use objects like;

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

let object_type = kindOf.TYPE1;
Boondocks answered 12/6, 2020 at 18:37 Comment(0)
C
8

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;
}
Childe answered 6/12, 2018 at 6:17 Comment(0)
A
0

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

Anglonorman answered 16/9, 2013 at 18:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.