Skip to content

LzxHahaha/egg-enums

Repository files navigation

egg-enums

NPM version build status Test coverage David deps Known Vulnerabilities npm download

Install

$ npm i egg-enums --save

Usage

// {app_root}/config/plugin.js
exports.enums = {
  enable: true,
  package: 'egg-enums',
};

Configuration

If you're using typescript, add import 'egg-enums'; to your index.d.ts ( go to egg document to get more information ).

In javascript there is NOTHING need to be config.

Example

// {app_root}/app/enums/letters.js
// use array to init enum
// each item's index can be used to find the item
module.exports = app => app.Enum([
  'A',
  'B',
  'C'
]);

// or

// {app_root}/app/enums/colors.js
// use object to set the values
// item can be an object, but MUST have an `id` field at the top level
module.exports = app => app.Enum({
  RED: 1,
  GREEN: 4,
  BLUE: {
    id: 5,
    name: 'blue',
    // other...
  },
});

// then you can use like this
console.log(app.enums.Letters.B === 1);       // true
console.log(app.enums.Letters[2] === 'C');    // true

console.log(app.enums.Colors.GREEN === 4);    // true
console.log(app.enums.Colors[5].name === 'blue');    // true

You can get all keys by use .$keys to get all enums.

// app.enums.Letters.$keys
[
  {
    "id": 0,
    "key": "A"
  },
  {
    "id": 1,
    "key": "B"
  },
  {
    "id": 2,
    "key": "C"
  }
]

// app.enums.Colors.$keys
[
  {
    "id": 1,
    "key": "RED"
  },
  {
    "id": 4,
    "key": "GREEN"
  },
  {
    "id": 5,
    "key": "BLUE",
    "name": "blue"
  }
]

So make sure that DO NOT use $keys to named an enum or use field key in enum items top level when you config.

Questions & Suggestions

Please open an issue here.

License

MIT

Releases

No releases published

Packages

No packages published