UNPKG

@adonis-cockpit/lucid-infer

Version:

Package to infer Lucid model attributes by parsing AST tree

42 lines (41 loc) 1.39 kB
import { loadFile } from "magicast"; import { fileURLToPath } from "node:url"; import { getColumnsFromAST, getColumnType, isClassPropertyNullable, } from "./ast.js"; function loadModule(specifier) { const url = new URL(import.meta.resolve(specifier)); return loadFile(fileURLToPath(url)); } export async function inferModel(path) { const { default: Model } = (await import(path)); const columns = []; const mod = await loadModule(path); const propertiesAST = getColumnsFromAST(mod.$ast); for (const [key, definition] of Model.$columnsDefinitions) { const property = propertiesAST.find((f) => f.key.type === "Identifier" && f.key.name === key); if (!property) { console.warn(`Could not find property ${key}`); // TODO: ERror continue; } columns.push(inferColumn(key, property, definition)); } for (const [key, definition] of Model.$relationsDefinitions) { columns.push({ kind: "relationship", key, type: definition.type, options: definition, }); } return columns; } function inferColumn(key, property, options) { const { type, isArray } = getColumnType(property); return { kind: "column", key, type, isArray, optional: isClassPropertyNullable(property), options, }; }