@processpuzzle/base-entity 0.7.0 → 0.7.2

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 CHANGED
@@ -5,8 +5,8 @@
5
5
  [![Node version](https://img.shields.io/npm/v/%40processpuzzle%2Fbase-entity?style=flat)](https://www.npmjs.com/package/@processpuzzle/base-entity)
6
6
 
7
7
  ## Introduction
8
-
9
- Base-Entity is a run-time form and table generator base on Entity Descriptor and Entity Attribute Descriptor. To make it short:
8
+
9
+ `@processpuzzle/base-entity` is a run-time form and table generator for Angular, driven by two descriptor objects: a **Base Entity Descriptor** that describes the entity (and its related entities), and **Base Entity Attribute Descriptors** that specify how each attribute is presented.
10
10
 
11
11
  <a href="https://github.com/ZsZs/processpuzzle/blob/develop/docs/base-entity-bird-eye-view.png?raw=true">
12
12
  <img src="https://github.com/ZsZs/processpuzzle/blob/develop/docs/base-entity-bird-eye-view.png?raw=true" width=600px alt="Bird eye view">
@@ -14,116 +14,202 @@ Base-Entity is a run-time form and table generator base on Entity Descriptor and
14
14
 
15
15
  From these **Inputs:**
16
16
 
17
- - Entity Descriptor => Describes the subject entity and probable it's associated entities.
18
- - Entity Attribute Descriptor => Specifies the presentation style of each attribute.
17
+ - **Entity Descriptor** – describes the subject entity and (optionally) its linked entities.
18
+ - **Entity Attribute Descriptors** – specify the presentation style of each attribute.
19
19
 
20
- generates these **Outputs:**
20
+ the library generates these **Outputs:**
21
21
 
22
- - Reactive Form Component => Reactive Angular form, created dynamically, run-time.
23
- - Angular Material Table => Angular Material Table, create dynamically, run-time.
22
+ - A **Reactive Angular Form** built dynamically at run-time.
23
+ - An **Angular Material Table** built dynamically at run-time.
24
24
 
25
- Of course this is a very coarse, abstract view of the functionality. In more detail, the library offers the following classes:
25
+ The diagram below shows the main classes the library exposes:
26
26
 
27
27
  <a href="https://github.com/ZsZs/processpuzzle/blob/develop/docs/base-entity-architectural-context.png?raw=true">
28
28
  <img src="https://github.com/ZsZs/processpuzzle/blob/develop/docs/base-entity-architectural-context.png?raw=true" width=600px alt="Architectural Context">
29
29
  </a>
30
30
 
31
- - Base Entity => interface to implement from the subject Custom Entity
32
- - Base Entity Service => abstract class to extend by the Custom Service to deliver the Custom Entity
33
- - Base Entity Mapper => abstract class to extend to map the Custom Entity from/to DTO
34
- - Base Entity Store => signal store for the components generated by the library
35
- - Base Entity Container => Angular component to contain the generated table and form
36
- - Base Entity List => Angular Material Table to display the Custom Entities in a table form
37
- - Base Entity Form => Reactive Angular Form to facilitate CRUD on a single custom object
31
+ - **BaseEntity** – interface your custom entity implements (only requires an `id`).
32
+ - **BaseEntityRestService / BaseEntityFirestoreService** – concrete CRUD services to extend; both implement the `BaseEntityService` contract.
33
+ - **BaseEntityMapper** – interface for translating between your DTO and your entity. `SimpleEntityMapper` covers the trivial case.
34
+ - **BaseEntityStore** – `@ngrx/signals` store feature backing the generated components. Composes with `BaseEntityTabsStore`, `BaseEntityContainerStore`, and the singleton `BaseFormNavigatorStore`.
35
+ - **BaseEntityFacade** – optional one-stop class that wires entity, mapper, service, store, and descriptor together.
36
+ - **BaseEntityContainerComponent** – host component that renders the table and the form together.
37
+ - **BaseEntityListComponent** – Angular Material table of your entities.
38
+ - **BaseEntityFormComponent** – reactive form for CRUD on a single entity.
38
39
 
39
40
  ## Usage
40
41
 
41
- Basically the library user has to extend a couple of base classes. These extensions are minimal, it't more like configuration of the base class.
42
+ To plug the library into your application you provide an entity class, a mapper, a service, a store, and a descriptor. Each step is a small amount of configuration — most of the behavior comes from the base classes.
42
43
 
43
44
  <a href="https://github.com/ZsZs/processpuzzle/blob/develop/docs/base-entity-design_overview.png?raw=true">
44
45
  <img src="https://github.com/ZsZs/processpuzzle/blob/develop/docs/base-entity-design_overview.png?raw=true" width=600px alt="Design Overview">
45
46
  </a>
46
47
 
47
- ### Extend **Base Entity**
48
+ The snippets below are taken from the [TestEntity sample in the testbed](https://github.com/ZsZs/processpuzzle/tree/develop/apps/processpuzzle-testbed/src/app/content/base-forms/test-entity).
49
+
50
+ ### 1. Define your entity
48
51
 
49
- As the **Base Entity** interface defines only an ID, you are almost completely free how you define your Entity to be managed by the library. For an example see the [sample entities](https://github.com/ZsZs/processpuzzle/tree/develop/apps/processpuzzle-testbed/src/app/content/base-forms), like TestEntity, TestEntityComponent and TrunkData.
52
+ `BaseEntity` only requires `id: string`. Anything else is yours to model freely.
50
53
 
51
54
  ```typescript
52
55
  export class TestEntity implements BaseEntity {
53
- id: string = uuidv4();
54
- name? = '';
55
- description?: string = '';
56
- boolean?: boolean;
57
- number?: number;
58
- date?: Date;
59
- selectable?: number;
56
+ readonly id: string;
57
+ private name: string;
58
+ private description: string | undefined;
59
+ private boolean: boolean;
60
+ private number: number;
61
+ private date: Date;
62
+ private lookup: string;
60
63
  private enumValue: TestEnum;
64
+ private artifact?: ArtifactAttr;
65
+ private tags?: Array<string>;
66
+ private components?: Array<TestEntityComponent>;
67
+
68
+ constructor(id?: string, name?: string /* … */) {
69
+ this.id = id ?? uuidv4();
70
+ // …
71
+ }
61
72
  }
62
73
  ```
63
74
 
64
- The Base Entity Mapper increases the flexibility how you can define your Entity to be managed even more as it offers a mapping between the mostly predefined DTOs and the Entity in the front end. For an example see the [sample mappers](https://github.com/ZsZs/processpuzzle/tree/develop/apps/processpuzzle-testbed/src/app/content/base-forms), TestEntityMapper, TestEntityComponentMapper and TrunkDataMapper.
75
+ ### 2. Provide a mapper
76
+
77
+ A mapper translates between the DTO returned by the backend and your entity class. `SimpleEntityMapper` works when no translation is needed; otherwise implement `BaseEntityMapper<Entity>` and use the exported `getEnumKeyByValue` / `getEnumValueByKey` helpers for enum round-tripping. Child entities are mapped by delegating to their own mappers.
78
+
65
79
  ```typescript
66
80
  @Injectable({ providedIn: 'root' })
67
81
  export class TestEntityMapper implements BaseEntityMapper<TestEntity> {
82
+ private readonly componentMapper = inject(TestEntityComponentMapper);
83
+
68
84
  fromDto(dto: any): TestEntity {
69
- return new TestEntity(dto.id, dto.name, dto.description, dto.boolean, dto.number, dto.date, getEnumKeyByEnumValue<TestEnum>(TestEnum, dto.enumValue));
85
+ return new TestEntity(
86
+ dto.id, dto.name, dto.description, dto.boolean, dto.number, dto.date, dto.lookup,
87
+ getEnumKeyByValue<TestEnum>(TestEnum, dto.enumValue),
88
+ dto.artifact,
89
+ dto.tags,
90
+ dto.components?.map((c: any) => this.componentMapper.fromDto(c)),
91
+ );
70
92
  }
71
93
 
72
94
  toDto(entity: TestEntity): any {
73
- return entity;
95
+ const dto = { ...entity } as any;
96
+ return { ...dto, enumValue: getEnumValueByKey<TestEnum>(TestEnum, dto.enumValue) };
74
97
  }
75
98
  }
76
-
77
- function getEnumKeyByEnumValue<E>(myEnum: { [key: number]: string }, enumValue: any): E | undefined {
78
- return Object.values(myEnum)[enumValue] as E;
79
- }
80
99
  ```
81
- To be able to configure the rather generic Data Service (BaseEntityService), you have to subclass it and provide in the constructor the required mapper, configuration key and resource path for the base URL.
82
- For an example see the [sample data services](https://github.com/ZsZs/processpuzzle/tree/develop/apps/processpuzzle-testbed/src/app/content/base-forms), like TestEntityService, TestEntityComponentService and TrunkDataService.
100
+
101
+ ### 3. Extend the data service
102
+
103
+ Pick `BaseEntityRestService` for an HTTP backend or `BaseEntityFirestoreService` for Firestore. Pass the mapper, a configuration key that resolves to the backend root URL, and the resource path.
104
+
83
105
  ```typescript
84
106
  @Injectable({ providedIn: 'root' })
85
- export class TestEntityService extends BaseEntityService<TestEntity> {
107
+ export class TestEntityService extends BaseEntityRestService<TestEntity> {
86
108
  constructor(protected override entityMapper: TestEntityMapper) {
87
- super(entityMapper, 'TEST_SERVICE_ROOT', 'test-entity');
109
+ super(entityMapper, 'BACKEND_SERVICE_ROOT', 'test-entity');
88
110
  }
89
111
  }
90
112
  ```
91
- Of course, you are free to define your own data access methods as much they are needed by your custom Signal Store or other objects.
92
113
 
93
- The core piece of this library's domain layer is the BaseEntityStore, a signal store, which is used by the generated angular components.
94
- The BaseEntityStore provides methods for CRUD operations and enhanced usability status. For details see the diagram above, or the [source code](https://github.com/ZsZs/processpuzzle/blob/develop/libs/base-entity/src/lib/base-entity.store.ts)
95
- To be able to use it, you just have to define your own signal store, with the usage of BaseEntityStore (Signal Store Feature).
114
+ You can add custom data-access methods on top of the inherited CRUD operations.
115
+
116
+ ### 4. Compose a signal store
117
+
118
+ The generated components read and write through an `@ngrx/signals` store. `BaseEntityStore` provides CRUD state and the Material table data source; the other features add tab state, container filtering, and form-navigation behavior.
119
+
96
120
  ```typescript
97
121
  export const TestEntityStore = signalStore(
98
122
  { providedIn: 'root' },
99
123
  BaseEntityStore<TestEntity>(TestEntity, () => inject(TestEntityService)),
100
- BaseFormNavigatorStore<TestEntity>(TestEntity),
101
124
  BaseEntityTabsStore(),
102
125
  BaseEntityContainerStore(),
103
126
  );
104
127
  ```
105
- The BaseFormNavigatorStore, BaseEntityTabsStore and BaseEntityContainerStore provides additional enhanced usability services, which will be explained in the Design section.
128
+
129
+ `BaseFormNavigatorStore` is a singleton that you do not add per entity — inject it where you need navigation between list and details views.
130
+
131
+ ### 5. Describe the attributes
132
+
133
+ Each visible field gets a `BaseEntityAttrDescriptor`. `FormControlType` covers `TEXT_BOX`, `TEXTAREA`, `CHECKBOX`, `DATE`, `DROPDOWN`, `LOOKUP`, `RADIO`, `TAGS`, `ARTIFACT`, `COMPONENTS`, `FOREIGN_KEY`, `LABEL`, `TITLE`, and `FLEX_BOX`. Use `FlexboxDescriptor` to lay attributes out in rows and columns, and `linkedEntityType` to attach a related entity's descriptor (used by `LOOKUP`, `FOREIGN_KEY`, and nested `COMPONENTS`).
134
+
135
+ ```typescript
136
+ function createTestEntityAttrDescriptors(): AbstractAttrDescriptor[] {
137
+ const nameAttr = new BaseEntityAttrDescriptor('name', FormControlType.TEXT_BOX, 'Name', undefined, true);
138
+ nameAttr.required = true;
139
+ const descriptionAttr = new BaseEntityAttrDescriptor('description', FormControlType.TEXTAREA, 'Description');
140
+ const booleanAttr = new BaseEntityAttrDescriptor('boolean', FormControlType.CHECKBOX, 'Boolean');
141
+ const numberAttr = new BaseEntityAttrDescriptor('number', FormControlType.TEXT_BOX, 'Number', undefined, false, { inputType: 'number' });
142
+ const dateAttr = new BaseEntityAttrDescriptor('date', FormControlType.DATE, 'Date', undefined, false, { inputType: 'date' });
143
+ const lookupAttr = new BaseEntityAttrDescriptor('lookup', FormControlType.LOOKUP, 'Lookup');
144
+ const enumAttr = new BaseEntityAttrDescriptor('enumValue', FormControlType.DROPDOWN, 'Enum', selectables);
145
+ const componentsAttr = new BaseEntityAttrDescriptor('components', FormControlType.COMPONENTS, 'Components');
146
+
147
+ lookupAttr.linkedEntityType = createTrunkDataDescriptor();
148
+ componentsAttr.linkedEntityType = createTestEntityComponentDescriptor();
149
+
150
+ const column1 = new FlexboxDescriptor([nameAttr, descriptionAttr, booleanAttr], FlexDirection.COLUMN);
151
+ const column2 = new FlexboxDescriptor([numberAttr, dateAttr, lookupAttr, enumAttr, componentsAttr], FlexDirection.COLUMN);
152
+ const layout = new FlexboxDescriptor([column1, column2], FlexDirection.CONTAINER);
153
+ layout.style = { 'column-gap': '20px' };
154
+ return [layout];
155
+ }
156
+
157
+ let cachedDescriptor: BaseEntityDescriptor | undefined;
158
+
159
+ export function createTestEntityDescriptor(): BaseEntityDescriptor {
160
+ if (cachedDescriptor) return cachedDescriptor;
161
+ cachedDescriptor = new BaseEntityDescriptor({ entityName: 'Test Entity', attrDescriptors: [] });
162
+ cachedDescriptor.attrDescriptors = createTestEntityAttrDescriptors();
163
+ return cachedDescriptor;
164
+ }
165
+ ```
166
+
167
+ A few notes:
168
+
169
+ - Caching the descriptor in a module-level variable keeps a single instance shared across components and breaks circular references between bidirectionally linked entities.
170
+ - `BaseEntityDescriptor` takes an options object (`{ entityName, attrDescriptors, store?, entityTitle? }`); `store` and `entityTitle` are usually set later in the host component.
171
+
172
+ ### 6. Render the container
173
+
174
+ Pass the descriptor to `BaseEntityContainerComponent` and attach the store. The container then drives both the list and the form views.
106
175
 
107
176
  ```typescript
108
- const selectables = Object.keys(TestEnum)
109
- .filter((key: any) => parseInt(key) >= 0)
110
- .map((key: string) => ({ key: key, value: TestEnum[key as keyof typeof TestEnum] }));
111
-
112
- const nameAttr = new BaseEntityAttrDescriptor('name', FormControlType.TEXT_BOX, 'Name', undefined, true);
113
- const descriptionAttr = new BaseEntityAttrDescriptor('description', FormControlType.TEXTAREA, 'Description');
114
- const booleanAttr = new BaseEntityAttrDescriptor('boolean', FormControlType.CHECKBOX, 'Boolean');
115
- const numberAttr = new BaseEntityAttrDescriptor('number', FormControlType.TEXT_BOX, 'Number', undefined, false, { inputType: 'number' });
116
- const dateAttr = new BaseEntityAttrDescriptor('date', FormControlType.DATE, 'Date', undefined, false, { inputType: 'date' });
117
- const enumAttr = new BaseEntityAttrDescriptor('enumValue', FormControlType.DROPDOWN, 'Enum', selectables);
118
-
119
- export const testEntityDescriptors: BaseEntityAttrDescriptor<TestEntity>[] = [nameAttr, descriptionAttr, booleanAttr, numberAttr, dateAttr, enumAttr];
120
-
121
- const baseEntityDescriptor: BaseEntityDescriptor = {
122
- entityName: 'Test Entity',
123
- store: this.store,
124
- attrDescriptors: testEntityAttrDescriptors,
125
- entityTitle: "this.store.currentEntity() ? this.store.currentEntity().name : ''",
126
- };
177
+ @Component({
178
+ selector: 'test-entity-container',
179
+ standalone: true,
180
+ imports: [BaseEntityContainerComponent],
181
+ template: `<base-entity-container [entityDescriptor]="baseEntityDescriptor"></base-entity-container>`,
182
+ })
183
+ export class TestEntityContainerComponent {
184
+ private store = inject(TestEntityStore);
185
+ baseEntityDescriptor: BaseEntityDescriptor;
186
+
187
+ constructor() {
188
+ this.baseEntityDescriptor = createTestEntityDescriptor();
189
+ this.baseEntityDescriptor.store = this.store;
190
+ this.baseEntityDescriptor.entityTitle = "this.store.currentEntity() ? this.store.currentEntity().name : ''";
191
+ }
192
+ }
127
193
  ```
128
194
 
195
+ ### Optional: bundle everything in a Facade
196
+
197
+ When you have many entities, `BaseEntityFacade` centralises the wiring (mapper, service, store, descriptor) so a single token can drive routed views. Extend it and declare `entityType`, `entityName`, and `attrDescriptors`; override the `create…` hooks to return your concrete classes.
198
+
199
+ ```typescript
200
+ @Injectable()
201
+ export class TestEntityFacade extends BaseEntityFacade<TestEntity> {
202
+ readonly entityType = TestEntity;
203
+ readonly entityName = 'Test Entity';
204
+ readonly attrDescriptors = createTestEntityDescriptor().attrDescriptors;
205
+
206
+ private readonly mapperRef = inject(TestEntityMapper);
207
+ private readonly serviceRef = inject(TestEntityService);
208
+
209
+ protected override createMapper() { return this.mapperRef; }
210
+ protected override createService() { return this.serviceRef; }
211
+ protected override createStoreClass(): Type<unknown> { return TestEntityStore; }
212
+ }
213
+ ```
129
214
 
215
+ The facade can then be provided through the `ACTIVE_ENTITY_FACADE` token, and `BaseEntityContainerComponent` will resolve its descriptor automatically — no per-entity container component required.