salix/services/loopback/common/methods/vn-model/getSetValues.js

51 lines
1.6 KiB
JavaScript

module.exports = Self => {
/**
* Returns a set of allowed values defined on table scheme
* @param {String} column - Model or Table column name
* @return {Array} - Array of set values
*/
Self.getSetValues = async function(column) {
let model = this.app.models[this.modelName].definition;
let properties = model.properties;
let columnName;
let tableName;
if (model.settings && model.settings.mysql)
tableName = model.settings.mysql.table;
if (properties[column]) {
columnName = column;
if (properties[column].mysql)
columnName = properties[column].mysql.columnName;
}
let findColumn = Object.keys(properties).find(prop => {
return properties[prop].mysql && properties[prop].mysql.columnName === column;
});
if (findColumn)
columnName = properties[findColumn].mysql.columnName;
let type = await this.rawSql(`
SELECT DISTINCT column_type FROM information_schema.columns
WHERE table_name = ?
AND column_name = ?`, [tableName, columnName]);
if (!type) return;
let setValues;
setValues = type[0].column_type;
setValues = setValues.replace(/set\((.*)\)/i, '$1');
setValues = setValues.replace(/'/g, '');
setValues = setValues.match(new RegExp(/(\w+)+/, 'ig'));
let values = [];
setValues.forEach(setValue => {
values.push({value: setValue});
});
return values;
};
};