Skip to content

Commit

Permalink
🎨 Improving code to generate the ts models
Browse files Browse the repository at this point in the history
  • Loading branch information
contactinquid committed Oct 13, 2024
1 parent 94d6cd1 commit e5e283c
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 7 deletions.
7 changes: 7 additions & 0 deletions resources/templates/ts_model.template
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { Model } from "@tailflow/laravel-orion/lib/model";

export class {{ modelName }} extends Model<{
{{ columns }}
}> {
// Additional methods or properties can be added here
}
60 changes: 53 additions & 7 deletions src/Commands/OrionTypescriptCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -99,28 +99,74 @@ protected function getSchema(string $connection): string
}

/**
* Generate the Orion TypeScript model.
* Generate the Orion TypeScript model using a template.
*
* @param string $controller
* @param string $table
*/
protected function generateOrionModel(string $controller, string $table)
{
$modelName = Str::replaceLast('Controller', '', $controller);
$content = "import {Model} from \"@tailflow/laravel-orion/lib/model\";\n\n";
$content .= "export class $modelName extends Model<{\n";

// 1. Load the template file
$templatePath = base_path('resources/templates/ts_model.template');
if (!file_exists($templatePath)) {
$this->error("Template file not found at $templatePath.");
return;
}
$templateContent = file_get_contents($templatePath);

// 2. Generate the columns string
$columns = Schema::getColumnListing($table);
$columnsString = '';
foreach ($columns as $column) {
$type = 'string'; // You could enhance this to detect the proper TypeScript type based on the column type.
$content .= " $column: $type,\n";
$type = $this->mapColumnType($table, $column); // Map to TypeScript types
$columnsString .= " $column: $type;\n";
}

$content .= "}>\n{
// 3. Replace placeholders in the template
$replacements = [
'{{ modelName }}' => $modelName,
'{{ columns }}' => rtrim($columnsString),
];

}";
$content = str_replace(array_keys($replacements), array_values($replacements), $templateContent);

// 4. Write the output file
$outputPath = base_path("resources/js/models/$modelName.ts");
file_put_contents($outputPath, $content);
}

/**
* Map database column types to TypeScript types.
*
* @param string $table
* @param string $column
* @return string
*/
protected function mapColumnType(string $table, string $column): string
{
$type = Schema::getColumnType($table, $column);

switch ($type) {
case 'integer':
case 'bigint':
case 'smallint':
case 'tinyint':
case 'float':
case 'double':
case 'decimal':
return 'number';
case 'boolean':
return 'boolean';
case 'json':
return 'any';
case 'datetime':
case 'timestamp':
case 'date':
return 'Date';
default:
return 'string';
}
}
}

0 comments on commit e5e283c

Please sign in to comment.