adba
Version:
Any DataBase to API
58 lines (57 loc) • 1.86 kB
JavaScript
import { pascalCase } from "change-case-all";
import { t } from "dbl-utils";
/**
* Retrieve an Objection model by its table name.
*
* @param tableName - Name of the table to search for.
* @param models - Object containing available models.
* @returns The matching model or undefined.
*
* @example
* const User = getModelByTableName("users", allModels);
*/
export function getModelByTableName(tableName, models) {
return Object.values(models).find((ModelIn) => ModelIn.tableName === tableName);
}
/**
* Converts a string into PascalCase, suitable for class names.
* Handles strings in kebab-case or snake_case.
* @param str - The input string.
* @returns The converted PascalCase string.
*/
export function className(str) {
return pascalCase(str);
}
/**
* Converts JSON schema properties to the column format expected by the Table component.
*
* @param schemaProperties - Properties section of a JSON schema.
* @param required - List of required property names.
* @returns Columns in the Table component format.
*/
export function jsonSchemaToColumns(schemaProperties, required = []) {
const columns = {};
for (const [key, prop] of Object.entries(schemaProperties)) {
const column = {
name: key,
label: t(prop.title || key, "columnNames"),
};
const comment = prop.$comment;
if (comment) {
const [t, f] = comment.split(".");
column.type = t || prop.type;
if (f)
column.format = f;
}
else if (typeof prop.type === "string") {
column.type = prop.type;
}
if (typeof prop.format === "string") {
column.format = prop.format;
}
if (required.includes(key))
column.required = true;
columns[key] = column;
}
return columns;
}