loopback-connector-mysql/lib/enumFactory.js

68 lines
1.7 KiB
JavaScript
Raw Normal View History

2016-05-03 23:52:03 +00:00
// Copyright IBM Corp. 2013,2016. All Rights Reserved.
// Node module: loopback-connector-mysql
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
2016-08-10 18:41:03 +00:00
'use strict';
const g = require('strong-globalize')();
2016-07-19 20:52:46 +00:00
const EnumFactory = function() {
2014-02-13 00:57:06 +00:00
if (arguments.length > 0) {
const Enum = function Enum(arg) {
2014-02-13 00:57:06 +00:00
if (typeof arg === 'number' && arg % 1 == 0) {
return Enum._values[arg];
} else if (Enum[arg]) {
2016-08-10 18:41:03 +00:00
return Enum[arg];
2014-02-13 00:57:06 +00:00
} else if (Enum._values.indexOf(arg) !== -1) {
return arg;
} else if (arg === null) {
return null;
} else {
return '';
}
};
const dxList = [];
// Want empty value to be at index 0 to match MySQL Enum values and
// MySQL non-strict behavior.
dxList.push('');
for (let arg in arguments) {
2014-02-13 00:57:06 +00:00
arg = String(arguments[arg]);
Object.defineProperty(Enum, arg.toUpperCase(), {
configurable: false,
enumerable: true,
value: arg,
2016-08-10 18:41:03 +00:00
writable: false,
});
2014-02-13 00:57:06 +00:00
dxList.push(arg);
}
Object.defineProperty(Enum, '_values', {
configurable: false,
enumerable: false,
value: dxList,
2016-08-10 18:41:03 +00:00
writable: false,
});
Object.defineProperty(Enum, '_string', {
configurable: false,
enumerable: false,
value: stringified(Enum),
2016-08-10 18:41:03 +00:00
writable: false,
});
2014-02-13 00:57:06 +00:00
Object.freeze(Enum);
return Enum;
} else {
2016-08-10 18:41:03 +00:00
throw g.f('No arguments - could not create {{Enum}}.');
2014-02-13 00:57:06 +00:00
}
};
function stringified(anEnum) {
const s = [];
for (const i in anEnum._values) {
2014-02-13 00:57:06 +00:00
if (anEnum._values[i] != '') {
s.push("'" + anEnum._values[i] + "'");
}
2014-02-13 00:57:06 +00:00
}
return s.join(',');
}
exports.EnumFactory = EnumFactory;