Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/ts models #56

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
.idea/
.angular/
4 changes: 4 additions & 0 deletions angular-crud/.npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@

# Ignores TypeScript files, but keeps definitions.
!*.ts
!*.d.ts
1,303 changes: 214 additions & 1,089 deletions angular-crud/package-lock.json

Large diffs are not rendered by default.

22 changes: 11 additions & 11 deletions angular-crud/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,21 +18,21 @@
"author": "Manfred Steyer",
"license": "MIT",
"schematics": "./src/collection.json",
"dependencies": {
"@angular-devkit/core": "^16.1.8",
"@angular-devkit/schematics": "^16.1.8",
"@angular/cdk": "^16.1.7",
"@schematics/angular": "^16.1.8",
"json5": "^2.2.0",
"typescript": "~5.1.3"
},
"devDependencies": {
"@types/jasmine": "^3.10.3",
"@types/jasmine": "~4.3.0",
"@types/json5": "0.0.30",
"@types/node": "^17.0.15",
"@types/node": "^16.11.7",
"chalk": "^4.1.2",
"istanbul": "0.4.5",
"jasmine": "^4.0.2",
"typescript": "^4.5.5"
},
"dependencies": {
"json5": "^2.2.0",
"@angular-devkit/core": "^13.2.2",
"@angular-devkit/schematics": "^13.2.2",
"@angular/cdk": "^13.2.1",
"@schematics/angular": "^13.2.2"
"jasmine": "^4.0.0"
},
"repository": {
"type": "git",
Expand Down
16 changes: 8 additions & 8 deletions angular-crud/src/collection.json
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
{
"schematics": {
"menu": {
"aliases": [ "crud-module" ],
"factory": "./crud-module/index#generate",
"description": "Generates a crud module",
"schema": "./crud-module/schema.json"
}
"$schema": "../node_modules/@angular-devkit/schematics/collection-schema.json",
"schematics": {
"crud-module": {
"factory": "./crud-module/index#generate",
"description": "Generates a crud module",
"schema": "./crud-module/schema.json"
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { FormArray, FormControl, FormGroup, Validators } from "@angular/forms";

export class <%= classify(name) %> {

static getModelForm(): FormGroup {

return new FormGroup({
<% for (let field of model.fields) { %>
<%=field.name%>: new FormControl({ value: '' <%if (field.disabled) { %>, disabled: true <% }%>}<%if (field.required) { %>, [Validators.required]<% }%>),
<% } %>
});
}
}
12 changes: 11 additions & 1 deletion angular-crud/src/crud-module/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import { CrudModel } from './model';
import { capitalize } from '@angular-devkit/core/src/utils/strings';
import { getWorkspace } from '@schematics/angular/utility/workspace';
import { addModuleImportToModule } from '@angular/cdk/schematics';
import { enrichWithTsModel } from '../utils/crud-model-utils';

export const BOOTSTRAP = 'bootstrap';
export const MATERIAL = 'material';
Expand Down Expand Up @@ -63,15 +64,24 @@ export function generate(options: CrudOptions): Rule {
const appPath = `${project?.sourceRoot}/app`;

const modelFile = `${appPath}/${options.name}/${options.model}`;
const modelBuffer = host.read(modelFile);
const tsModelFile = `${appPath}/${options.name}/${options.modelTs}`;

if(!host.exists(modelFile) && !host.exists(tsModelFile)) {
throw new SchematicsException(`No model file exists.`);
}

const modelBuffer = host.read(modelFile);
if (modelBuffer === null) {
throw new SchematicsException(`Model file ${options.model} does not exist.`);
}

const modelJson = modelBuffer.toString('utf-8');
const model = JSON5.parse(modelJson) as CrudModel;

if(host.exists(tsModelFile)) {
enrichWithTsModel(model, tsModelFile);
}

// add imports to app.module.ts
addModuleImportToModule(host,
`${appPath}/app.module.ts`,
Expand Down
18 changes: 9 additions & 9 deletions angular-crud/src/crud-module/index_spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,14 +73,14 @@ describe('Angular CRUD Schematics', () => {
// add model file
tree.create('/projects/crudtest/src/app/hotel/model.json', JSON.stringify(model));

appTree = await schematicRunner.runExternalSchematicAsync('@schematics/angular', 'workspace', workspaceOptions, tree).toPromise();
appTree = await schematicRunner.runExternalSchematicAsync('@schematics/angular', 'application', appOptions, appTree).toPromise();
appTree = await schematicRunner.runExternalSchematic('@schematics/angular', 'workspace', workspaceOptions, tree);
appTree = await schematicRunner.runExternalSchematic('@schematics/angular', 'application', appOptions, appTree);
});

it('should create hotel-list component files', (done) => {
const files = ['hotel-list.component.html', 'hotel-list.component.spec.ts', 'hotel-list.component.ts'];
const hotelListPath = '/projects/crudtest/src/app/hotel/hotel-list/';
schematicRunner.runSchematicAsync('crud-module', defaultOptions, appTree).toPromise().then(tree => {
schematicRunner.runSchematic('crud-module', defaultOptions, appTree).then(tree => {
files.forEach(f => {
const path = `${hotelListPath}${f}`;
expect(tree.exists(path)).toEqual(true);
Expand All @@ -91,7 +91,7 @@ describe('Angular CRUD Schematics', () => {

it('should use Bootstrap by default', (done) => {
const hotelListPath = '/projects/crudtest/src/app/hotel/hotel-list/hotel-list.component.html';
schematicRunner.runSchematicAsync('crud-module', defaultOptions, appTree).toPromise().then(tree => {
schematicRunner.runSchematic('crud-module', defaultOptions, appTree).then(tree => {
const listTemplate = tree.readContent(hotelListPath);
expect(listTemplate).toContain(`class="table table-centered table-hover mb-0"`);
expect(listTemplate).toContain(`class="btn btn-primary"`);
Expand All @@ -102,7 +102,7 @@ describe('Angular CRUD Schematics', () => {
it('should create hotel-edit component files', (done) => {
const files = ['hotel-edit.component.html', 'hotel-edit.component.spec.ts', 'hotel-edit.component.ts'];
const hotelListPath = '/projects/crudtest/src/app/hotel/hotel-edit/';
schematicRunner.runSchematicAsync('crud-module', defaultOptions, appTree).toPromise().then(tree => {
schematicRunner.runSchematic('crud-module', defaultOptions, appTree).then(tree => {
files.forEach(f => {
const path = `${hotelListPath}${f}`;
expect(tree.exists(path)).toEqual(true);
Expand All @@ -112,7 +112,7 @@ describe('Angular CRUD Schematics', () => {
});

it('should add routes', (done) => {
schematicRunner.runSchematicAsync('crud-module', defaultOptions, appTree).toPromise().then(tree => {
schematicRunner.runSchematic('crud-module', defaultOptions, appTree).then(tree => {
const routingModule = tree.readContent('/projects/crudtest/src/app/hotel/hotel.routes.ts');
expect(routingModule).toContain(`path: 'hotels'`);
expect(routingModule).toContain(`path: 'hotels/:id'`);
Expand All @@ -121,7 +121,7 @@ describe('Angular CRUD Schematics', () => {
});

it('should import the module in the app module file', (done) => {
schematicRunner.runSchematicAsync('crud-module', defaultOptions, appTree).toPromise().then(tree => {
schematicRunner.runSchematic('crud-module', defaultOptions, appTree).then(tree => {
const appModule = tree.readContent('/projects/crudtest/src/app/app.module.ts');
expect(appModule).toMatch(/.\/hotel\/hotel.module/);
expect(appModule).toMatch(/HotelModule/);
Expand All @@ -133,7 +133,7 @@ describe('Angular CRUD Schematics', () => {
const bootstrapOptions = {...defaultOptions};
bootstrapOptions.style = 'bootstrap';

schematicRunner.runSchematicAsync('crud-module', bootstrapOptions, appTree).toPromise().then(tree => {
schematicRunner.runSchematic('crud-module', bootstrapOptions, appTree).then(tree => {
const hotelList = tree.readContent('/projects/crudtest/src/app/hotel/hotel-list/hotel-list.component.html');
expect(hotelList).toMatch(/<table class="table/);

Expand All @@ -147,7 +147,7 @@ describe('Angular CRUD Schematics', () => {
const materialOptions = {...defaultOptions};
materialOptions.style = 'material';

schematicRunner.runSchematicAsync('crud-module', materialOptions, appTree).toPromise().then(tree => {
schematicRunner.runSchematic('crud-module', materialOptions, appTree).then(tree => {
const hotelList = tree.readContent('/projects/crudtest/src/app/hotel/hotel-list/hotel-list.component.html');
expect(hotelList).toMatch(/<table mat-table/);

Expand Down
15 changes: 13 additions & 2 deletions angular-crud/src/crud-module/model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,25 @@ export interface Field {
name: string;
isId: boolean;
readonly: boolean;
type: TypeOptions;
disabled: boolean;
required: boolean;
type: TypeOptions | string;
control: ControlOptions | string;
label: string;
default: any;
validation: string;
show: ShowOptions[] | string;
property: Property;
}

export type TypeOptions = 'text' | 'number' | 'date';
export type ShowOptions = 'filter' | 'list' | 'insert' | 'update';
export type ControlOptions = 'text';
export type ControlOptions = 'text' | 'number' | 'date' | 'datetime-local' | 'time' | 'month' | 'checkbox' | 'password' | 'email';
export type PropertyTypeOptions = 'string' | 'number' | 'boolean' | 'Date';

export type Property = {
name: string;
signature: any;
type: PropertyTypeOptions | string;
nullable: boolean;
}
10 changes: 10 additions & 0 deletions angular-crud/src/crud-module/schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,16 @@
"default": "model.json",
"description": "Model describing the crud form"
},
"modelTs":{
"type":"string",
"default": "model.ts",
"description": "TypeScript model file for the crud form"
},
"modelType":{
"type":"string",
"default": "json",
"description": "JSON or TS model file (values 'json' or 'ts')"
},
"style": {
"type": "string",
"default": "paper-dashboard"
Expand Down
2 changes: 2 additions & 0 deletions angular-crud/src/crud-module/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,7 @@ export interface CrudOptions {
module: string;
export: boolean;
model: string;
modelTs: string;
modelType: string;
style: string;
}
89 changes: 88 additions & 1 deletion angular-crud/src/utils/crud-model-utils.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { CrudModel, Field, ShowOptions } from '../crud-module/model';
import { CrudModel, Field, Property, ShowOptions } from '../crud-module/model';
import { SchematicsException } from '@angular-devkit/schematics/src/exception/exception';
import { camelize } from '@angular-devkit/core/src/utils/strings';
import * as ts from "typescript";

export function filterField(field: Field): boolean {

Expand Down Expand Up @@ -49,3 +50,89 @@ export function pluralize(str: string): string {
) && str + 's'
);
}

export function enrichWithTsModel(model: CrudModel, tsModelFile: string) {

let program = ts.createProgram([tsModelFile], { allowJs: false });
const sourceFile = program.getSourceFile(tsModelFile);

ts.forEachChild(sourceFile!, node => {
if (ts.isTypeAliasDeclaration(node)) {
node.forEachChild(child => {
if (ts.isTypeLiteralNode(child)) {
child.forEachChild(prop => {
if (ts.isPropertySignature(prop)) {

prop.forEachChild(propChild => {
if (ts.isIdentifier(propChild)) {

let signature = prop.getFullText(sourceFile);
let propName = propChild.escapedText.toString();

// does the field with the same name exist? if so, merge
let field = model.fields.find(f => f.name === propName);

// is id?
let isId = false;
if (signature.indexOf('id') > 0) {
isId = true;
}

let propType = 'string'; // property type
let htmlInputType = 'text'; // html control
let nullable = false;

if (signature.indexOf('boolean') > 0) {
propType = 'boolean';
htmlInputType = 'checkbox';
}

if (signature.indexOf('number') > 0) {
propType = 'number';
htmlInputType = 'number';
}

if (signature.indexOf('date') > 0 || signature.indexOf('Date') > 0) {
propType = 'Date';
htmlInputType = 'date';
}

if (signature.indexOf('| null') > 0) {
nullable = true;
}

let property: Property = { name: propName, signature, type: propType, nullable };

if (field === null || field === undefined) {
field = {
name: propName,
isId: isId,
readonly: false,
disabled: false,
required: false,
type: htmlInputType,
control: htmlInputType,
label: propName,
default: '',
validation: '',
show: '',
property,
};

model.fields.push(field);

} else {
field.control = htmlInputType;
field.isId = isId;
field.property = property;
}
}
})
}
})
}
})
}
})

}
19 changes: 5 additions & 14 deletions angular-crud/tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
{
"compilerOptions": {
"baseUrl": "tsconfig",
"lib": [
"es2017",
"dom"
],
"lib": ["es2018", "dom"],
"declaration": true,
"module": "commonjs",
"moduleResolution": "node",
"noEmitOnError": true,
Expand All @@ -19,15 +17,8 @@
"sourceMap": true,
"strictNullChecks": true,
"target": "es6",
"types": [
"jasmine",
"node"
]
"types": ["jasmine", "node"]
},
"include": [
"src/**/*"
],
"exclude": [
"src/*/files/**/*"
]
"include": ["src/**/*"],
"exclude": ["src/*/files/**/*"]
}
3 changes: 1 addition & 2 deletions demo/angular.json
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,5 @@
}
}
}
},
"defaultProject": "demo"
}
}
Loading