56 lines
1.7 KiB
JavaScript
56 lines
1.7 KiB
JavaScript
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;
|
|
let tableName = this.modelName;
|
|
let schema = null;
|
|
|
|
if (model.settings && model.settings.mysql) {
|
|
let tableSplit = model.settings.mysql.table.split('.');
|
|
tableName = tableSplit.pop();
|
|
schema = tableSplit.pop() || null;
|
|
}
|
|
|
|
let property = properties[column];
|
|
|
|
if (!property)
|
|
throw new UserError(`Column does not exist`);
|
|
|
|
let columnName = property.mysql
|
|
? property.mysql.columnName
|
|
: column;
|
|
|
|
let columnInfo = await this.rawSql(
|
|
`SELECT column_type columnType
|
|
FROM information_schema.columns
|
|
WHERE table_name = ?
|
|
AND table_schema = IFNULL(?, DATABASE())
|
|
AND column_name = ?`,
|
|
[tableName, schema, columnName]
|
|
);
|
|
|
|
if (!columnInfo || !columnInfo[0])
|
|
throw new UserError(`Cannot fetch column values`);
|
|
|
|
let setValues;
|
|
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;
|
|
};
|
|
};
|