data-primals-engine 1.4.3 β†’ 1.5.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.
Files changed (50) hide show
  1. package/README.md +878 -867
  2. package/client/package-lock.json +49 -0
  3. package/client/package.json +1 -0
  4. package/client/src/App.jsx +1 -1
  5. package/client/src/App.scss +13 -3
  6. package/client/src/AssistantChat.scss +3 -2
  7. package/client/src/DashboardView.jsx +569 -569
  8. package/client/src/DataEditor.jsx +2 -2
  9. package/client/src/DataLayout.jsx +1 -8
  10. package/client/src/DataTable.jsx +26 -4
  11. package/client/src/Field.jsx +1825 -1788
  12. package/client/src/FlexDataRenderer.jsx +2 -0
  13. package/client/src/FlexTreeUtils.js +1 -1
  14. package/client/src/KPIDialog.jsx +11 -1
  15. package/client/src/ModelCreator.jsx +1 -2
  16. package/client/src/ModelCreatorField.jsx +23 -27
  17. package/client/src/ModelList.jsx +1 -1
  18. package/client/src/constants.js +1 -1
  19. package/client/src/hooks/useTutorials.jsx +62 -65
  20. package/client/src/translations.js +2 -0
  21. package/package.json +2 -1
  22. package/perf/README.md +147 -0
  23. package/perf/artillery-hooks.js +37 -0
  24. package/perf/perf-shot-hardwork.yml +84 -0
  25. package/perf/perf-shot-search.yml +45 -0
  26. package/perf/setup.yml +26 -0
  27. package/server.js +1 -1
  28. package/src/constants.js +2 -27
  29. package/src/core.js +15 -1
  30. package/src/data.js +1 -1
  31. package/src/defaultModels.js +1544 -1540
  32. package/src/email.js +5 -2
  33. package/src/engine.js +5 -3
  34. package/src/filter.js +5 -3
  35. package/src/modules/assistant/assistant.js +3 -1
  36. package/src/modules/bucket.js +12 -15
  37. package/src/modules/data/data.backup.js +11 -8
  38. package/src/modules/data/data.js +6 -3
  39. package/src/modules/data/data.operations.js +3231 -2999
  40. package/src/modules/data/data.routes.js +1821 -1785
  41. package/src/modules/data/data.scheduling.js +2 -1
  42. package/src/modules/data/data.validation.js +4 -1
  43. package/src/modules/file.js +4 -2
  44. package/src/modules/user.js +4 -1
  45. package/src/modules/workflow.js +9 -10
  46. package/src/openai.jobs.js +2 -0
  47. package/src/packs.js +22 -5
  48. package/src/providers.js +22 -7
  49. package/test/data.integration.test.js +1060 -981
  50. package/test/import_export.integration.test.js +1 -1
package/README.md CHANGED
@@ -1,867 +1,878 @@
1
- # data-primals-engine
2
- [![Node.js CI](https://github.com/anonympins/data-primals-engine/actions/workflows/node.js.yml/badge.svg?branch=main)](https://github.com/anonympins/data-primals-engine/actions/workflows/node.js.yml)
3
- ![](https://img.shields.io/npm/dw/data-primals-engine)
4
- ![](https://img.shields.io/npm/last-update/data-primals-engine)
5
- ![](https://img.shields.io/github/v/release/anonympins/data-primals-engine)
6
- ![](https://img.shields.io/github/license/anonympins/data-primals-engine)
7
-
8
- **data-primals-engine** is a powerful and flexible **Node.js** backend framework designed to accelerate development of complex data-driven applications. Built on **Express.js** and **MongoDB**, it offers dynamic data modeling, automation workflows, advanced user management, and more.
9
-
10
- > Whether you're building a CRM, e-commerce site, CMS, or SaaS platform, **data-primals-engine** provides the strong foundations so you can focus on what makes your application unique.
11
-
12
- <p align="center">
13
- <a href="https://data.primals.net/prez1.jpg" target="_blank"><img alt="Light" src="https://data.primals.net/prez1.jpg" width="35%"></a>
14
- <a href="https://data.primals.net/prez6.jpg" target="_blank"><img alt="Light" src="https://data.primals.net/prez6.jpg" width="35%"></a>
15
- <a href="https://data.primals.net/api-docs" target="_blank"><img alt="Dark" src="https://data.primals.net/prez5.jpg" width="25%"></a>
16
- </p>
17
- ---
18
-
19
- ## πŸš€ Key Features
20
-
21
- - **Visual Data Modeling**: Define and update schemas using a powerful UI Model Creator, or directly with JSON. No migrations required.
22
- - **Custom API Endpoints**: Create server-side logic and new API endpoints directly from the UI in a secure, sandboxed environment.
23
- - **Automation Workflows**: Trigger complex actions based on data events (create, update, delete) or schedules (cron).
24
- - **Advanced Querying & Aggregation**: Go beyond simple filters with a visual Condition Builder, deep relation expansion, complex lookups, and dynamic calculated fields.
25
- - **Rich UI Data Views**: Ready-to-use React components to display your data, including a powerful and configurable Data Table, a Kanban board, and a Calendar view.
26
- - **Integrated Backup & Restore**: Secure, encrypted user data backups with rotation policies, supporting both local and AWS S3 storage.
27
- - **Automatic Data Auditing**: Automatically tracks all changes (create, update, delete) for every record, providing a complete version history for auditing and traceability.
28
- - **Event-Driven & Extensible**: A core event system allows for deep customization and the easy creation of new modules or plugins.
29
- - **Authentication & Authorization**: Robust role-based access control (RBAC) and pluggable user providers.
30
- - **Built-in File Management**: Handle file uploads seamlessly with integrated support for AWS S3 storage.
31
- - **🧠 AI Integration**: Natively supports OpenAI, DeepSeek and Google Gemini models via LangChain for content generation, analysis, and more.
32
- - **🌐 Internationalization (i18n)**: Fully supports multilingual interfaces and user-specific translated data.
33
- - **πŸ“¦ Starter Packs**: Quickly bootstrap applications with pre-built data packs for CRM, e-commerce, and more.
34
- - **πŸ“„Auto-Generated API Documentation**: Interactive API documentation available via the interface or at `/api-docs`.
35
-
36
- ## 🌟 Why Choose data-primals-engine?
37
-
38
- - **Zero Boilerplate**: Focus on your business logic, not infrastructure
39
- - **Scalability**: Architecture designed for rapidly growing applications
40
- - **Modularity**: Enable/disable features as needed
41
- - **Batteries Included**: Everything you need to get started quickly
42
- - **Proven Performance**: Handles 50k+ documents efficiently
43
- - **AI Ready**: Built-in LangChain integration for main providers (OpenAI,Gemini,Anthropic,DeepSeek)
44
-
45
- ---
46
-
47
- ## βš™οΈ Requirements
48
-
49
- - Node.js β‰₯ 20
50
- - MongoDB (local or remote), see [installation guide](https://www.mongodb.com/docs/manual/installation/)
51
- - NPM or Yarn
52
-
53
- ---
54
-
55
- ## ⚑ Quick Start
56
-
57
- ### check
58
- ```bash
59
- # Verify required versions
60
- node -v # Must show β‰₯ v20
61
- mongod --version # Must be installed
62
- ```
63
-
64
- ### install
65
-
66
- ```bash
67
- npm i data-primals-engine
68
- ```
69
- or
70
- ```bash
71
- git clone https://github.com/anonympins/data-primals-engine.git
72
- cd data-primals-engine
73
- npm install
74
- ```
75
-
76
- ### configure
77
- Possibly create a `.env` file:
78
- ```env
79
- MONGO_DB_URL=mongodb://127.0.0.1:27017
80
- ```
81
- | Variable | Description | Example |
82
- |:----------------------|:------------------------------------------------------------------------|:-----------------------------------------|
83
- | MONGO_DB_URL | Connection URL for your MongoDB database. | mongodb://user:pass@host:27017/db |
84
- | PORT | Port on which the Express server will listen. | 7633 |
85
- | JWT_SECRET | Secret key for signing JWT authentication tokens. | a_long_random_secret_string |
86
- | OPENAI_API_KEY | Your optional OpenAI API key for AI features. | sk-xxxxxxxxxxxxxxxxxxxx |
87
- | GOOGLE_API_KEY | Your optional Google (Gemini) API key for AI features. | AIzaSyxxxxxxxxxxxxxxxxxxxx |
88
- | DEEPSEEK_API_KEY | Your optional DeepSeek API key for AI features. | sk-xxxxxxxxxxxxxxxxxxxx |
89
- | ANTHROPIC_API_KEY | Your optional Anthropic API key for AI features. | sk-ant-xxxxxxxxxxxxxxxxxxx |
90
- | AWS_ACCESS_KEY_ID | AWS access key for S3 storage (files, backups). Keep empty to disable | AKIAIOSFODNN7EXAMPLE |
91
- | AWS_SECRET_ACCESS_KEY | AWS secret access key. | wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY | |
92
- | AWS_REGION | Region for your S3 bucket. | eu-west-3 | |
93
- | AWS_S3_BUCKET_NAME | Name of the S3 bucket to use. | my-backup-bucket | |
94
- | SMTP_HOST | SMTP server host for sending emails. | smtp.example.com |
95
- | SMTP_PORT | SMTP server port. | 587 |
96
- | SMTP_USER | Username for SMTP authentication. | user@example.com |
97
- | SMTP_PASS | Password for SMTP authentication. | password |
98
- | TLS | Encrypted connection (TLS) mode. Disabled by default | 0/1 false/true |
99
- | CA_CERT | Path to CA cert file. | certs/ca.crt |
100
- | CERT | Path to cert file. | certs/cert.pem |
101
- | CERT_KEY | Path to the key file for your certificate. | certs/key.pem |
102
-
103
- ### Start the server
104
- ```bash
105
- # Development mode
106
- npm run devserver
107
-
108
- # Production mode
109
- npm run server
110
- ```
111
-
112
- By default, the app runs on port **7633** : http://localhost:7633
113
-
114
-
115
- ---
116
-
117
- ## 🧠 Concepts
118
-
119
- ### Authentication & Authorization
120
-
121
- The engine includes a pluggable system for user management. For development and testing, it uses a `DefaultUserProvider` which creates a volatile **`demo`** user. This is perfect for getting started quickly without setting up a user database.
122
-
123
- For production environments, you should use SSO providers as seen in the page below, or extend the base `UserProvider` class to connect to your actual user database (e.g., another MongoDB collection, a SQL database, or an external authentication service). This allows you to implement your own logic for finding and creating users.
124
-
125
- ### Model generation
126
- Models are the way to handle structured data. They organize data and they can be declared in JSON.
127
-
128
- ```json
129
- {
130
- "name": "product",
131
- "description": "E-commerce product schema",
132
- "fields": [
133
- { "name": "name", "type": "string", "required": true },
134
- { "name": "price", "type": "number", "required": true },
135
- { "name": "stock", "type": "number", "default": 0 },
136
- { "name": "category", "type": "relation", "relation": "taxonomy",
137
- "relationFilter": { "$eq": ["$type", "category"] }
138
- },
139
- { "name": "tags", "type": "relation", "relation": "taxonomy", "multiple": true,
140
- "relationFilter": { "$eq": ["$type", "keyword"] }
141
- }
142
- ]
143
- }
144
- ```
145
-
146
- ### Custom fields types
147
-
148
- | Type | Description | Properties/Notes |
149
- |:------------|:------------------------------------------------------------------------------------|:--------------------------------------------------------------------------|
150
- | string | Character string. | minLength, maxLength |
151
- | string_t | International character string ID. | same as string, translated in { key, value } |
152
- | number | Numeric value (integer or float). | min, max |
153
- | boolean | Boolean value (true/false). | – |
154
- | date | Stores a ISO date. | – |
155
- | datetime | Stores an ISO date and time. | – |
156
- | richtext | Rich text field (HTML) for WYSIWYG editors. | |
157
- | richtext_t | International rich text field (HTML) for WYSIWYG editors. | i18n |
158
- | email | String validated as an email address. | – |
159
- | password | String that will be automatically hashed. | – |
160
- | enum | Allows selecting a value from a predefined list. | items: ["value1", "value2"] |
161
- | relation | Creates a link to a document in another model. | relation: "target_model_name", multiple: true/false |
162
- | file | For uploading a file (stored on S3 if configured). | allowedTypes:['image/jpeg', 'image/png', 'image/bmp'], maxSize: 1024*1000 |
163
- | image | Specialized file type for images, with preview. | – |
164
- | array | Stores a list of values. | itemsType: 'enum' // any type except relations |
165
- | object | Stores a nested JSON object. – | |
166
- | code | Stores language="*" as string, stores language="json" as arbitrary JSON structure. | language="json" conditionBuilder=true |
167
- | color | Stores an hexadecimal value of an RGB color | '#FF0000' |
168
- | model | Stores a model by name | – |
169
- | modelField | Stores a model field path | – |
170
-
171
- ### Other model features
172
- - Handles up to 2,000 direct relations by default (can be customized). For larger datasets, use intermediate collections
173
- - Automatic indexing on key fields
174
- - Custom indexing on fields
175
- - Anonymizable fields (encrypted for API users)
176
-
177
- ### Model constraints
178
- ```javascript
179
- {
180
- "name": "modelName",
181
- "fields": [
182
- { "name": "fieldName1", .... },
183
- { "name": "fieldName2", .... }
184
- ],
185
- "constraints": [
186
- // uniqueness
187
- { "name": "uniqueConstraint", type: "unique", keys: ["fieldName1", "fieldName2"] }
188
- ]
189
- }
190
- ```
191
-
192
- ## πŸ—οΈ Use Case Examples
193
-
194
- ### πŸ›’ E-Commerce Backoffice
195
- - Install ecommerce-starter pack
196
- - Add products via API/UI
197
- - Customize order workflows
198
-
199
- ### 🎫 Support Ticket System
200
- - Create ticket model with [open, pending, resolved] statuses
201
- - Configure notification workflows
202
- - Add custom endpoints or dashboards/kpi for analytics
203
-
204
- ### πŸ€– AI Chatbot
205
- - Define your model
206
- - Set up workflow: "When new entry β†’ generate AI content"
207
-
208
- ### πŸ“§ Email Campaign Management
209
- The "Marketing & Campaigning" starter pack provides a powerful solution for sending large-scale email campaigns without overloading your server.
210
-
211
- - **Install the Pack**: A single command installs the necessary models (`campaign`, `audience`) and a sophisticated workflow.
212
- - **Dynamic Audiences**: Create target audiences with MongoDB filters. For example, select all contacts with the "newsletter" tag or located in a specific country.
213
- - **Personalized Content**: Use variables like `{recipient.firstName}` in the subject and body of your emails for a personal touch.
214
- - **Automated & Scalable Sending**: When you schedule a campaign, a pre-configured workflow takes over:
215
- - It processes your audience in small batches (e.g., 10 recipients at a time).
216
- - It sends emails to each batch and waits before processing the next, ensuring stability.
217
- - It tracks processed recipients to avoid duplicates and allow the campaign to be safely paused and resumed.
218
- - Once all emails are sent, the campaign is automatically marked as "completed".
219
-
220
- This use case demonstrates how starter packs and workflows can automate complex, performance-critical business logic right out of the box.
221
-
222
- ---
223
-
224
- ## πŸ“ Project Structure
225
- ```
226
- data-primals-engine/
227
- β”œβ”€β”€ src/
228
- β”‚ β”œβ”€β”€ middlewares/
229
- β”‚ β”œβ”€β”€ migrations/
230
- β”‚ β”œβ”€β”€ modules/
231
- β”‚ β”œβ”€β”€ workers/
232
- β”‚ β”œβ”€β”€ engine.js // The Express engine that serves the API
233
- β”‚ β”œβ”€β”€ constants.js // The inner-application constants definitions
234
- β”‚ β”œβ”€β”€ packs.js // The packs that will be loaded and available with installPack() method
235
- β”‚ β”œβ”€β”€ defaultModels.js // The default models available at startup.
236
- β”‚ β”œβ”€β”€ ...
237
- └── server.js
238
- ```
239
-
240
- ---
241
-
242
- ## πŸ”Œ API Examples (using `curl`)
243
-
244
- ### πŸ“ Model Management
245
-
246
- #### Create a model
247
- > Defines a new data model (schema) in the system. The request body must contain the model's name and an array of field definitions.
248
- ```bash
249
- curl -X POST http://localhost:7633/api/model?_user=demo \
250
- -H "Authorization: Bearer demotoken" \
251
- -H "Content-Type: application/json" \
252
- -d '{
253
- "name": "newModel",
254
- "description": "A test model.",
255
- "fields": [
256
- {"name": "title", "type": "string", "required": true},
257
- {"name": "price", "type": "number"}
258
- ]
259
- }'
260
- ```
261
-
262
- #### Update a model
263
- > Modifies an existing model's structure using its unique ID. This allows you to add, remove, or change fields.
264
- ```bash
265
- curl -X PUT http://localhost:7633/api/model/60d0fe4f5311236168a109ca?_user=demo \
266
- -H "Authorization: Bearer demotoken" \
267
- -H "Content-Type: application/json" \
268
- -d '{
269
- "name": "updatedModel",
270
- "description": "Updated description.",
271
- "fields": [
272
- {"name": "title", "type": "string", "required": true},
273
- {"name": "status", "type": "enum", "items": ["active", "inactive"]}
274
- ]
275
- }'
276
- ```
277
-
278
- #### Delete a model
279
- > Permanently deletes a model definition using its name. This action is irreversible.
280
- ```bash
281
- curl -X DELETE "http://localhost:7633/api/model?_user=demo&name=newModel" \
282
- -H "Authorization: Bearer demotoken"
283
- ```
284
-
285
- ### πŸ—‚οΈ Data Management
286
-
287
- #### Create a document
288
- > Creates a single new document in the specified model. The `data` object must conform to the model's schema.
289
- ```bash
290
- curl -X POST http://localhost:7633/api/data?_user=demo \
291
- -H "Authorization: Bearer demotoken" \
292
- -H "Content-Type: application/json" \
293
- -d '{
294
- "model": "product",
295
- "data": {
296
- "name": "Widget Extraordinaire",
297
- "price": 99.99,
298
- "stock": 150,
299
- "published": true
300
- }
301
- }'
302
- ```
303
-
304
-
305
- #### Search documents
306
- > Searches for documents using a MongoDB-style filter. This endpoint is ideal for complex queries, pagination, and sorting.
307
-
308
- ```bash
309
- curl -X POST http://localhost:7633/api/data/search?_user=demo \
310
- -H "Authorization: Bearer demotoken" \
311
- -H "Content-Type: application/json" \
312
- -d '{
313
- "model": "product",
314
- "filter": { "$gt" : ["$price", 50] }
315
- }'
316
- ```
317
-
318
- #### Update a document by ID
319
- > Updates a single document by its unique ID. The request body contains the fields to be modified.
320
- ```bash
321
- curl -X PUT http://localhost:7633/api/data/64a31c123ef59d4c8d55aa99?_user=demo \
322
- -H "Authorization: Bearer demotoken" \
323
- -H "Content-Type: application/json" \
324
- -d '{
325
- "model": "product",
326
- "data": { "price": 109.99 }
327
- }'
328
- ```
329
-
330
-
331
- #### Bulk update
332
- > Updates multiple documents matching a filter. This is efficient for applying changes to a batch of records, such as restocking all out-of-stock products.
333
- ```bash
334
- curl -X PUT http://localhost:7633/api/data?_user=demo \
335
- -H "Authorization: Bearer demotoken" \
336
- -H "Content-Type: application/json" \
337
- -d '{
338
- "model": "product",
339
- "data": { "stock": 999 }
340
- }'
341
- ```
342
-
343
- #### Delete documents
344
- > Deletes one or more documents. You can provide an array of `ids` to delete specific documents.
345
- ```bash
346
- curl -X DELETE http://localhost:7633/api/data?_user=demo \
347
- -H "Authorization: Bearer demotoken" \
348
- -H "Content-Type: application/json" \
349
- -d '{
350
- "ids": ["64a31c123ef59d4c8d55aa99"]
351
- }'
352
- ```
353
-
354
- ## Other operations
355
-
356
- Make sure you use the code below to initialize the user :
357
- ```javascript
358
- import express from "express";
359
- import {Engine, insertData, searchData } from 'data-primals-engine';
360
-
361
- // Ensure the engine is initialized
362
-
363
- const app = express();
364
- const engine = await Engine.Create({ app });
365
- const currentUser = await engine.userProvider.findUserByUsername('demo');
366
- if (!currentUser) {
367
- throw new Error("Could not retrieve the user. Please check credentials or user provider.");
368
- }
369
- console.log(`Successfully authenticated as ${currentUser.username}`);
370
- ```
371
-
372
- ### insertData(modelName, data, files, user)
373
-
374
- > Inserts one or more documents, intelligently handling nested relationships.
375
-
376
- ```javascript
377
- // Uses the `currentUser` object defined above
378
- const newProduct = { name: 'Super Widget', price: 99.99, status: 'available' };
379
- const result = await insertData('product', newProduct, {}, currentUser);
380
-
381
- if (result.success) {
382
- console.log(`Successfully inserted document with ID: ${result.insertedIds[0]}`);
383
- }
384
- ```
385
-
386
- ### editData(modelName, filter, data, files, user)
387
-
388
- > Updates existing data matching the filter.
389
-
390
- Example:
391
-
392
- ```javascript
393
- await editData(
394
- "userProfile",
395
- { _id: "507f1f77bcf86cd799439011" },
396
- { bio: "Updated bio text" },
397
- null, // No files
398
- currentUser
399
- );
400
- ```
401
-
402
- ### patchData(modelName, filter, data, files, user)
403
-
404
- > Partially updates data (only modifies specified fields).
405
-
406
- Example:
407
-
408
- ```javascript
409
- await patchData(
410
- "settings",
411
- { userId: "507f1f77bcf86cd799439011" },
412
- { theme: "dark" },
413
- null,
414
- currentUser
415
- );
416
- ```
417
-
418
- ### deleteData(modelName, filter, user)
419
-
420
- >Deletes data with cascading relation cleanup.
421
-
422
- Examples:
423
-
424
- ```javascript
425
- // Delete by IDs
426
- await deleteData("comments", ["61d1f1a9e3f1a9e3f1a9e3f1"], user);
427
-
428
- // Delete by filter
429
- await deleteData("logs", { createdAt: { $lt: "2023-01-01" } }, user);
430
- ```
431
-
432
- ### searchData(query, user)
433
-
434
- Powerful search with relation expansion and filtering.
435
-
436
- Query Options:
437
-
438
- - model: Model name to search
439
- - filter: MongoDB-style filter
440
- - depth: Relation expansion depth (default: 1)
441
- - limit/page: Pagination
442
- - sort: Sorting criteria
443
-
444
- Example:
445
- ```javascript
446
- const results = await searchData({
447
- model: "blogPost",
448
- filter: { status: "published" },
449
- depth: 2, // Expand author and comments
450
- limit: 10,
451
- sort: "createdAt:DESC"
452
- }, user);
453
- ```
454
-
455
- ## Import/Export
456
- ### importData(options, files, user)
457
- > Imports data from Excel / JSON / CSV files.
458
-
459
- Supported Formats:
460
-
461
- - Excel with headers or field mapping
462
- - CSV with headers or field mapping
463
- - JSON arrays
464
- - JSON with model-keyed objects
465
-
466
- Example:
467
-
468
- ```javascript
469
- const result = await importData(
470
- {
471
- model: "products",
472
- hasHeaders: true
473
- },
474
- {
475
- file: req.files.myFileField // from multipart body
476
- },
477
- currentUser
478
- );
479
- ```
480
-
481
- ### exportData(options, user)
482
- > Exports data to a structured format.
483
-
484
- Example:
485
-
486
- ```javascript
487
- await exportData(
488
- {
489
- models: ["products", "categories"],
490
- depth: 1, // Include relations
491
- lang: "fr" // Localized data
492
- },
493
- currentUser
494
- );
495
- // Returns: { success: true, data: { products: [...], categories: [...] } }
496
- ```
497
-
498
- ## Backup & Restore
499
- ### dumpUserData(user)
500
- > Creates an encrypted backup of user data.
501
-
502
- Features:
503
-
504
- - Automatic encryption
505
- - S3 or local storage
506
- - Retention policies by plan (daily/weekly/monthly)
507
-
508
- Example:
509
-
510
- ```javascript
511
- await dumpUserData(currentUser);
512
- // Backup saved to S3 or ./backups/
513
- ```
514
-
515
- ### loadFromDump(user, options)
516
-
517
- > Restores user data from backup.
518
-
519
- Options:
520
- - modelsOnly: Restore only model definitions
521
-
522
- Example:
523
-
524
- ```javascript
525
- await loadFromDump(currentUser, { modelsOnly: false });
526
- // Full restore including data
527
- ```
528
-
529
- ## Pack Management
530
-
531
- ### installPack(packId, user, lang)
532
-
533
- > Installs a data pack.
534
-
535
- Example:
536
-
537
- ```javascript
538
- const result = await installPack([
539
- {
540
- "name": "My custom pack",
541
- "description": "Markdown **description** of the pack",
542
- "tags": ["customPack", "tag1", "tag2"],
543
- "models": [
544
- "env", // default model
545
- {
546
- "name": "post",
547
- "description": "Defines a post",
548
- "fields": [
549
- {"name": "subject", "type": "string", "required": true},
550
- ]
551
- }, // or custom
552
- ],
553
- "data": {
554
- "all": { // all languages installed data
555
- "post": [
556
- {"subject": "My pack first data"}
557
- ]
558
- },
559
- "en": { // English specific installed data
560
- "post": [
561
- {"subject": "My english first post"}
562
- ]
563
- }
564
- }
565
- }
566
- ], user, "en");
567
- // Returns installation summary
568
- ```
569
-
570
- ```javascript
571
- const result = await installPack("61d1f1a9e3f1a9e3f1a9e3f1", user, "en");
572
- // Returns installation summary
573
- ```
574
-
575
- > You can also open the pack gallery to see the JSON structure of each pack, before installing them.
576
-
577
-
578
- ---
579
- ### Data Auditing & History
580
- data-primals-engine includes a built-in, automatic auditing system that creates a complete history for every record in your database.
581
-
582
- >This feature is essential for traceability, debugging, and maintaining a clear audit trail of all data manipulations.
583
-
584
- #### How It Works
585
- The history feature is non-intrusive and fully automatic.
586
-
587
- Whenever you use the standard data management functions (insertData, patchData, deleteData, etc.), the engine performs two actions:
588
- 1. It executes the requested operation (create, update, or delete) on the target document.
589
- 2. It saves a complete "snapshot" of the document's state into a dedicated history collection.
590
-
591
- >Each history entry contains the original data along with crucial metadata:
592
- - `_op`: The type of operation (i for insert, u for update, d for delete).
593
- - `_v`: The version number of the record.
594
- - `_user`: The username of the user who performed the action.
595
- - `_updatedAt`: The timestamp of the operation.
596
- - `_rid`: The ID of the original record, linking all history entries together.
597
-
598
- ### Accessing the History
599
- You can retrieve the full history for any record via a simple API endpoint:
600
- ```x-sh
601
- curl -X GET http://localhost:7633/api/data/history/:modelName/:recordId
602
- ```
603
-
604
- ---
605
-
606
- ## Workflows: Automate Your Business Logic
607
-
608
- > Workflows are the automation engine of your application.
609
-
610
- They allow you to define complex business processes that run in response to specific events, without writing custom code.
611
-
612
- This is perfect for tasks like **sending welcome emails**, managing **order fulfillment**, or triggering data synchronization.
613
-
614
- A workflow is composed of two main parts: **Triggers** and **Actions**.
615
-
616
- > A 'workflowTrigger' is the event that initiates a workflow run.
617
- - **DataAdded**: Fires when a new document is created (e.g., a new user signs up).
618
- - **DataEdited**: Fires when a document is updated (e.g., an order status changes to "shipped").
619
- - **DataDeleted**: Fires when a document is removed.
620
- - **Scheduled**: Runs at a specific time or interval using a Cron expression (e.g., 0 0 * * * for a nightly data cleanup job).
621
- - **Manual**: Triggered on-demand via an API call, allowing you to integrate workflows into any part of your application.
622
-
623
- > A 'workflowAction' is the individual steps a workflow executes. You can chain them together to create sophisticated logic.
624
- - **CreateData**: Create a new document in any model.
625
- - **UpdateData**: Modify one or more existing documents that match a filter.
626
- - **SendEmail**: Send a transactional email using dynamic data from the trigger.
627
- - **HttpRequest**: Make an HTTP request (GET, POST, etc.) to an external service or API.
628
- - **ExecuteScript**: Run a custom JavaScript snippet for complex logic, data transformation, or conditional branching.
629
- - **GenerateAIContent**: Use an integrated AI provider (like OpenAI or Gemini) to generate text, summarize content, or make decisions.
630
- - **Wait**: Pause the workflow for a specific duration before continuing to the next step
631
-
632
- See the details of the workflow models for more details.
633
-
634
- ## ⚑ Dynamic API Endpoints
635
- Beyond standard CRUD operations, data-primals-engine allows you to create your own custom API endpoints directly from the UI. This feature acts like a built-in serverless function environment, enabling you to write custom business logic, integrate with third-party services, or create complex data aggregations on the fly.
636
-
637
- Your code is executed in a secure, isolated sandbox, with access to the core data functions and the incoming request context.
638
-
639
- ### How It Works
640
- Define an Endpoint: You create a new document in the endpoint model.
641
- Write Your Logic: In the code field, you write the JavaScript that will be executed.
642
- Activate: The engine automatically listens for requests on /api/actions/:path that match your endpoint's definition.
643
-
644
- ### The endpoint Model
645
- To create a custom endpoint, you need to define a document with the following structure:
646
- ```json
647
- {
648
- "name": "GetContactPostCount",
649
- "path": "postCount/:name",
650
- "method": "GET",
651
- "code": "const posts = await db.find('content', { author: { $find: { $eq: ['$lastName', request.params.name]}}}); return { postCount: posts.length };",
652
- "isActive": true,
653
- "isPublic": true
654
- }
655
- ```
656
- | Field | Type | Description |
657
- |:---------|:--------|:---------------------------------------------------------------------|
658
- | name | string | A descriptive name for your endpoint (e.g., "Calculate User Stats"). |
659
- | path | string | The URL path. It can include parameters like :id. |
660
- | method | enum | The HTTP method: GET, POST, PUT, PATCH, or DELETE. |
661
- | code | code | The JavaScript code to execute when the endpoint is called. |
662
- | isActive | boolean | A flag to enable or disable the endpoint without deleting it. |
663
- | isPublic | boolean | A flag to enable public access (private by default). |
664
- ---
665
-
666
- ### The Execution Context
667
- Your JavaScript code runs in an async context and has access to several global objects that are securely injected into the sandbox:
668
- Your current user is used to make the calls.
669
-
670
- #### The context Object
671
- > This object contains all the information about the incoming HTTP request.
672
- - context.request.**body**: The parsed request body (for POST, PUT, PATCH).
673
- - context.request.**query**: The URL query parameters as an object.
674
- - context.request.**params**: The URL path parameters (e.g., username from /user-summary/:username).
675
- - context.request.**headers**: The incoming request headers.
676
-
677
- #### The db Object
678
- > A secure API to interact with the database. All methods are async and must be awaited. They automatically operate within the authenticated user's permissions.
679
- - await db.**create**(modelName, dataObject): Inserts a new document.
680
- - await db.**find**(modelName, filter): Finds multiple documents. Returns an array.
681
- - await db.**findOne**(modelName, filter): Finds a single document. Returns an object or null.
682
- - await db.**update**(modelName, filter, updateObject): Partially updates documents matching the filter (similar to a PATCH).
683
- - await db.**delete**(modelName, filter): Deletes documents matching the filter.
684
-
685
- #### The logger Object
686
- > A safe way to log messages from your script. These logs will be collected and can be returned in the API response if an error occurs, which is very useful for debugging.
687
- - logger.**info**(...args)
688
- - logger.**warn**(...args)
689
- - logger.**error**(...args)
690
-
691
- #### The env Object
692
- > Provides access to the user-defined variables stored in the env model, not the server's process.env.
693
- - await env.**get**(variableName): Retrieves a single environment variable's value.
694
- - await env.**getAll**(): Retrieves all user environment variables as an object.
695
-
696
- #### Example: Creating a User Summary Endpoint
697
- Let's create an endpoint that fetches a user's profile and counts how many posts they have published.
698
- 1. Create the Endpoint Document
699
- Create a new document in the endpoint model with the following data:
700
- ```json
701
- {
702
- "name": "Get User Summary",
703
- "path": "user-summary/:username",
704
- "method": "GET",
705
- "isActive": true,
706
- "code": "const { username } = context.request.params;\n\n if (!username) {\n logger.error('Username parameter is required.');\n return { success: false, error: 'Username is required.' };\n }\n\n logger.info(`Fetching summary for user: ${username}`);\n\n // Fetch the user profile using the sandboxed db API\n const userProfile = await db.findOne('userProfile', { username: username });\n\n if (!userProfile) {\n return { success: false, error: 'User not found' };\n }\n\n // Count the user's published posts\n const posts = await db.find('post', { \n authorId: userProfile._id.toString(), \n status: 'published' \n });\n\n return {\n profile: userProfile,\n publishedPosts: posts.length\n };\n});",
707
- }
708
- ```
709
- 2. Call the New Endpoint
710
- You can now call this custom endpoint like any other API route:
711
-
712
- Expected response :
713
- ```json
714
- {
715
- "profile": {
716
- "_id": "60d0fe4f5311236168a109ca",
717
- "username": "demo",
718
- "bio": "A demo user profile.",
719
- "...": "..."
720
- },
721
- "publishedPosts": 15
722
- }
723
-
724
- ```
725
-
726
- ### Pluggable SSO Authentication (Google, SAML, Azure AD)
727
-
728
- `data-primals-engine` features a powerful and modular Single Sign-On (SSO) system built on Passport.js. This allows you to easily integrate with various enterprise and social identity providers. The core engine remains lightweight, and you only enable the providers you need.
729
-
730
- #### How It Works
731
-
732
- The engine provides a central `Sso` component that manages authentication logic. Each provider (Google, SAML, etc.) is an independent module that "plugs into" this central component.
733
-
734
- To enable an SSO provider, follow these three steps:
735
-
736
- #### Example: Enabling Google Sign-In
737
-
738
- **1. Install the Provider's Library**
739
-
740
- The required Passport strategy is a `peerDependency`. You must install it in your project:
741
- ```bash
742
- npm install passport-google-oauth20
743
- ```
744
-
745
- **2. Enable the Module**
746
-
747
- To enable the module in your next engine initilization, just add it to the `modules` array:
748
- ```javascript
749
- Config.Set("modules", ["auth-google", "..."]);
750
- ```
751
-
752
- **3. Set Environment Variables**
753
-
754
- Create or update your `.env` file with the credentials obtained from the Google Cloud Console:
755
- ```env
756
- GOOGLE_CLIENT_ID=your-google-client-id
757
- GOOGLE_CLIENT_SECRET=your-google-client-secret
758
- ```
759
-
760
- The login flow will now be available at `/api/auth/google`.
761
-
762
- #### Other Providers
763
-
764
- The process is identical for other supported providers:
765
-
766
- - **SAML**:
767
- 1. `npm install passport-saml-encrypted`
768
- 2. Enable the `auth-saml` module.
769
- 3. Set `SAML_ENTRY_POINT`, `SAML_ISSUER`, `SAML_CERT`, and `SAML_DECRYPTION_KEY` environment variables.
770
-
771
- - **Microsoft Azure AD**:
772
- 1. `npm install passport-azure-ad`
773
- 2. Enable the `auth-microsoft` module.
774
- 3. Set `MICROSOFT_CLIENT_ID`, `MICROSOFT_CLIENT_SECRET`, and `MICROSOFT_TENANT_ID` environment variables.
775
-
776
- This modular approach makes it simple to extend the engine with any Passport-compatible strategy to meet your authentication needs.
777
-
778
- See implementations in the `modules` directory.
779
-
780
- ---
781
- ## Extensibility
782
-
783
- ### Events (Triggers) Table
784
- > You can use the events below to access the engine and manipulate API responses.
785
- > It is useful for custom modules or middlewares for your application.
786
-
787
- Just use
788
-
789
- ```javascript
790
- Event.Listen("OnDataAdded", (data) => {
791
- my_callback()
792
- }, "event", "user");
793
- ```
794
-
795
- or the system version
796
- ```javascript
797
- Event.Listen("OnDataAdded", (engine, data) => {
798
- my_callback()
799
- }, "event", "system");
800
- ```
801
-
802
- | Event | Description | Scope | Triggered by | Arguments (Payload) |
803
- |:-----------------|:------------------------------------------------------------------------|:--------------|:---------------------|:-----------------------------------------------------------------------------------------------------------------------------------------|
804
- | OnServerStart | Triggered once the HTTP server is started and listening. | System | engine.start() | engine |
805
- | OnServerStop | Triggered right after the HTTP server is stopped. | System | engine.stop() | engine |
806
- | OnModelsLoaded | Triggered after the initial models are loaded and validated at startup. | System | setupInitialModels() | engine, dbModels |
807
- | OnModelsDeleted | Triggered after all models are deleted via the reset function. | System | engine.resetModels() | engine |
808
- | OnUserDataDumped | Triggered after a user's data has been backed up (dumped). | System | jobDumpUserData() | engine |
809
- | OnDataRestored | Triggered after a user's data has been restored from a backup. | System | loadFromDump() | (none) |
810
- | OnPackInstalled | Triggered after a data pack has been successfully installed. | System | installPack() | pack |
811
- | OnModelEdited | Triggered after a model definition has been modified. | System & User | editModel() | System: engine, newModel (Pipeline*)<br>User: newModel (or the version modified by the system) |
812
- | OnDataAdded | Triggered after new data has been inserted. | System & User | insertData() | System: engine, insertedIds (Pipeline*)<br>User: insertedIds (or the version modified by the system) |
813
- | OnDataDeleted | Triggered just after data is actually deleted. | System & User | deleteData() | System: engine, {model, filter} (Pipeline*)<br>User: {model, filter} |
814
- | OnDataSearched | Triggered after a data search. | System & User | searchData() | System: engine, {data, count} (Pipeline*)<br>User: {data, count} (or the version modified by the system) |
815
- | OnDataExported | Triggered after a data export. | System & User | exportData() | System: engine, exportResults, modelsToExport (Pipeline*)<br>User: exportResults, modelsToExport (or the version modified by the system) |
816
- | OnDataInsert | Triggered just before data insertion. It will use the overrided data. | System | internal | (data) |
817
- | OnDataValidate | Triggered to override validation check. | System | internal | (value, field, data) |
818
- | OnDataFilter | Triggered to override data filtering operation. | System | internal | (filteredValue, field, data) |
819
- | OnEmailTemplate | Triggered to override custom email templates | System | internal | (templateData, lang) |
820
-
821
- ### Triggering events
822
-
823
- If you want to provide your own hooks, you can call :
824
- ```javascript
825
- const result = await Event.Trigger("OnMyCustomEvent", "event", "user", ...args);
826
- ```
827
- Results are merged together if multiple events are triggered.
828
- - strings are concatenated
829
- - numbers are added
830
- - booleans are ANDed
831
- - arrays are concatenated
832
- - objects are merged using spread operator
833
-
834
- ---
835
-
836
- ## βš›οΈ Frontend Integration (React)
837
-
838
- This engine is designed to work seamlessly with its dedicated client library, **`data-primals-engine/client`**. This library provides a complete set of React hooks and UI components to build a rich, data-centric user interface on top of the backend.
839
-
840
- While this README focuses on the backend engine and its API, you can find detailed instructions on how to integrate the client part in your React application here:
841
-
842
- ➑️ **[View the Frontend Integration Guide](https://github.com/anonympins/data-primals-engine/tree/develop/client)**
843
-
844
-
845
- ---
846
-
847
- ## 🀝 Contributing
848
-
849
- Find the issues available for [contributions here](https://github.com/anonympins/data-primals-engine/issues?q=is%3Aissue%20state%3Aopen%20label%3A%22help%20wanted%22%20no%3Aassignee)
850
-
851
- 1. Fork the repo
852
- 2. Create your feature branch: `git checkout -b feature/your-feature`
853
- 3. Launch ```npm run dev``` and make your changes with hot-reload on local port
854
- 3. Commit changes: `git commit -m "Add new feature"`
855
- 4. Push to your branch: `git push origin feature/your-feature`
856
- 5. Open a pull request
857
-
858
- Star ⭐ the repo if you find it useful!
859
-
860
- ---
861
-
862
- ## πŸ“„ License
863
- Distributed under the **MIT License**. See `LICENSE` file.
864
-
865
- ---
866
-
867
- ## [πŸ”Ό](#data-primals-engine) Back to Top
1
+ # data-primals-engine
2
+ [![Node.js CI](https://github.com/anonympins/data-primals-engine/actions/workflows/node.js.yml/badge.svg?branch=main)](https://github.com/anonympins/data-primals-engine/actions/workflows/node.js.yml)
3
+ ![](https://img.shields.io/npm/dw/data-primals-engine)
4
+ ![](https://img.shields.io/npm/last-update/data-primals-engine)
5
+ ![](https://img.shields.io/github/v/release/anonympins/data-primals-engine)
6
+ ![](https://img.shields.io/github/license/anonympins/data-primals-engine)
7
+
8
+ **data-primals-engine** is a powerful and flexible **Node.js** backend framework designed to accelerate development of complex data-driven applications. Built on **Express.js** and **MongoDB**, it offers dynamic data modeling, automation workflows, advanced user management, and more.
9
+
10
+ > Whether you're building a CRM, e-commerce site, CMS, or SaaS platform, **data-primals-engine** provides the strong foundations so you can focus on what makes your application unique.
11
+
12
+ <p align="center">
13
+ <a href="https://data.primals.net/prez1.jpg" target="_blank"><img alt="Light" src="https://data.primals.net/prez1.jpg" width="35%"></a>
14
+ <a href="https://data.primals.net/prez6.jpg" target="_blank"><img alt="Light" src="https://data.primals.net/prez6.jpg" width="35%"></a>
15
+ <a href="https://data.primals.net/api-docs" target="_blank"><img alt="Dark" src="https://data.primals.net/prez5.jpg" width="25%"></a>
16
+ </p>
17
+ ---
18
+
19
+ ## πŸš€ Key Features
20
+
21
+ - **Visual Data Modeling**: Define and update schemas using a powerful UI Model Creator, or directly with JSON. No migrations required.
22
+ - **Custom API Endpoints**: Create server-side logic and new API endpoints directly from the UI in a secure, sandboxed environment.
23
+ - **Automation Workflows**: Trigger complex actions based on data events (create, update, delete) or schedules (cron).
24
+ - **Advanced Querying & Aggregation**: Go beyond simple filters with a visual Condition Builder, deep relation expansion, complex lookups, and dynamic calculated fields.
25
+ - **Rich UI Data Views**: Ready-to-use React components to display your data, including a powerful and configurable Data Table, a Kanban board, and a Calendar view.
26
+ - **Integrated Backup & Restore**: Secure, encrypted user data backups with rotation policies, supporting both local and AWS S3 storage.
27
+ - **Automatic Data Auditing**: Automatically tracks all changes (create, update, delete) for every record, providing a complete version history for auditing and traceability.
28
+ - **Event-Driven & Extensible**: A core event system allows for deep customization and the easy creation of new modules or plugins.
29
+ - **Authentication & Authorization**: Robust role-based access control (RBAC) and pluggable user providers.
30
+ - **Built-in File Management**: Handle file uploads seamlessly with integrated support for AWS S3 storage.
31
+ - **🧠 AI Integration**: Natively supports OpenAI, DeepSeek and Google Gemini models via LangChain for content generation, analysis, and more.
32
+ - **🌐 Internationalization (i18n)**: Fully supports multilingual interfaces and user-specific translated data.
33
+ - **πŸ“¦ Starter Packs**: Quickly bootstrap applications with pre-built data packs for CRM, e-commerce, and more.
34
+ - **πŸ“„Auto-Generated API Documentation**: Interactive API documentation available via the interface or at `/api-docs`.
35
+
36
+ ## 🌟 Why Choose data-primals-engine?
37
+
38
+ - **Zero Boilerplate**: Focus on your business logic, not infrastructure
39
+ - **Scalability**: Architecture designed for rapidly growing applications
40
+ - **Modularity**: Enable/disable features as needed
41
+ - **Batteries Included**: Everything you need to get started quickly
42
+ - **Proven Performance**: Handles 50k+ documents efficiently
43
+ - **AI Ready**: Built-in LangChain integration for main providers (OpenAI,Gemini,Anthropic,DeepSeek)
44
+
45
+ ---
46
+
47
+ ## πŸ“Š Proven Performance
48
+
49
+ The engine has been rigorously tested to ensure stability and scalability. Load tests simulating complex, multi-step user journeys (including model creation, data import, and API interactions) show excellent results:
50
+ - **Zero Failures**: 100% success rate under sustained concurrent load.
51
+ - **Excellent Responsiveness**: Median response times as low as 15-30ms.
52
+ - **Linear Scaling**: Predictable performance as user load increases.
53
+
54
+ For detailed reports, see the [Performance Testing Documentation](./perf/README.md).
55
+
56
+ ---
57
+
58
+ ## βš™οΈ Requirements
59
+
60
+ - Node.js β‰₯ 20
61
+ - MongoDB (local or remote), see [installation guide](https://www.mongodb.com/docs/manual/installation/)
62
+ - NPM or Yarn
63
+
64
+ ---
65
+
66
+ ## ⚑ Quick Start
67
+
68
+ ### check
69
+ ```bash
70
+ # Verify required versions
71
+ node -v # Must show β‰₯ v20
72
+ mongod --version # Must be installed
73
+ ```
74
+
75
+ ### install
76
+
77
+ ```bash
78
+ npm i data-primals-engine
79
+ ```
80
+ or
81
+ ```bash
82
+ git clone https://github.com/anonympins/data-primals-engine.git
83
+ cd data-primals-engine
84
+ npm install
85
+ ```
86
+
87
+ ### configure
88
+ Possibly create a `.env` file:
89
+ ```env
90
+ MONGO_DB_URL=mongodb://127.0.0.1:27017
91
+ ```
92
+ | Variable | Description | Example |
93
+ |:----------------------|:------------------------------------------------------------------------|:-----------------------------------------|
94
+ | MONGO_DB_URL | Connection URL for your MongoDB database. | mongodb://user:pass@host:27017/db |
95
+ | PORT | Port on which the Express server will listen. | 7633 |
96
+ | JWT_SECRET | Secret key for signing JWT authentication tokens. | a_long_random_secret_string |
97
+ | OPENAI_API_KEY | Your optional OpenAI API key for AI features. | sk-xxxxxxxxxxxxxxxxxxxx |
98
+ | GOOGLE_API_KEY | Your optional Google (Gemini) API key for AI features. | AIzaSyxxxxxxxxxxxxxxxxxxxx |
99
+ | DEEPSEEK_API_KEY | Your optional DeepSeek API key for AI features. | sk-xxxxxxxxxxxxxxxxxxxx |
100
+ | ANTHROPIC_API_KEY | Your optional Anthropic API key for AI features. | sk-ant-xxxxxxxxxxxxxxxxxxx |
101
+ | AWS_ACCESS_KEY_ID | AWS access key for S3 storage (files, backups). Keep empty to disable | AKIAIOSFODNN7EXAMPLE |
102
+ | AWS_SECRET_ACCESS_KEY | AWS secret access key. | wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY | |
103
+ | AWS_REGION | Region for your S3 bucket. | eu-west-3 | |
104
+ | AWS_S3_BUCKET_NAME | Name of the S3 bucket to use. | my-backup-bucket | |
105
+ | SMTP_HOST | SMTP server host for sending emails. | smtp.example.com |
106
+ | SMTP_PORT | SMTP server port. | 587 |
107
+ | SMTP_USER | Username for SMTP authentication. | user@example.com |
108
+ | SMTP_PASS | Password for SMTP authentication. | password |
109
+ | TLS | Encrypted connection (TLS) mode. Disabled by default | 0/1 false/true |
110
+ | CA_CERT | Path to CA cert file. | certs/ca.crt |
111
+ | CERT | Path to cert file. | certs/cert.pem |
112
+ | CERT_KEY | Path to the key file for your certificate. | certs/key.pem |
113
+
114
+ ### Start the server
115
+ ```bash
116
+ # Development mode
117
+ npm run devserver
118
+
119
+ # Production mode
120
+ npm run server
121
+ ```
122
+
123
+ By default, the app runs on port **7633** : http://localhost:7633
124
+
125
+
126
+ ---
127
+
128
+ ## 🧠 Concepts
129
+
130
+ ### Authentication & Authorization
131
+
132
+ The engine includes a pluggable system for user management. For development and testing, it uses a `DefaultUserProvider` which creates a volatile **`demo`** user. This is perfect for getting started quickly without setting up a user database.
133
+
134
+ For production environments, you should use SSO providers as seen in the page below, or extend the base `UserProvider` class to connect to your actual user database (e.g., another MongoDB collection, a SQL database, or an external authentication service). This allows you to implement your own logic for finding and creating users.
135
+
136
+ ### Model generation
137
+ Models are the way to handle structured data. They organize data and they can be declared in JSON.
138
+
139
+ ```json
140
+ {
141
+ "name": "product",
142
+ "description": "E-commerce product schema",
143
+ "fields": [
144
+ { "name": "name", "type": "string", "required": true },
145
+ { "name": "price", "type": "number", "required": true },
146
+ { "name": "stock", "type": "number", "default": 0 },
147
+ { "name": "category", "type": "relation", "relation": "taxonomy",
148
+ "relationFilter": { "$eq": ["$type", "category"] }
149
+ },
150
+ { "name": "tags", "type": "relation", "relation": "taxonomy", "multiple": true,
151
+ "relationFilter": { "$eq": ["$type", "keyword"] }
152
+ }
153
+ ]
154
+ }
155
+ ```
156
+
157
+ ### Custom fields types
158
+
159
+ | Type | Description | Properties/Notes |
160
+ |:------------|:------------------------------------------------------------------------------------|:--------------------------------------------------------------------------|
161
+ | string | Character string. | minLength, maxLength |
162
+ | string_t | International character string ID. | same as string, translated in { key, value } |
163
+ | number | Numeric value (integer or float). | min, max |
164
+ | boolean | Boolean value (true/false). | – |
165
+ | date | Stores a ISO date. | – |
166
+ | datetime | Stores an ISO date and time. | – |
167
+ | richtext | Rich text field (HTML) for WYSIWYG editors. | |
168
+ | richtext_t | International rich text field (HTML) for WYSIWYG editors. | i18n |
169
+ | email | String validated as an email address. | – |
170
+ | password | String that will be automatically hashed. | – |
171
+ | enum | Allows selecting a value from a predefined list. | items: ["value1", "value2"] |
172
+ | relation | Creates a link to a document in another model. | relation: "target_model_name", multiple: true/false |
173
+ | file | For uploading a file (stored on S3 if configured). | allowedTypes:['image/jpeg', 'image/png', 'image/bmp'], maxSize: 1024*1000 |
174
+ | image | Specialized file type for images, with preview. | – |
175
+ | array | Stores a list of values. | itemsType: 'enum' // any type except relations |
176
+ | object | Stores a nested JSON object. – | |
177
+ | code | Stores language="*" as string, stores language="json" as arbitrary JSON structure. | language="json" conditionBuilder=true |
178
+ | color | Stores an hexadecimal value of an RGB color | '#FF0000' |
179
+ | model | Stores a model by name | – |
180
+ | modelField | Stores a model field path | – |
181
+
182
+ ### Other model features
183
+ - Handles up to 2,000 direct relations by default (can be customized). For larger datasets, use intermediate collections
184
+ - Automatic indexing on key fields
185
+ - Custom indexing on fields
186
+ - Anonymizable fields (encrypted for API users)
187
+
188
+ ### Model constraints
189
+ ```javascript
190
+ {
191
+ "name": "modelName",
192
+ "fields": [
193
+ { "name": "fieldName1", .... },
194
+ { "name": "fieldName2", .... }
195
+ ],
196
+ "constraints": [
197
+ // uniqueness
198
+ { "name": "uniqueConstraint", type: "unique", keys: ["fieldName1", "fieldName2"] }
199
+ ]
200
+ }
201
+ ```
202
+
203
+ ## πŸ—οΈ Use Case Examples
204
+
205
+ ### πŸ›’ E-Commerce Backoffice
206
+ - Install ecommerce-starter pack
207
+ - Add products via API/UI
208
+ - Customize order workflows
209
+
210
+ ### 🎫 Support Ticket System
211
+ - Create ticket model with [open, pending, resolved] statuses
212
+ - Configure notification workflows
213
+ - Add custom endpoints or dashboards/kpi for analytics
214
+
215
+ ### πŸ€– AI Chatbot
216
+ - Define your model
217
+ - Set up workflow: "When new entry β†’ generate AI content"
218
+
219
+ ### πŸ“§ Email Campaign Management
220
+ The "Marketing & Campaigning" starter pack provides a powerful solution for sending large-scale email campaigns without overloading your server.
221
+
222
+ - **Install the Pack**: A single command installs the necessary models (`campaign`, `audience`) and a sophisticated workflow.
223
+ - **Dynamic Audiences**: Create target audiences with MongoDB filters. For example, select all contacts with the "newsletter" tag or located in a specific country.
224
+ - **Personalized Content**: Use variables like `{recipient.firstName}` in the subject and body of your emails for a personal touch.
225
+ - **Automated & Scalable Sending**: When you schedule a campaign, a pre-configured workflow takes over:
226
+ - It processes your audience in small batches (e.g., 10 recipients at a time).
227
+ - It sends emails to each batch and waits before processing the next, ensuring stability.
228
+ - It tracks processed recipients to avoid duplicates and allow the campaign to be safely paused and resumed.
229
+ - Once all emails are sent, the campaign is automatically marked as "completed".
230
+
231
+ This use case demonstrates how starter packs and workflows can automate complex, performance-critical business logic right out of the box.
232
+
233
+ ---
234
+
235
+ ## πŸ“ Project Structure
236
+ ```
237
+ data-primals-engine/
238
+ β”œβ”€β”€ src/
239
+ β”‚ β”œβ”€β”€ middlewares/
240
+ β”‚ β”œβ”€β”€ migrations/
241
+ β”‚ β”œβ”€β”€ modules/
242
+ β”‚ β”œβ”€β”€ workers/
243
+ β”‚ β”œβ”€β”€ engine.js // The Express engine that serves the API
244
+ β”‚ β”œβ”€β”€ constants.js // The inner-application constants definitions
245
+ β”‚ β”œβ”€β”€ packs.js // The packs that will be loaded and available with installPack() method
246
+ β”‚ β”œβ”€β”€ defaultModels.js // The default models available at startup.
247
+ β”‚ β”œβ”€β”€ ...
248
+ └── server.js
249
+ ```
250
+
251
+ ---
252
+
253
+ ## πŸ”Œ API Examples (using `curl`)
254
+
255
+ ### πŸ“ Model Management
256
+
257
+ #### Create a model
258
+ > Defines a new data model (schema) in the system. The request body must contain the model's name and an array of field definitions.
259
+ ```bash
260
+ curl -X POST http://localhost:7633/api/model?_user=demo \
261
+ -H "Authorization: Bearer demotoken" \
262
+ -H "Content-Type: application/json" \
263
+ -d '{
264
+ "name": "newModel",
265
+ "description": "A test model.",
266
+ "fields": [
267
+ {"name": "title", "type": "string", "required": true},
268
+ {"name": "price", "type": "number"}
269
+ ]
270
+ }'
271
+ ```
272
+
273
+ #### Update a model
274
+ > Modifies an existing model's structure using its unique ID. This allows you to add, remove, or change fields.
275
+ ```bash
276
+ curl -X PUT http://localhost:7633/api/model/60d0fe4f5311236168a109ca?_user=demo \
277
+ -H "Authorization: Bearer demotoken" \
278
+ -H "Content-Type: application/json" \
279
+ -d '{
280
+ "name": "updatedModel",
281
+ "description": "Updated description.",
282
+ "fields": [
283
+ {"name": "title", "type": "string", "required": true},
284
+ {"name": "status", "type": "enum", "items": ["active", "inactive"]}
285
+ ]
286
+ }'
287
+ ```
288
+
289
+ #### Delete a model
290
+ > Permanently deletes a model definition using its name. This action is irreversible.
291
+ ```bash
292
+ curl -X DELETE "http://localhost:7633/api/model?_user=demo&name=newModel" \
293
+ -H "Authorization: Bearer demotoken"
294
+ ```
295
+
296
+ ### πŸ—‚οΈ Data Management
297
+
298
+ #### Create a document
299
+ > Creates a single new document in the specified model. The `data` object must conform to the model's schema.
300
+ ```bash
301
+ curl -X POST http://localhost:7633/api/data?_user=demo \
302
+ -H "Authorization: Bearer demotoken" \
303
+ -H "Content-Type: application/json" \
304
+ -d '{
305
+ "model": "product",
306
+ "data": {
307
+ "name": "Widget Extraordinaire",
308
+ "price": 99.99,
309
+ "stock": 150,
310
+ "published": true
311
+ }
312
+ }'
313
+ ```
314
+
315
+
316
+ #### Search documents
317
+ > Searches for documents using a MongoDB-style filter. This endpoint is ideal for complex queries, pagination, and sorting.
318
+
319
+ ```bash
320
+ curl -X POST http://localhost:7633/api/data/search?_user=demo \
321
+ -H "Authorization: Bearer demotoken" \
322
+ -H "Content-Type: application/json" \
323
+ -d '{
324
+ "model": "product",
325
+ "filter": { "$gt" : ["$price", 50] }
326
+ }'
327
+ ```
328
+
329
+ #### Update a document by ID
330
+ > Updates a single document by its unique ID. The request body contains the fields to be modified.
331
+ ```bash
332
+ curl -X PUT http://localhost:7633/api/data/64a31c123ef59d4c8d55aa99?_user=demo \
333
+ -H "Authorization: Bearer demotoken" \
334
+ -H "Content-Type: application/json" \
335
+ -d '{
336
+ "model": "product",
337
+ "data": { "price": 109.99 }
338
+ }'
339
+ ```
340
+
341
+
342
+ #### Bulk update
343
+ > Updates multiple documents matching a filter. This is efficient for applying changes to a batch of records, such as restocking all out-of-stock products.
344
+ ```bash
345
+ curl -X PUT http://localhost:7633/api/data?_user=demo \
346
+ -H "Authorization: Bearer demotoken" \
347
+ -H "Content-Type: application/json" \
348
+ -d '{
349
+ "model": "product",
350
+ "data": { "stock": 999 }
351
+ }'
352
+ ```
353
+
354
+ #### Delete documents
355
+ > Deletes one or more documents. You can provide an array of `ids` to delete specific documents.
356
+ ```bash
357
+ curl -X DELETE http://localhost:7633/api/data?_user=demo \
358
+ -H "Authorization: Bearer demotoken" \
359
+ -H "Content-Type: application/json" \
360
+ -d '{
361
+ "ids": ["64a31c123ef59d4c8d55aa99"]
362
+ }'
363
+ ```
364
+
365
+ ## Other operations
366
+
367
+ Make sure you use the code below to initialize the user :
368
+ ```javascript
369
+ import express from "express";
370
+ import {Engine, insertData, searchData } from 'data-primals-engine';
371
+
372
+ // Ensure the engine is initialized
373
+
374
+ const app = express();
375
+ const engine = await Engine.Create({ app });
376
+ const currentUser = await engine.userProvider.findUserByUsername('demo');
377
+ if (!currentUser) {
378
+ throw new Error("Could not retrieve the user. Please check credentials or user provider.");
379
+ }
380
+ console.log(`Successfully authenticated as ${currentUser.username}`);
381
+ ```
382
+
383
+ ### insertData(modelName, data, files, user)
384
+
385
+ > Inserts one or more documents, intelligently handling nested relationships.
386
+
387
+ ```javascript
388
+ // Uses the `currentUser` object defined above
389
+ const newProduct = { name: 'Super Widget', price: 99.99, status: 'available' };
390
+ const result = await insertData('product', newProduct, {}, currentUser);
391
+
392
+ if (result.success) {
393
+ console.log(`Successfully inserted document with ID: ${result.insertedIds[0]}`);
394
+ }
395
+ ```
396
+
397
+ ### editData(modelName, filter, data, files, user)
398
+
399
+ > Updates existing data matching the filter.
400
+
401
+ Example:
402
+
403
+ ```javascript
404
+ await editData(
405
+ "userProfile",
406
+ { _id: "507f1f77bcf86cd799439011" },
407
+ { bio: "Updated bio text" },
408
+ null, // No files
409
+ currentUser
410
+ );
411
+ ```
412
+
413
+ ### patchData(modelName, filter, data, files, user)
414
+
415
+ > Partially updates data (only modifies specified fields).
416
+
417
+ Example:
418
+
419
+ ```javascript
420
+ await patchData(
421
+ "settings",
422
+ { userId: "507f1f77bcf86cd799439011" },
423
+ { theme: "dark" },
424
+ null,
425
+ currentUser
426
+ );
427
+ ```
428
+
429
+ ### deleteData(modelName, filter, user)
430
+
431
+ >Deletes data with cascading relation cleanup.
432
+
433
+ Examples:
434
+
435
+ ```javascript
436
+ // Delete by IDs
437
+ await deleteData("comments", ["61d1f1a9e3f1a9e3f1a9e3f1"], user);
438
+
439
+ // Delete by filter
440
+ await deleteData("logs", { createdAt: { $lt: "2023-01-01" } }, user);
441
+ ```
442
+
443
+ ### searchData(query, user)
444
+
445
+ Powerful search with relation expansion and filtering.
446
+
447
+ Query Options:
448
+
449
+ - model: Model name to search
450
+ - filter: MongoDB-style filter
451
+ - depth: Relation expansion depth (default: 1)
452
+ - limit/page: Pagination
453
+ - sort: Sorting criteria
454
+
455
+ Example:
456
+ ```javascript
457
+ const results = await searchData({
458
+ model: "blogPost",
459
+ filter: { status: "published" },
460
+ depth: 2, // Expand author and comments
461
+ limit: 10,
462
+ sort: "createdAt:DESC"
463
+ }, user);
464
+ ```
465
+
466
+ ## Import/Export
467
+ ### importData(options, files, user)
468
+ > Imports data from Excel / JSON / CSV files.
469
+
470
+ Supported Formats:
471
+
472
+ - Excel with headers or field mapping
473
+ - CSV with headers or field mapping
474
+ - JSON arrays
475
+ - JSON with model-keyed objects
476
+
477
+ Example:
478
+
479
+ ```javascript
480
+ const result = await importData(
481
+ {
482
+ model: "products",
483
+ hasHeaders: true
484
+ },
485
+ {
486
+ file: req.files.myFileField // from multipart body
487
+ },
488
+ currentUser
489
+ );
490
+ ```
491
+
492
+ ### exportData(options, user)
493
+ > Exports data to a structured format.
494
+
495
+ Example:
496
+
497
+ ```javascript
498
+ await exportData(
499
+ {
500
+ models: ["products", "categories"],
501
+ depth: 1, // Include relations
502
+ lang: "fr" // Localized data
503
+ },
504
+ currentUser
505
+ );
506
+ // Returns: { success: true, data: { products: [...], categories: [...] } }
507
+ ```
508
+
509
+ ## Backup & Restore
510
+ ### dumpUserData(user)
511
+ > Creates an encrypted backup of user data.
512
+
513
+ Features:
514
+
515
+ - Automatic encryption
516
+ - S3 or local storage
517
+ - Retention policies by plan (daily/weekly/monthly)
518
+
519
+ Example:
520
+
521
+ ```javascript
522
+ await dumpUserData(currentUser);
523
+ // Backup saved to S3 or ./backups/
524
+ ```
525
+
526
+ ### loadFromDump(user, options)
527
+
528
+ > Restores user data from backup.
529
+
530
+ Options:
531
+ - modelsOnly: Restore only model definitions
532
+
533
+ Example:
534
+
535
+ ```javascript
536
+ await loadFromDump(currentUser, { modelsOnly: false });
537
+ // Full restore including data
538
+ ```
539
+
540
+ ## Pack Management
541
+
542
+ ### installPack(packId, user, lang)
543
+
544
+ > Installs a data pack.
545
+
546
+ Example:
547
+
548
+ ```javascript
549
+ const result = await installPack([
550
+ {
551
+ "name": "My custom pack",
552
+ "description": "Markdown **description** of the pack",
553
+ "tags": ["customPack", "tag1", "tag2"],
554
+ "models": [
555
+ "env", // default model
556
+ {
557
+ "name": "post",
558
+ "description": "Defines a post",
559
+ "fields": [
560
+ {"name": "subject", "type": "string", "required": true},
561
+ ]
562
+ }, // or custom
563
+ ],
564
+ "data": {
565
+ "all": { // all languages installed data
566
+ "post": [
567
+ {"subject": "My pack first data"}
568
+ ]
569
+ },
570
+ "en": { // English specific installed data
571
+ "post": [
572
+ {"subject": "My english first post"}
573
+ ]
574
+ }
575
+ }
576
+ }
577
+ ], user, "en");
578
+ // Returns installation summary
579
+ ```
580
+
581
+ ```javascript
582
+ const result = await installPack("61d1f1a9e3f1a9e3f1a9e3f1", user, "en");
583
+ // Returns installation summary
584
+ ```
585
+
586
+ > You can also open the pack gallery to see the JSON structure of each pack, before installing them.
587
+
588
+
589
+ ---
590
+ ### Data Auditing & History
591
+ data-primals-engine includes a built-in, automatic auditing system that creates a complete history for every record in your database.
592
+
593
+ >This feature is essential for traceability, debugging, and maintaining a clear audit trail of all data manipulations.
594
+
595
+ #### How It Works
596
+ The history feature is non-intrusive and fully automatic.
597
+
598
+ Whenever you use the standard data management functions (insertData, patchData, deleteData, etc.), the engine performs two actions:
599
+ 1. It executes the requested operation (create, update, or delete) on the target document.
600
+ 2. It saves a complete "snapshot" of the document's state into a dedicated history collection.
601
+
602
+ >Each history entry contains the original data along with crucial metadata:
603
+ - `_op`: The type of operation (i for insert, u for update, d for delete).
604
+ - `_v`: The version number of the record.
605
+ - `_user`: The username of the user who performed the action.
606
+ - `_updatedAt`: The timestamp of the operation.
607
+ - `_rid`: The ID of the original record, linking all history entries together.
608
+
609
+ ### Accessing the History
610
+ You can retrieve the full history for any record via a simple API endpoint:
611
+ ```x-sh
612
+ curl -X GET http://localhost:7633/api/data/history/:modelName/:recordId
613
+ ```
614
+
615
+ ---
616
+
617
+ ## Workflows: Automate Your Business Logic
618
+
619
+ > Workflows are the automation engine of your application.
620
+
621
+ They allow you to define complex business processes that run in response to specific events, without writing custom code.
622
+
623
+ This is perfect for tasks like **sending welcome emails**, managing **order fulfillment**, or triggering data synchronization.
624
+
625
+ A workflow is composed of two main parts: **Triggers** and **Actions**.
626
+
627
+ > A 'workflowTrigger' is the event that initiates a workflow run.
628
+ - **DataAdded**: Fires when a new document is created (e.g., a new user signs up).
629
+ - **DataEdited**: Fires when a document is updated (e.g., an order status changes to "shipped").
630
+ - **DataDeleted**: Fires when a document is removed.
631
+ - **Scheduled**: Runs at a specific time or interval using a Cron expression (e.g., 0 0 * * * for a nightly data cleanup job).
632
+ - **Manual**: Triggered on-demand via an API call, allowing you to integrate workflows into any part of your application.
633
+
634
+ > A 'workflowAction' is the individual steps a workflow executes. You can chain them together to create sophisticated logic.
635
+ - **CreateData**: Create a new document in any model.
636
+ - **UpdateData**: Modify one or more existing documents that match a filter.
637
+ - **SendEmail**: Send a transactional email using dynamic data from the trigger.
638
+ - **HttpRequest**: Make an HTTP request (GET, POST, etc.) to an external service or API.
639
+ - **ExecuteScript**: Run a custom JavaScript snippet for complex logic, data transformation, or conditional branching.
640
+ - **GenerateAIContent**: Use an integrated AI provider (like OpenAI or Gemini) to generate text, summarize content, or make decisions.
641
+ - **Wait**: Pause the workflow for a specific duration before continuing to the next step
642
+
643
+ See the details of the workflow models for more details.
644
+
645
+ ## ⚑ Dynamic API Endpoints
646
+ Beyond standard CRUD operations, data-primals-engine allows you to create your own custom API endpoints directly from the UI. This feature acts like a built-in serverless function environment, enabling you to write custom business logic, integrate with third-party services, or create complex data aggregations on the fly.
647
+
648
+ Your code is executed in a secure, isolated sandbox, with access to the core data functions and the incoming request context.
649
+
650
+ ### How It Works
651
+ Define an Endpoint: You create a new document in the endpoint model.
652
+ Write Your Logic: In the code field, you write the JavaScript that will be executed.
653
+ Activate: The engine automatically listens for requests on /api/actions/:path that match your endpoint's definition.
654
+
655
+ ### The endpoint Model
656
+ To create a custom endpoint, you need to define a document with the following structure:
657
+ ```json
658
+ {
659
+ "name": "GetContactPostCount",
660
+ "path": "postCount/:name",
661
+ "method": "GET",
662
+ "code": "const posts = await db.find('content', { author: { $find: { $eq: ['$lastName', request.params.name]}}}); return { postCount: posts.length };",
663
+ "isActive": true,
664
+ "isPublic": true
665
+ }
666
+ ```
667
+ | Field | Type | Description |
668
+ |:---------|:--------|:---------------------------------------------------------------------|
669
+ | name | string | A descriptive name for your endpoint (e.g., "Calculate User Stats"). |
670
+ | path | string | The URL path. It can include parameters like :id. |
671
+ | method | enum | The HTTP method: GET, POST, PUT, PATCH, or DELETE. |
672
+ | code | code | The JavaScript code to execute when the endpoint is called. |
673
+ | isActive | boolean | A flag to enable or disable the endpoint without deleting it. |
674
+ | isPublic | boolean | A flag to enable public access (private by default). |
675
+ ---
676
+
677
+ ### The Execution Context
678
+ Your JavaScript code runs in an async context and has access to several global objects that are securely injected into the sandbox:
679
+ Your current user is used to make the calls.
680
+
681
+ #### The context Object
682
+ > This object contains all the information about the incoming HTTP request.
683
+ - context.request.**body**: The parsed request body (for POST, PUT, PATCH).
684
+ - context.request.**query**: The URL query parameters as an object.
685
+ - context.request.**params**: The URL path parameters (e.g., username from /user-summary/:username).
686
+ - context.request.**headers**: The incoming request headers.
687
+
688
+ #### The db Object
689
+ > A secure API to interact with the database. All methods are async and must be awaited. They automatically operate within the authenticated user's permissions.
690
+ - await db.**create**(modelName, dataObject): Inserts a new document.
691
+ - await db.**find**(modelName, filter): Finds multiple documents. Returns an array.
692
+ - await db.**findOne**(modelName, filter): Finds a single document. Returns an object or null.
693
+ - await db.**update**(modelName, filter, updateObject): Partially updates documents matching the filter (similar to a PATCH).
694
+ - await db.**delete**(modelName, filter): Deletes documents matching the filter.
695
+
696
+ #### The logger Object
697
+ > A safe way to log messages from your script. These logs will be collected and can be returned in the API response if an error occurs, which is very useful for debugging.
698
+ - logger.**info**(...args)
699
+ - logger.**warn**(...args)
700
+ - logger.**error**(...args)
701
+
702
+ #### The env Object
703
+ > Provides access to the user-defined variables stored in the env model, not the server's process.env.
704
+ - await env.**get**(variableName): Retrieves a single environment variable's value.
705
+ - await env.**getAll**(): Retrieves all user environment variables as an object.
706
+
707
+ #### Example: Creating a User Summary Endpoint
708
+ Let's create an endpoint that fetches a user's profile and counts how many posts they have published.
709
+ 1. Create the Endpoint Document
710
+ Create a new document in the endpoint model with the following data:
711
+ ```json
712
+ {
713
+ "name": "Get User Summary",
714
+ "path": "user-summary/:username",
715
+ "method": "GET",
716
+ "isActive": true,
717
+ "code": "const { username } = context.request.params;\n\n if (!username) {\n logger.error('Username parameter is required.');\n return { success: false, error: 'Username is required.' };\n }\n\n logger.info(`Fetching summary for user: ${username}`);\n\n // Fetch the user profile using the sandboxed db API\n const userProfile = await db.findOne('userProfile', { username: username });\n\n if (!userProfile) {\n return { success: false, error: 'User not found' };\n }\n\n // Count the user's published posts\n const posts = await db.find('post', { \n authorId: userProfile._id.toString(), \n status: 'published' \n });\n\n return {\n profile: userProfile,\n publishedPosts: posts.length\n };\n});",
718
+ }
719
+ ```
720
+ 2. Call the New Endpoint
721
+ You can now call this custom endpoint like any other API route:
722
+
723
+ Expected response :
724
+ ```json
725
+ {
726
+ "profile": {
727
+ "_id": "60d0fe4f5311236168a109ca",
728
+ "username": "demo",
729
+ "bio": "A demo user profile.",
730
+ "...": "..."
731
+ },
732
+ "publishedPosts": 15
733
+ }
734
+
735
+ ```
736
+
737
+ ### Pluggable SSO Authentication (Google, SAML, Azure AD)
738
+
739
+ `data-primals-engine` features a powerful and modular Single Sign-On (SSO) system built on Passport.js. This allows you to easily integrate with various enterprise and social identity providers. The core engine remains lightweight, and you only enable the providers you need.
740
+
741
+ #### How It Works
742
+
743
+ The engine provides a central `Sso` component that manages authentication logic. Each provider (Google, SAML, etc.) is an independent module that "plugs into" this central component.
744
+
745
+ To enable an SSO provider, follow these three steps:
746
+
747
+ #### Example: Enabling Google Sign-In
748
+
749
+ **1. Install the Provider's Library**
750
+
751
+ The required Passport strategy is a `peerDependency`. You must install it in your project:
752
+ ```bash
753
+ npm install passport-google-oauth20
754
+ ```
755
+
756
+ **2. Enable the Module**
757
+
758
+ To enable the module in your next engine initilization, just add it to the `modules` array:
759
+ ```javascript
760
+ Config.Set("modules", ["auth-google", "..."]);
761
+ ```
762
+
763
+ **3. Set Environment Variables**
764
+
765
+ Create or update your `.env` file with the credentials obtained from the Google Cloud Console:
766
+ ```env
767
+ GOOGLE_CLIENT_ID=your-google-client-id
768
+ GOOGLE_CLIENT_SECRET=your-google-client-secret
769
+ ```
770
+
771
+ The login flow will now be available at `/api/auth/google`.
772
+
773
+ #### Other Providers
774
+
775
+ The process is identical for other supported providers:
776
+
777
+ - **SAML**:
778
+ 1. `npm install passport-saml-encrypted`
779
+ 2. Enable the `auth-saml` module.
780
+ 3. Set `SAML_ENTRY_POINT`, `SAML_ISSUER`, `SAML_CERT`, and `SAML_DECRYPTION_KEY` environment variables.
781
+
782
+ - **Microsoft Azure AD**:
783
+ 1. `npm install passport-azure-ad`
784
+ 2. Enable the `auth-microsoft` module.
785
+ 3. Set `MICROSOFT_CLIENT_ID`, `MICROSOFT_CLIENT_SECRET`, and `MICROSOFT_TENANT_ID` environment variables.
786
+
787
+ This modular approach makes it simple to extend the engine with any Passport-compatible strategy to meet your authentication needs.
788
+
789
+ See implementations in the `modules` directory.
790
+
791
+ ---
792
+ ## Extensibility
793
+
794
+ ### Events (Triggers) Table
795
+ > You can use the events below to access the engine and manipulate API responses.
796
+ > It is useful for custom modules or middlewares for your application.
797
+
798
+ Just use
799
+
800
+ ```javascript
801
+ Event.Listen("OnDataAdded", (data) => {
802
+ my_callback()
803
+ }, "event", "user");
804
+ ```
805
+
806
+ or the system version
807
+ ```javascript
808
+ Event.Listen("OnDataAdded", (engine, data) => {
809
+ my_callback()
810
+ }, "event", "system");
811
+ ```
812
+
813
+ | Event | Description | Scope | Triggered by | Arguments (Payload) |
814
+ |:-----------------|:------------------------------------------------------------------------|:--------------|:---------------------|:-----------------------------------------------------------------------------------------------------------------------------------------|
815
+ | OnServerStart | Triggered once the HTTP server is started and listening. | System | engine.start() | engine |
816
+ | OnServerStop | Triggered right after the HTTP server is stopped. | System | engine.stop() | engine |
817
+ | OnModelsLoaded | Triggered after the initial models are loaded and validated at startup. | System | setupInitialModels() | engine, dbModels |
818
+ | OnModelsDeleted | Triggered after all models are deleted via the reset function. | System | engine.resetModels() | engine |
819
+ | OnUserDataDumped | Triggered after a user's data has been backed up (dumped). | System | jobDumpUserData() | engine |
820
+ | OnDataRestored | Triggered after a user's data has been restored from a backup. | System | loadFromDump() | (none) |
821
+ | OnPackInstalled | Triggered after a data pack has been successfully installed. | System | installPack() | pack |
822
+ | OnModelEdited | Triggered after a model definition has been modified. | System & User | editModel() | System: engine, newModel (Pipeline*)<br>User: newModel (or the version modified by the system) |
823
+ | OnDataAdded | Triggered after new data has been inserted. | System & User | insertData() | System: engine, insertedIds (Pipeline*)<br>User: insertedIds (or the version modified by the system) |
824
+ | OnDataDeleted | Triggered just after data is actually deleted. | System & User | deleteData() | System: engine, {model, filter} (Pipeline*)<br>User: {model, filter} |
825
+ | OnDataSearched | Triggered after a data search. | System & User | searchData() | System: engine, {data, count} (Pipeline*)<br>User: {data, count} (or the version modified by the system) |
826
+ | OnDataExported | Triggered after a data export. | System & User | exportData() | System: engine, exportResults, modelsToExport (Pipeline*)<br>User: exportResults, modelsToExport (or the version modified by the system) |
827
+ | OnDataInsert | Triggered just before data insertion. It will use the overrided data. | System | internal | (data) |
828
+ | OnDataValidate | Triggered to override validation check. | System | internal | (value, field, data) |
829
+ | OnDataFilter | Triggered to override data filtering operation. | System | internal | (filteredValue, field, data) |
830
+ | OnEmailTemplate | Triggered to override custom email templates | System | internal | (templateData, lang) |
831
+
832
+ ### Triggering events
833
+
834
+ If you want to provide your own hooks, you can call :
835
+ ```javascript
836
+ const result = await Event.Trigger("OnMyCustomEvent", "event", "user", ...args);
837
+ ```
838
+ Results are merged together if multiple events are triggered.
839
+ - strings are concatenated
840
+ - numbers are added
841
+ - booleans are ANDed
842
+ - arrays are concatenated
843
+ - objects are merged using spread operator
844
+
845
+ ---
846
+
847
+ ## βš›οΈ Frontend Integration (React)
848
+
849
+ This engine is designed to work seamlessly with its dedicated client library, **`data-primals-engine/client`**. This library provides a complete set of React hooks and UI components to build a rich, data-centric user interface on top of the backend.
850
+
851
+ While this README focuses on the backend engine and its API, you can find detailed instructions on how to integrate the client part in your React application here:
852
+
853
+ ➑️ **[View the Frontend Integration Guide](https://github.com/anonympins/data-primals-engine/tree/develop/client)**
854
+
855
+
856
+ ---
857
+
858
+ ## 🀝 Contributing
859
+
860
+ Find the issues available for [contributions here](https://github.com/anonympins/data-primals-engine/issues?q=is%3Aissue%20state%3Aopen%20label%3A%22help%20wanted%22%20no%3Aassignee)
861
+
862
+ 1. Fork the repo
863
+ 2. Create your feature branch: `git checkout -b feature/your-feature`
864
+ 3. Launch ```npm run dev``` and make your changes with hot-reload on local port
865
+ 3. Commit changes: `git commit -m "Add new feature"`
866
+ 4. Push to your branch: `git push origin feature/your-feature`
867
+ 5. Open a pull request
868
+
869
+ Star ⭐ the repo if you find it useful!
870
+
871
+ ---
872
+
873
+ ## πŸ“„ License
874
+ Distributed under the **MIT License**. See `LICENSE` file.
875
+
876
+ ---
877
+
878
+ ## [πŸ”Ό](#data-primals-engine) Back to Top