Skip to content

Instantly share code, notes, and snippets.

@FredLackeyOfficial
Last active November 16, 2016 17:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save FredLackeyOfficial/543d14fa88b498b71fbffc644b0dba1c to your computer and use it in GitHub Desktop.
Save FredLackeyOfficial/543d14fa88b498b71fbffc644b0dba1c to your computer and use it in GitHub Desktop.
Brainstorming boilerplate enum template for NodeJS
/**
* Created by Fred Lackey on 11/16/16.
*/
/*
Provides maximum flexibility when dealing with enums.
SCHEMA:
var schema = new mongoose.Schema({
status : { type: String, enum: enums.TOKEN_STATUS.ids }
});
UPDATES:
token.status = enums.TOKEN_STATUS.values.CANCELED.id
token.save(function(err){
// Do something...
});
BUSINESS LOGIC:
var statuses = enums.TOKEN_STATUS.values;
var curStatus = enums.TOKEN_STATUS.getById(token.status);
if (curStatus === statuses.CANCELED) {
// Do something...
}
LOOPS:
enums.TOKEN_STATUS.keys.forEach(function(key){
// Do something
});
*/
var values = {
CANCELED: { id: 'C', name: 'Canceled' },
USED: { id: 'U', name: 'Used' },
EXPIRED: { id: 'X', name: 'Expired' }
};
var keys = [];
var items = [];
var ids = [];
Object.keys(values).forEach(function(key){
keys.push(key);
// Embed key
values[key].key = key;
var item = values[key];
items.push(item);
ids.push(item.id);
});
module.exports.keys = keys;
module.exports.items = items;
module.exports.ids = ids;
module.exports.values = ids;
module.exports.getById = function (id) {
id = (id || '').trim().toUpperCase();
return items.find(function(item){
return (id === item.id);
});
};
module.exports.getByKey = function (key) {
return values[key];
};
module.exports.getByName = function (name) {
name = (name || '').trim().toUpperCase();
return items.find(function(item){
return (name === item.name.toUpperCase());
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment