@barcidev/ngx-autogen 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,366 @@
1
+ # ngx-autogen
2
+
3
+ [![Language: English](https://img.shields.io/badge/lang-en-blue.svg)](README.md)
4
+ [![Language: Spanish](https://img.shields.io/badge/lang-es-yellow.svg)](README.es.md)
5
+
6
+ **ngx-autogen** is a set of schematics designed to optimize and standardize the workflow in Angular projects. This library provides code generation tools that follow best practices, allowing developers to save time on repetitive tasks and architecture configuration.
7
+
8
+ ## 🚀 Features
9
+
10
+ The project is initially launched with a focus on state management, but is designed to grow:
11
+
12
+ - **Store Schematic**: Our first available schematic. It allows you to automatically generate the entire structure needed for a store based on signals (NGRX-Signals), facilitating the quick and scalable integration of state management in your applications.
13
+
14
+ ## 📅 Coming Soon
15
+
16
+ **ngx-autogen** is a project in continuous evolution. New tools and schematics will be progressively added to cover more aspects of Angular development, such as:
17
+
18
+ - Generation of services and utilities.
19
+ - Scaffolding for advanced components.
20
+
21
+ ## 📦 Installation
22
+
23
+ You can install the package in your Angular project using Angular CLI so that the project is automatically configured with the necessary dependencies:
24
+
25
+ ```bash
26
+ ng add ngx-autogen
27
+ ```
28
+
29
+ ## 🛠️ Usage
30
+
31
+ ### Generate a Store
32
+
33
+ #### Properties
34
+
35
+ - `name` (required): name of the store.
36
+ - `pk` (optional): name of the primary key. If not specified, the one specified during the schematic installation process will be used; otherwise, `id` will be used.
37
+ - `path` (optional): path of the store. If not specified, the one specified during the schematic installation process will be used; otherwise, `src/app/core` will be used.
38
+
39
+ #### Example
40
+
41
+ ```bash
42
+ ng g app-store --name="user" --pk="cod"
43
+ ```
44
+
45
+ This will create the files `user.model.ts`, `user.service.ts`, `user.store.ts` within the `src/app/core/user` folder, the `entity.model.ts` file if it doesn't exist within the `src/app/core/common/entity` folder, and the `index.ts` file within the `src/app/core` folder.
46
+
47
+ ```bash
48
+ common/
49
+ └── entity/
50
+ └── entity.model.ts
51
+ user/
52
+ ├── user.service.ts
53
+ ├── user.model.ts
54
+ └── user.store.ts
55
+ index.ts
56
+ ```
57
+
58
+ The `index.ts` file will export everything necessary so that the store can be imported and used anywhere in the application.
59
+
60
+ ```bash
61
+ /* USER */
62
+ export * from './user/user.model';
63
+ export * from './user/user.service';
64
+ export * from './user/user.store';
65
+ ```
66
+
67
+ The `entity.model.ts` file contains the interfaces and types necessary for state and form management.
68
+
69
+ ```bash
70
+ import { FormControl } from '@angular/forms';
71
+
72
+ export interface EntityStatus {
73
+ addError?: Error | null;
74
+ addLoading?: boolean;
75
+ removeError?: Error | null;
76
+ removeLoading?: boolean;
77
+ error: Error | null;
78
+ idsRemoving?: (number | string)[];
79
+ idSelected?: null | number | string;
80
+ idsUpdating?: (number | string)[];
81
+ loaded: boolean;
82
+ loading: boolean;
83
+ selectedError?: Error | null;
84
+ selectedLoading?: boolean;
85
+ updateError?: Error | null;
86
+ updateLoading?: boolean;
87
+ }
88
+
89
+ export type FormGroupType<T> = {
90
+ [K in keyof T]: FormControl<T[K]>;
91
+ };
92
+ ```
93
+
94
+ The `user.model.ts` file contains the data model interface.
95
+
96
+ ```bash
97
+ import { FormGroupType } from '../common/form/form.model';
98
+
99
+ export interface AddUser {
100
+ }
101
+
102
+ export type AddUserForm = FormGroupType<AddUser>;
103
+
104
+ export interface UserDto {
105
+ cod: number;
106
+ }
107
+
108
+ export type UpdateUser = Partial<UserDto> & Pick<UserDto, 'cod'>;
109
+
110
+ export interface UserRequest{}
111
+ ```
112
+
113
+ The `user.service.ts` file contains the service responsible for business logic.
114
+
115
+ ```bash
116
+ import { Injectable } from '@angular/core';
117
+ import { Observable, of } from 'rxjs';
118
+ import {
119
+ AddUser,
120
+ UserDto,
121
+ UpdateUser
122
+ } from './user.model';
123
+
124
+ @Injectable({
125
+ providedIn: 'root'
126
+ })
127
+ export class UserService {
128
+
129
+ addUser$(entity: AddUser): Observable<number> {
130
+ return of(0);
131
+ }
132
+
133
+ removeUser$(cod: number): Observable<boolean> {
134
+ return of(true);
135
+ }
136
+
137
+ getUsers$(): Observable<UserDto[]> {
138
+ return of([]);
139
+ }
140
+
141
+ updateUser$(entity: UpdateUser): Observable<boolean> {
142
+ return of(true);
143
+ }
144
+ }
145
+ ```
146
+
147
+ The `user.store.ts` file contains the store responsible for state management.
148
+
149
+ ```bash
150
+ import { computed, inject } from '@angular/core';
151
+ import { patchState, signalStore, type, withComputed, withHooks, withMethods, withState } from '@ngrx/signals';
152
+ import {
153
+ addEntity,
154
+ entityConfig,
155
+ removeEntity,
156
+ setAllEntities,
157
+ updateEntity,
158
+ withEntities
159
+ } from '@ngrx/signals/entities';
160
+ import { rxMethod } from '@ngrx/signals/rxjs-interop';
161
+ import { catchError, of, pipe, switchMap, tap } from 'rxjs';
162
+
163
+ import { EntityStatus } from '../common/entity/entity.model';
164
+ import {
165
+ UserDto,
166
+ AddUser,
167
+ UpdateUser
168
+ } from './user.model';
169
+ import { UserService } from './user.service';
170
+
171
+ const initialStatus: EntityStatus = {
172
+ error: null,
173
+ loaded: false,
174
+ loading: false,
175
+ };
176
+
177
+ const config = entityConfig({
178
+ entity: type<UserDto>(),
179
+ selectId: (entity) => entity.cod,
180
+ });
181
+
182
+ export const UserStore = signalStore(
183
+ withEntities(config),
184
+ withState({
185
+ _status: initialStatus,
186
+ }),
187
+ withComputed(({ entityMap, _status }) => ({
188
+ users: computed(() => Object.values(entityMap())),
189
+ userSeleccionado: computed(() => {
190
+ const cod = _status().idSelected;
191
+ return cod ? entityMap()[cod] : null;
192
+ }),
193
+ error: computed(() => _status().error),
194
+ loaded: computed(() => _status().loaded),
195
+ loading: computed(() => _status().loading),
196
+ loadingRemove: computed(
197
+ () => (cod?: number) =>
198
+ (cod ? _status().idsRemoving?.includes(cod) : _status().removeLoading) || false
199
+ ),
200
+ loadingUpdate: computed(
201
+ () => (cod?: number) =>
202
+ (cod ? _status().idsUpdating?.includes(cod) : _status().updateLoading) || false
203
+ ),
204
+ })),
205
+ withMethods((store, userService = inject(UserService)) => ({
206
+ addUser: rxMethod<AddUser>(
207
+ pipe(
208
+ tap(() => {
209
+ patchState(store, { _status: { ...store._status(), addLoading: true } });
210
+ }),
211
+ switchMap((entity) => {
212
+ return userService.addUser$(entity).pipe(
213
+ tap((cod) => {
214
+ patchState(store, addEntity({ ...entity, cod }, config), {
215
+ _status: {
216
+ ...store._status(),
217
+ addLoading: false,
218
+ error: null,
219
+ },
220
+ });
221
+ }),
222
+ catchError(() => {
223
+ patchState(store, {
224
+ _status: {
225
+ ...store._status(),
226
+ addLoading: false,
227
+ error: new Error('Error adding user'),
228
+ },
229
+ });
230
+ return of(entity);
231
+ })
232
+ );
233
+ })
234
+ )
235
+ ),
236
+ loadUsers: rxMethod<void>(
237
+ pipe(
238
+ tap(() => {
239
+ patchState(store, { _status: { ...store._status(), loading: true } });
240
+ }),
241
+ switchMap(() => {
242
+ return userService.getUsers$().pipe(
243
+ tap((response) => {
244
+ patchState(store, setAllEntities(response, config), {
245
+ _status: {
246
+ ...store._status(),
247
+ error: null,
248
+ loaded: true,
249
+ loading: false,
250
+ },
251
+ });
252
+ }),
253
+ catchError(() => {
254
+ patchState(store, {
255
+ _status: {
256
+ ...store._status(),
257
+ error: new Error('Error loading users'),
258
+ loading: false,
259
+ },
260
+ });
261
+ return of([]);
262
+ })
263
+ );
264
+ })
265
+ )
266
+ ),
267
+ removeUser: rxMethod<number>(
268
+ pipe(
269
+ tap((cod) => {
270
+ patchState(store, {
271
+ _status: {
272
+ ...store._status(),
273
+ removeLoading: true,
274
+ idsRemoving: [...(store._status().idsRemoving || []), cod],
275
+ },
276
+ });
277
+ }),
278
+ switchMap((cod) => {
279
+ return userService.removeUser$(cod).pipe(
280
+ tap((success) => {
281
+ if (success) {
282
+ const idsRemoving = store._status().idsRemoving || [];
283
+ patchState(store, removeEntity(cod), {
284
+ _status: {
285
+ ...store._status(),
286
+ removeLoading: false,
287
+ error: null,
288
+ idsRemoving: idsRemoving.filter((idRemoving) => idRemoving !== cod),
289
+ },
290
+ });
291
+ } else {
292
+ throw new Error('Error deleting user');
293
+ }
294
+ }),
295
+ catchError(() => {
296
+ const idsRemoving = store._status().idsRemoving || [];
297
+ patchState(store, {
298
+ _status: {
299
+ ...store._status(),
300
+ removeLoading: false,
301
+ error: new Error('Error deleting user'),
302
+ idsRemoving: idsRemoving.filter((idRemoving) => idRemoving !== cod),
303
+ },
304
+ });
305
+ return of(false);
306
+ })
307
+ );
308
+ })
309
+ )
310
+ ),
311
+ updateUser: rxMethod<UpdateUser>(
312
+ pipe(
313
+ tap((entity) => {
314
+ patchState(store, {
315
+ _status: {
316
+ ...store._status(),
317
+ idsUpdating: [...(store._status().idsUpdating || []), entity.cod],
318
+ updateLoading: true,
319
+ },
320
+ });
321
+ }),
322
+ switchMap((entity) => {
323
+ return userService.updateUser$(entity).pipe(
324
+ tap((success) => {
325
+ if (success) {
326
+ const idsUpdating = store._status().idsUpdating || [];
327
+ patchState(store, updateEntity({ changes: entity, id: entity.cod }, config), {
328
+ _status: {
329
+ ...store._status(),
330
+ error: null,
331
+ idsUpdating: idsUpdating.filter((idUpdating) => idUpdating !== entity.cod),
332
+ updateLoading: false,
333
+ },
334
+ });
335
+ } else {
336
+ throw new Error('Error updating user');
337
+ }
338
+ }),
339
+ catchError(() => {
340
+ const idsUpdating = store._status().idsUpdating || [];
341
+ patchState(store, {
342
+ _status: {
343
+ ...store._status(),
344
+ error: new Error('Error updating user'),
345
+ idsUpdating: idsUpdating.filter((idUpdating) => idUpdating !== entity.cod),
346
+ updateLoading: false,
347
+ },
348
+ });
349
+ return of(false);
350
+ })
351
+ );
352
+ })
353
+ )
354
+ ),
355
+ })),
356
+ withHooks({
357
+ onInit: (store) => {
358
+ store.loadUsers();
359
+ },
360
+ })
361
+ );
362
+ ```
363
+
364
+ ## 📄 License
365
+
366
+ This project is under the [MIT](LICENSE) license.
package/package.json ADDED
@@ -0,0 +1,61 @@
1
+ {
2
+ "name": "@barcidev/ngx-autogen",
3
+ "version": "0.1.0",
4
+ "description": "A collection of Angular schematics for essential functionalities.",
5
+ "main": "dist/index.js",
6
+ "scripts": {
7
+ "build": "tsc -p tsconfig.json",
8
+ "test": "npm run build && jasmine src/**/*_spec.js",
9
+ "prepublishOnly": "npm run build"
10
+ },
11
+ "files": [
12
+ "src/**/*.js",
13
+ "src/**/*.template",
14
+ "src/**/*.d.ts",
15
+ "src/**/schema.json",
16
+ "src/collection.json",
17
+ "README.md",
18
+ "LICENSE"
19
+ ],
20
+ "keywords": [
21
+ "angular",
22
+ "schematics",
23
+ "state-management",
24
+ "ngrx",
25
+ "signals",
26
+ "scaffolding"
27
+ ],
28
+ "author": "Jorge Palacio Barcinilla",
29
+ "license": "MIT",
30
+ "schematics": "./src/collection.json",
31
+ "repository": {
32
+ "type": "git",
33
+ "url": "https://github.com/jpalacio09/ngx-autogen.git"
34
+ },
35
+ "publishConfig": {
36
+ "access": "public"
37
+ },
38
+ "homepage": "https://github.com/jpalacio09/ngx-autogen#readme",
39
+ "bugs": {
40
+ "url": "https://github.com/jpalacio09/ngx-autogen/issues"
41
+ },
42
+ "funding": {
43
+ "type": "github",
44
+ "url": "https://github.com/sponsors/jpalacio09"
45
+ },
46
+ "engines": {
47
+ "node": ">=16.0.0"
48
+ },
49
+ "dependencies": {
50
+ "@angular-devkit/core": "^20.3.13",
51
+ "@angular-devkit/schematics": "^20.3.13",
52
+ "@schematics/angular": "^21.0.4",
53
+ "typescript": "~5.9.2"
54
+ },
55
+ "devDependencies": {
56
+ "@types/jasmine": "~5.1.0",
57
+ "@types/node": "^20.17.19",
58
+ "copyfiles": "^2.4.1",
59
+ "jasmine": "^5.0.0"
60
+ }
61
+ }
@@ -0,0 +1,15 @@
1
+ {
2
+ "$schema": "../node_modules/@angular-devkit/schematics/collection-schema.json",
3
+ "schematics": {
4
+ "ng-add": {
5
+ "description": "Ng add schematic for ngx-autogen.",
6
+ "factory": "./ng-add/index#ngAdd",
7
+ "schema": "./ng-add/schema.json"
8
+ },
9
+ "app-store": {
10
+ "description": "Adds NgRx Store to the Angular application with signal support.",
11
+ "factory": "./ngrx/store/index#signalStore",
12
+ "schema": "./ngrx/store/schema.json"
13
+ }
14
+ }
15
+ }
@@ -0,0 +1,3 @@
1
+ import { Rule } from "@angular-devkit/schematics";
2
+ import { NgAddSchemaOptions } from "./schema";
3
+ export declare function ngAdd(options: NgAddSchemaOptions): Rule;
@@ -0,0 +1,77 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ngAdd = ngAdd;
4
+ const schematics_1 = require("@angular-devkit/schematics");
5
+ const tasks_1 = require("@angular-devkit/schematics/tasks");
6
+ function ngAdd(options) {
7
+ return (tree, _context) => {
8
+ const packagePath = "/package.json";
9
+ const buffer = tree.read(packagePath);
10
+ if (!buffer) {
11
+ throw new schematics_1.SchematicsException("Could not find package.json. Make sure you are in the root of an Angular project.");
12
+ }
13
+ const packageJson = JSON.parse(buffer.toString());
14
+ // 1. Obtener la versión de Angular Core
15
+ const angularCoreVer = packageJson.dependencies["@angular/core"] ||
16
+ packageJson.devDependencies["@angular/core"];
17
+ if (!angularCoreVer) {
18
+ throw new schematics_1.SchematicsException("The version of @angular/core could not be determined. Please ensure that Angular is installed in your project.");
19
+ }
20
+ const mainVersion = parseInt(angularCoreVer.replace(/[^\d.]/g, "").split(".")[0], 10);
21
+ // 2. Validación: NgRx Signals requiere Angular 16+ (v17+ recomendado)
22
+ if (mainVersion < 16) {
23
+ _context.logger.error(`❌ Error: ngx-essentials requires Angular v16 or higher. Detected: v${mainVersion}`);
24
+ return tree; // Stop execution
25
+ }
26
+ // 3. Mapear versión de NgRx (NgRx suele ir a la par con Angular)
27
+ const ngrxVersion = `^${mainVersion}.0.0`;
28
+ _context.logger.info(`📦 Configuring dependencies for Angular v${mainVersion}...`);
29
+ // 4. Modificar package.json
30
+ const packageName = "ngx-autogen";
31
+ // Inyectar dependencias compatibles
32
+ packageJson.dependencies = Object.assign(Object.assign({}, packageJson.dependencies), { "@ngrx/signals": ngrxVersion });
33
+ // Mover a devDependencies si es necesario
34
+ if (packageJson.dependencies[packageName]) {
35
+ const currentVer = packageJson.dependencies[packageName];
36
+ delete packageJson.dependencies[packageName];
37
+ packageJson.devDependencies = Object.assign(Object.assign({}, packageJson.devDependencies), { [packageName]: currentVer });
38
+ }
39
+ packageJson.dependencies = sortObjectKeys(packageJson.dependencies);
40
+ packageJson.devDependencies = sortObjectKeys(packageJson.devDependencies);
41
+ tree.overwrite(packagePath, JSON.stringify(packageJson, null, 2));
42
+ // 5. Configurar angular.json (Collections y Primary Key)
43
+ updateAngularJson(tree, options);
44
+ // 6. Tarea de instalación
45
+ _context.addTask(new tasks_1.NodePackageInstallTask());
46
+ return tree;
47
+ };
48
+ }
49
+ function sortObjectKeys(obj) {
50
+ return Object.keys(obj)
51
+ .sort()
52
+ .reduce((result, key) => {
53
+ result[key] = obj[key];
54
+ return result;
55
+ }, {});
56
+ }
57
+ function updateAngularJson(tree, options) {
58
+ const path = "/angular.json";
59
+ const buffer = tree.read(path);
60
+ if (!buffer)
61
+ return;
62
+ const workspace = JSON.parse(buffer.toString());
63
+ if (!workspace.cli)
64
+ workspace.cli = {};
65
+ const collections = workspace.cli.schematicCollections || [];
66
+ if (!collections.includes("ngx-autogen")) {
67
+ collections.push("ngx-autogen");
68
+ workspace.cli.schematicCollections = collections;
69
+ }
70
+ if (!workspace.schematics)
71
+ workspace.schematics = {};
72
+ workspace.schematics["ngx-autogen:all"] = {
73
+ pk: options.pk,
74
+ };
75
+ tree.overwrite(path, JSON.stringify(workspace, null, 2));
76
+ }
77
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,3 @@
1
+ export interface NgAddSchemaOptions {
2
+ pk: string;
3
+ }
@@ -0,0 +1,14 @@
1
+ {
2
+ "$schema": "http://json-schema.org/schema",
3
+ "$id": "ng-add-schema",
4
+ "type": "object",
5
+ "properties": {
6
+ "pk": {
7
+ "type": "string",
8
+ "description": "The name of the default Primary Key (e.g., id, cod, uuid); default is 'id'.",
9
+ "x-prompt": "What is the name of the default Primary Key (e.g., id, cod, uuid)?",
10
+ "default": "id"
11
+ }
12
+ },
13
+ "required": ["pk"]
14
+ }
@@ -0,0 +1,22 @@
1
+ import { FormControl } from '@angular/forms';
2
+
3
+ export interface EntityStatus {
4
+ addError?: Error | null;
5
+ addLoading?: boolean;
6
+ error: Error | null;
7
+ idSelected?: null | number | string;
8
+ idsRemoving?: (number | string)[];
9
+ idsUpdating?: (number | string)[];
10
+ loaded: boolean;
11
+ loading: boolean;
12
+ removeError?: Error | null;
13
+ removeLoading?: boolean;
14
+ selectedError?: Error | null;
15
+ selectedLoading?: boolean;
16
+ updateError?: Error | null;
17
+ updateLoading?: boolean;
18
+ }
19
+
20
+ export type FormGroupType<T> = {
21
+ [K in keyof T]: FormControl<T[K]>;
22
+ };
@@ -0,0 +1,14 @@
1
+ import { FormGroupType } from '../common/entity/entity.model';
2
+
3
+ export interface Add<%= classify(name) %> {
4
+ }
5
+
6
+ export type Add<%= classify(name) %>Form = FormGroupType<Add<%= classify(name) %>>;
7
+
8
+ export interface <%= classify(name) %>Dto {
9
+ <%= pk %>: number;
10
+ }
11
+
12
+ export type Update<%= classify(name) %> = Partial<<%= classify(name) %>Dto> & Pick<<%= classify(name) %>Dto, '<%= pk %>'>;
13
+
14
+ export interface <%= classify(name) %>Request{}
@@ -0,0 +1,29 @@
1
+ import { Injectable } from '@angular/core';
2
+ import { Observable, of } from 'rxjs';
3
+ import {
4
+ Add<%= classify(name) %>,
5
+ <%= classify(name) %>Dto,
6
+ Update<%= classify(name) %>
7
+ } from './<%= dasherize(name) %>.model';
8
+
9
+ @Injectable({
10
+ providedIn: 'root'
11
+ })
12
+ export class <%= classify(name) %>Service {
13
+
14
+ add<%= classify(name) %>$(entity: Add<%= classify(name) %>): Observable<number> {
15
+ return of(0);
16
+ }
17
+
18
+ remove<%= classify(name) %>$(<%= pk %>: number): Observable<boolean> {
19
+ return of(true);
20
+ }
21
+
22
+ get<%= classify(pluralize(name)) %>$(): Observable<<%= classify(name) %>Dto[]> {
23
+ return of([]);
24
+ }
25
+
26
+ update<%= classify(name) %>$(entity: Update<%= classify(name) %>): Observable<boolean> {
27
+ return of(true);
28
+ }
29
+ }