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

56 lines
1.7 KiB
JavaScript
Raw Permalink Normal View History

2019-12-11 14:01:01 +00:00
const UserError = require('vn-loopback/util/user-error');
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;
2018-12-19 07:42:07 +00:00
let tableName = this.modelName;
let schema = null;
2018-12-19 07:42:07 +00:00
if (model.settings && model.settings.mysql) {
let tableSplit = model.settings.mysql.table.split('.');
tableName = tableSplit.pop();
schema = tableSplit.pop() || null;
}
2019-12-11 14:01:01 +00:00
let property = properties[column];
2019-12-11 14:01:01 +00:00
if (!property)
throw new UserError(`Column does not exist`);
2019-12-11 14:01:01 +00:00
let columnName = property.mysql
? property.mysql.columnName
: column;
2019-12-11 14:01:01 +00:00
let columnInfo = await this.rawSql(
`SELECT column_type columnType
FROM information_schema.columns
WHERE table_name = ?
2018-12-19 07:42:07 +00:00
AND table_schema = IFNULL(?, DATABASE())
AND column_name = ?`,
[tableName, schema, columnName]
);
2019-12-11 14:01:01 +00:00
if (!columnInfo || !columnInfo[0])
throw new UserError(`Cannot fetch column values`);
let setValues;
2019-12-11 14:01:01 +00:00
setValues = columnInfo[0].columnType
.replace(/^set\((.*)\)$/i, '$1')
.replace(/'/g, '')
.match(new RegExp(/(\w+)+/, 'ig'));
let values = [];
setValues.forEach(setValue => {
values.push({value: setValue});
});
return values;
};
};