@jsstudio/development-api-interceptor
Version:
development-api-interceptor
77 lines • 2.98 kB
JavaScript
import { VALIDATION } from '../../constants';
import { ValidationError } from '../../error-handling';
export class Relationship {
/**
* Validate if relationship valid or not.
*
* @param {JsonSchema} jsonSchema - Json object received from frontend .
* @returns { boolean} isValid .
*/
isRelationshipValid(jsonSchema) {
try {
const tables = jsonSchema.tables;
for (const table of tables) {
if (!table.relationships) {
continue;
}
table.relationships.forEach((relation) => {
const associatedColObj = this.getAssociatedTableCol(tables, relation.associated_table, relation.associated_column);
const foreignColObj = this.getForeignKeyCol(table, relation.foreign_key_column);
this.isColTypeSame(foreignColObj, associatedColObj);
});
}
}
catch (err) {
throw new ValidationError(err);
}
return true;
}
/**
* Check if Associated table and column exist or not.
*
* @param {Table} tables - Table array object .
* @param {string} table - AssociatedTable string value .
* @param {string} columnName - Associated table column name .
* @returns {object} tableCol .
*/
getAssociatedTableCol(tables, table, columnName) {
const tableValue = tables.find((o) => o.table_name === table);
const tableCol = tableValue === null || tableValue === void 0 ? void 0 : tableValue.columns.find((o) => o.entity_name === columnName);
if (!tableCol) {
throw new Error(VALIDATION.ASSOCIATED_TABLE_NOT_FOUND);
}
return tableCol;
}
/**
* Check if foreign key column exist or not .
*
* @param {Table} table - table string value .
* @param {string} foreignKey - table column name .
* @returns {object} foreignColObj .
*/
getForeignKeyCol(table, foreignKey) {
const foreignColObj = table.columns.find((o) => o.entity_name === foreignKey);
if (!foreignColObj) {
throw new Error(VALIDATION.FOREIGN_KEY_COL_NOT_FOUND);
}
return foreignColObj;
}
/**
* Check if foreign key column and associated table column type same .
*
* @param {Column} foreignColObj - table string value .
* @param {Column} associatedColObj - table column name .
* @returns {boolean} .
*/
isColTypeSame(foreignColObj, associatedColObj) {
var _a;
if (foreignColObj.type !== associatedColObj.type) {
throw new Error(VALIDATION.ASSOCIATED_TABLE_COL_TYPE_MISMATCH);
}
if (!((_a = foreignColObj.constraints) === null || _a === void 0 ? void 0 : _a.FOREIGN_KEY)) {
throw new Error(VALIDATION.FOREIGN_KEY_CONSTRAINT_MISSING);
}
return true;
}
}
//# sourceMappingURL=Relationship.js.map