data-primals-engine 1.4.3 → 1.5.1

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 (77) hide show
  1. package/README.md +913 -867
  2. package/client/package-lock.json +49 -0
  3. package/client/package.json +1 -0
  4. package/client/src/AddWidgetTypeModal.jsx +47 -43
  5. package/client/src/App.jsx +3 -7
  6. package/client/src/App.scss +25 -3
  7. package/client/src/AssistantChat.jsx +363 -323
  8. package/client/src/AssistantChat.scss +30 -12
  9. package/client/src/Dashboard.jsx +480 -396
  10. package/client/src/Dashboard.scss +1 -1
  11. package/client/src/DashboardHtmlViewItem.jsx +147 -0
  12. package/client/src/DashboardView.jsx +104 -19
  13. package/client/src/DataEditor.jsx +12 -5
  14. package/client/src/DataLayout.jsx +805 -762
  15. package/client/src/DataLayout.scss +14 -0
  16. package/client/src/DataTable.jsx +63 -77
  17. package/client/src/Dialog.scss +1 -1
  18. package/client/src/Field.jsx +591 -322
  19. package/client/src/FlexDataRenderer.jsx +2 -0
  20. package/client/src/FlexTreeUtils.js +1 -1
  21. package/client/src/FlexViewCard.jsx +44 -0
  22. package/client/src/HistoryDialog.jsx +47 -14
  23. package/client/src/HtmlViewBuilderModal.jsx +91 -0
  24. package/client/src/HtmlViewBuilderModal.scss +18 -0
  25. package/client/src/HtmlViewCard.jsx +44 -0
  26. package/client/src/HtmlViewCard.scss +35 -0
  27. package/client/src/KPIDialog.jsx +11 -1
  28. package/client/src/KanbanCard.jsx +1 -2
  29. package/client/src/ModelCreator.jsx +6 -6
  30. package/client/src/ModelCreatorField.jsx +74 -31
  31. package/client/src/ModelList.jsx +93 -54
  32. package/client/src/Notification.jsx +136 -136
  33. package/client/src/Notification.scss +0 -18
  34. package/client/src/Pagination.jsx +5 -3
  35. package/client/src/RelationField.jsx +354 -258
  36. package/client/src/RelationSelectorWidget.jsx +173 -0
  37. package/client/src/constants.js +1 -1
  38. package/client/src/contexts/ModelContext.jsx +10 -1
  39. package/client/src/contexts/UIContext.jsx +72 -63
  40. package/client/src/filter.js +262 -212
  41. package/client/src/hooks/useTutorials.jsx +62 -65
  42. package/client/src/hooks/useValidation.js +75 -0
  43. package/client/src/translations.js +26 -24
  44. package/package.json +3 -1
  45. package/perf/README.md +147 -0
  46. package/perf/artillery-hooks.js +37 -0
  47. package/perf/perf-shot-hardwork.yml +84 -0
  48. package/perf/perf-shot-search.yml +45 -0
  49. package/perf/setup.yml +26 -0
  50. package/server.js +1 -1
  51. package/src/constants.js +3 -28
  52. package/src/core.js +15 -1
  53. package/src/data.js +1 -1
  54. package/src/defaultModels.js +63 -7
  55. package/src/email.js +5 -2
  56. package/src/engine.js +5 -3
  57. package/src/filter.js +5 -3
  58. package/src/i18n.js +710 -10
  59. package/src/modules/assistant/assistant.js +151 -19
  60. package/src/modules/bucket.js +14 -16
  61. package/src/modules/data/data.backup.js +11 -8
  62. package/src/modules/data/data.core.js +118 -92
  63. package/src/modules/data/data.history.js +531 -492
  64. package/src/modules/data/data.js +9 -56
  65. package/src/modules/data/data.operations.js +3282 -2999
  66. package/src/modules/data/data.relations.js +686 -686
  67. package/src/modules/data/data.routes.js +118 -24
  68. package/src/modules/data/data.scheduling.js +2 -1
  69. package/src/modules/data/data.validation.js +85 -3
  70. package/src/modules/file.js +247 -236
  71. package/src/modules/user.js +4 -1
  72. package/src/modules/workflow.js +9 -10
  73. package/src/openai.jobs.js +2 -0
  74. package/src/packs.js +5482 -5461
  75. package/src/providers.js +22 -7
  76. package/test/data.integration.test.js +136 -2
  77. package/test/import_export.integration.test.js +1 -1
package/README.md CHANGED
@@ -1,867 +1,913 @@
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.js20
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
+ ### Programmatic Configuration
115
+
116
+ In addition to environment variables, you can programmatically override most of the application's internal constants at runtime. This is useful for fine-tuning performance, limits, or behavior without restarting the server.
117
+
118
+ The engine exposes a `Config` object for this purpose. You can modify any constant defined in `src/constants.js`.
119
+
120
+ To override a constant, use the `Config.Set()` method **before** initializing the engine:
121
+
122
+ ```javascript
123
+ import express from "express";
124
+ import { Engine, Config } from 'data-primals-engine';
125
+
126
+ // Override default constants before engine initialization
127
+ Config.Set("maxRequestData", 1000); // Increase max data per request
128
+ Config.Set("maxFileSize", 50 * 1024 * 1024); // Allow larger file uploads (50MB)
129
+
130
+ const app = express();
131
+ const engine = await Engine.Create({ app });
132
+ ```
133
+
134
+ ### Start the server
135
+ ```bash
136
+ # Development mode
137
+ npm run devserver
138
+
139
+ # Production mode
140
+ npm run server
141
+ ```
142
+
143
+ By default, the app runs on port **7633** : http://localhost:7633
144
+
145
+
146
+ ---
147
+
148
+ ## 🧠 Concepts
149
+
150
+ ### Authentication & Authorization
151
+
152
+ 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.
153
+
154
+ 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.
155
+
156
+ ### Model generation
157
+ Models are the way to handle structured data. They organize data and they can be declared in JSON.
158
+
159
+ ```json
160
+ {
161
+ "name": "product",
162
+ "description": "E-commerce product schema",
163
+ "fields": [
164
+ { "name": "name", "type": "string", "required": true },
165
+ { "name": "price", "type": "number", "required": true },
166
+ { "name": "stock", "type": "number", "default": 0 },
167
+ { "name": "category", "type": "relation", "relation": "taxonomy",
168
+ "relationFilter": { "$eq": ["$type", "category"] }
169
+ },
170
+ { "name": "tags", "type": "relation", "relation": "taxonomy", "multiple": true,
171
+ "relationFilter": { "$eq": ["$type", "keyword"] }
172
+ }
173
+ ]
174
+ }
175
+ ```
176
+
177
+ ### Custom fields types
178
+
179
+ | Type | Description | Properties/Notes |
180
+ |:------------|:------------------------------------------------------------------------------------|:--------------------------------------------------------------------------|
181
+ | string | Character string. | minLength, maxLength |
182
+ | string_t | International character string ID. | same as string, translated in { key, value } |
183
+ | number | Numeric value (integer or float). | min, max |
184
+ | boolean | Boolean value (true/false). | – |
185
+ | date | Stores a ISO date. | – |
186
+ | datetime | Stores an ISO date and time. | – |
187
+ | richtext | Rich text field (HTML) for WYSIWYG editors. | |
188
+ | richtext_t | International rich text field (HTML) for WYSIWYG editors. | i18n |
189
+ | email | String validated as an email address. | – |
190
+ | password | String that will be automatically hashed. | – |
191
+ | enum | Allows selecting a value from a predefined list. | items: ["value1", "value2"] |
192
+ | relation | Creates a link to a document in another model. | relation: "target_model_name", multiple: true/false |
193
+ | file | For uploading a file (stored on S3 if configured). | allowedTypes:['image/jpeg', 'image/png', 'image/bmp'], maxSize: 1024*1000 |
194
+ | image | Specialized file type for images, with preview. | – |
195
+ | array | Stores a list of values. | itemsType: 'enum' // any type except relations |
196
+ | object | Stores a nested JSON object. – | |
197
+ | code | Stores language="*" as string, stores language="json" as arbitrary JSON structure. | language="json" conditionBuilder=true |
198
+ | color | Stores an hexadecimal value of an RGB color | '#FF0000' |
199
+ | model | Stores a model by name | – |
200
+ | modelField | Stores a model field path | – |
201
+
202
+ ### Other model features
203
+ - Handles up to 2,000 direct relations by default (can be customized). For larger datasets, use intermediate collections
204
+ - Automatic indexing on key fields
205
+ - Custom indexing on fields
206
+ - Anonymizable fields (encrypted for API users)
207
+
208
+ ### Model constraints
209
+ ```javascript
210
+ {
211
+ "name": "modelName",
212
+ "fields": [
213
+ { "name": "fieldName1", .... },
214
+ { "name": "fieldName2", .... }
215
+ ],
216
+ "constraints": [
217
+ // uniqueness
218
+ { "name": "uniqueConstraint", type: "unique", keys: ["fieldName1", "fieldName2"] }
219
+ ]
220
+ }
221
+ ```
222
+
223
+ ## 🏗️ Use Case Examples
224
+
225
+ ### 🛒 E-Commerce Backoffice
226
+ - Install ecommerce-starter pack
227
+ - Add products via API/UI
228
+ - Customize order workflows
229
+
230
+ ### 🎫 Support Ticket System
231
+ - Create ticket model with [open, pending, resolved] statuses
232
+ - Configure notification workflows
233
+ - Add custom endpoints or dashboards/kpi for analytics
234
+
235
+ ### 🤖 AI Chatbot
236
+ - Define your model
237
+ - Set up workflow: "When new entry → generate AI content"
238
+
239
+ ### 📧 Email Campaign Management
240
+ The "Marketing & Campaigning" starter pack provides a powerful solution for sending large-scale email campaigns without overloading your server.
241
+
242
+ - **Install the Pack**: A single command installs the necessary models (`campaign`, `audience`) and a sophisticated workflow.
243
+ - **Dynamic Audiences**: Create target audiences with MongoDB filters. For example, select all contacts with the "newsletter" tag or located in a specific country.
244
+ - **Personalized Content**: Use variables like `{recipient.firstName}` in the subject and body of your emails for a personal touch.
245
+ - **Automated & Scalable Sending**: When you schedule a campaign, a pre-configured workflow takes over:
246
+ - It processes your audience in small batches (e.g., 10 recipients at a time).
247
+ - It sends emails to each batch and waits before processing the next, ensuring stability.
248
+ - It tracks processed recipients to avoid duplicates and allow the campaign to be safely paused and resumed.
249
+ - Once all emails are sent, the campaign is automatically marked as "completed".
250
+
251
+ This use case demonstrates how starter packs and workflows can automate complex, performance-critical business logic right out of the box.
252
+
253
+ ---
254
+
255
+ ## 📁 Project Structure
256
+ ```
257
+ data-primals-engine/
258
+ ├── src/
259
+ │ ├── middlewares/
260
+ │ ├── migrations/
261
+ │ ├── modules/
262
+ │ ├── workers/
263
+ │ ├── engine.js // The Express engine that serves the API
264
+ │ ├── constants.js // The inner-application constants definitions
265
+ │ ├── packs.js // The packs that will be loaded and available with installPack() method
266
+ │ ├── defaultModels.js // The default models available at startup.
267
+ │ ├── ...
268
+ └── server.js
269
+ ```
270
+
271
+ ---
272
+
273
+ ## 🔌 API Examples (using `curl`)
274
+
275
+ ### 📁 Model Management
276
+
277
+ #### Create a model
278
+ > Defines a new data model (schema) in the system. The request body must contain the model's name and an array of field definitions.
279
+ ```bash
280
+ curl -X POST http://localhost:7633/api/model?_user=demo \
281
+ -H "Authorization: Bearer demotoken" \
282
+ -H "Content-Type: application/json" \
283
+ -d '{
284
+ "name": "newModel",
285
+ "description": "A test model.",
286
+ "fields": [
287
+ {"name": "title", "type": "string", "required": true},
288
+ {"name": "price", "type": "number"}
289
+ ]
290
+ }'
291
+ ```
292
+
293
+ #### Update a model
294
+ > Modifies an existing model's structure using its unique ID. This allows you to add, remove, or change fields.
295
+ ```bash
296
+ curl -X PUT http://localhost:7633/api/model/60d0fe4f5311236168a109ca?_user=demo \
297
+ -H "Authorization: Bearer demotoken" \
298
+ -H "Content-Type: application/json" \
299
+ -d '{
300
+ "name": "updatedModel",
301
+ "description": "Updated description.",
302
+ "fields": [
303
+ {"name": "title", "type": "string", "required": true},
304
+ {"name": "status", "type": "enum", "items": ["active", "inactive"]}
305
+ ]
306
+ }'
307
+ ```
308
+
309
+ #### Delete a model
310
+ > Permanently deletes a model definition using its name. This action is irreversible.
311
+ ```bash
312
+ curl -X DELETE "http://localhost:7633/api/model?_user=demo&name=newModel" \
313
+ -H "Authorization: Bearer demotoken"
314
+ ```
315
+
316
+ ### 🗂️ Data Management
317
+
318
+ #### Create a document
319
+ > Creates a single new document in the specified model. The `data` object must conform to the model's schema.
320
+ ```bash
321
+ curl -X POST http://localhost:7633/api/data?_user=demo \
322
+ -H "Authorization: Bearer demotoken" \
323
+ -H "Content-Type: application/json" \
324
+ -d '{
325
+ "model": "product",
326
+ "data": {
327
+ "name": "Widget Extraordinaire",
328
+ "price": 99.99,
329
+ "stock": 150,
330
+ "published": true
331
+ }
332
+ }'
333
+ ```
334
+
335
+
336
+ #### Search documents
337
+ > Searches for documents using a MongoDB-style filter. This endpoint is ideal for complex queries, pagination, and sorting.
338
+
339
+ ```bash
340
+ curl -X POST http://localhost:7633/api/data/search?_user=demo \
341
+ -H "Authorization: Bearer demotoken" \
342
+ -H "Content-Type: application/json" \
343
+ -d '{
344
+ "model": "product",
345
+ "filter": { "$gt" : ["$price", 50] }
346
+ }'
347
+ ```
348
+
349
+ #### Update a document by ID
350
+ > Updates a single document by its unique ID. The request body contains the fields to be modified.
351
+ ```bash
352
+ curl -X PUT http://localhost:7633/api/data/64a31c123ef59d4c8d55aa99?_user=demo \
353
+ -H "Authorization: Bearer demotoken" \
354
+ -H "Content-Type: application/json" \
355
+ -d '{
356
+ "model": "product",
357
+ "data": { "price": 109.99 }
358
+ }'
359
+ ```
360
+
361
+
362
+ #### Bulk update
363
+ > 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.
364
+ ```bash
365
+ curl -X PUT http://localhost:7633/api/data?_user=demo \
366
+ -H "Authorization: Bearer demotoken" \
367
+ -H "Content-Type: application/json" \
368
+ -d '{
369
+ "model": "product",
370
+ "data": { "stock": 999 }
371
+ }'
372
+ ```
373
+
374
+ #### Delete documents
375
+ > Deletes one or more documents. You can provide an array of `ids` to delete specific documents.
376
+ ```bash
377
+ curl -X DELETE http://localhost:7633/api/data?_user=demo \
378
+ -H "Authorization: Bearer demotoken" \
379
+ -H "Content-Type: application/json" \
380
+ -d '{
381
+ "ids": ["64a31c123ef59d4c8d55aa99"]
382
+ }'
383
+ ```
384
+
385
+ ## Other operations
386
+
387
+ Make sure you use the code below to initialize the user :
388
+ ```javascript
389
+ import express from "express";
390
+ import {Engine, insertData, searchData } from 'data-primals-engine';
391
+
392
+ // Ensure the engine is initialized
393
+
394
+ const app = express();
395
+ const engine = await Engine.Create({ app });
396
+ const currentUser = await engine.userProvider.findUserByUsername('demo');
397
+ if (!currentUser) {
398
+ throw new Error("Could not retrieve the user. Please check credentials or user provider.");
399
+ }
400
+ console.log(`Successfully authenticated as ${currentUser.username}`);
401
+ ```
402
+
403
+ ### insertData(modelName, data, files, user)
404
+
405
+ > Inserts one or more documents, intelligently handling nested relationships.
406
+
407
+ ```javascript
408
+ // Uses the `currentUser` object defined above
409
+ const newProduct = { name: 'Super Widget', price: 99.99, status: 'available' };
410
+ const result = await insertData('product', newProduct, {}, currentUser);
411
+
412
+ if (result.success) {
413
+ console.log(`Successfully inserted document with ID: ${result.insertedIds[0]}`);
414
+ }
415
+ ```
416
+
417
+ ### editData(modelName, filter, data, files, user)
418
+
419
+ > Updates existing data matching the filter.
420
+
421
+ Example:
422
+
423
+ ```javascript
424
+ await editData(
425
+ "userProfile",
426
+ { _id: "507f1f77bcf86cd799439011" },
427
+ { bio: "Updated bio text" },
428
+ null, // No files
429
+ currentUser
430
+ );
431
+ ```
432
+
433
+ ```javascript
434
+ await editData(
435
+ "resource",
436
+ { source: "507f1f77bcf86cd799439011" },
437
+ { "file[]": {
438
+ "path": "C:/Users/.../test-upload-on-insert.txt",
439
+ "name": 'test-upload-on-insert.txt',
440
+ "type": 'text/plain',
441
+ "size": 1524,
442
+ "lastModifiedDate": new Date(),
443
+ }}, // No files
444
+ currentUser
445
+ );
446
+ ```
447
+
448
+ ### patchData(modelName, filter, data, files, user)
449
+
450
+ > Partially updates data (only modifies specified fields).
451
+
452
+ Example:
453
+
454
+ ```javascript
455
+ await patchData(
456
+ "settings",
457
+ { userId: "507f1f77bcf86cd799439011" },
458
+ { theme: "dark" },
459
+ null,
460
+ currentUser
461
+ );
462
+ ```
463
+
464
+ ### deleteData(modelName, filter, user)
465
+
466
+ >Deletes data with cascading relation cleanup.
467
+
468
+ Examples:
469
+
470
+ ```javascript
471
+ // Delete by IDs
472
+ await deleteData("comments", ["61d1f1a9e3f1a9e3f1a9e3f1"], user);
473
+
474
+ // Delete by filter
475
+ await deleteData("logs", { createdAt: { $lt: "2023-01-01" } }, user);
476
+ ```
477
+
478
+ ### searchData(query, user)
479
+
480
+ Powerful search with relation expansion and filtering.
481
+
482
+ Query Options:
483
+
484
+ - model: Model name to search
485
+ - filter: MongoDB-style filter
486
+ - depth: Relation expansion depth (default: 1)
487
+ - limit/page: Pagination
488
+ - sort: Sorting criteria
489
+
490
+ Example:
491
+ ```javascript
492
+ const results = await searchData({
493
+ model: "blogPost",
494
+ filter: { status: "published" },
495
+ depth: 2, // Expand author and comments
496
+ limit: 10,
497
+ sort: "createdAt:DESC"
498
+ }, user);
499
+ ```
500
+
501
+ ## Import/Export
502
+ ### importData(options, files, user)
503
+ > Imports data from Excel / JSON / CSV files.
504
+
505
+ Supported Formats:
506
+
507
+ - Excel with headers or field mapping
508
+ - CSV with headers or field mapping
509
+ - JSON arrays
510
+ - JSON with model-keyed objects
511
+
512
+ Example:
513
+
514
+ ```javascript
515
+ const result = await importData(
516
+ {
517
+ model: "products",
518
+ hasHeaders: true
519
+ },
520
+ {
521
+ file: req.files.myFileField // from multipart body
522
+ },
523
+ currentUser
524
+ );
525
+ ```
526
+
527
+ ### exportData(options, user)
528
+ > Exports data to a structured format.
529
+
530
+ Example:
531
+
532
+ ```javascript
533
+ await exportData(
534
+ {
535
+ models: ["products", "categories"],
536
+ depth: 1, // Include relations
537
+ lang: "fr" // Localized data
538
+ },
539
+ currentUser
540
+ );
541
+ // Returns: { success: true, data: { products: [...], categories: [...] } }
542
+ ```
543
+
544
+ ## Backup & Restore
545
+ ### dumpUserData(user)
546
+ > Creates an encrypted backup of user data.
547
+
548
+ Features:
549
+
550
+ - Automatic encryption
551
+ - S3 or local storage
552
+ - Retention policies by plan (daily/weekly/monthly)
553
+
554
+ Example:
555
+
556
+ ```javascript
557
+ await dumpUserData(currentUser);
558
+ // Backup saved to S3 or ./backups/
559
+ ```
560
+
561
+ ### loadFromDump(user, options)
562
+
563
+ > Restores user data from backup.
564
+
565
+ Options:
566
+ - modelsOnly: Restore only model definitions
567
+
568
+ Example:
569
+
570
+ ```javascript
571
+ await loadFromDump(currentUser, { modelsOnly: false });
572
+ // Full restore including data
573
+ ```
574
+
575
+ ## Pack Management
576
+
577
+ ### installPack(packId, user, lang)
578
+
579
+ > Installs a data pack.
580
+
581
+ Example:
582
+
583
+ ```javascript
584
+ const result = await installPack([
585
+ {
586
+ "name": "My custom pack",
587
+ "description": "Markdown **description** of the pack",
588
+ "tags": ["customPack", "tag1", "tag2"],
589
+ "models": [
590
+ "env", // default model
591
+ {
592
+ "name": "post",
593
+ "description": "Defines a post",
594
+ "fields": [
595
+ {"name": "subject", "type": "string", "required": true},
596
+ ]
597
+ }, // or custom
598
+ ],
599
+ "data": {
600
+ "all": { // all languages installed data
601
+ "post": [
602
+ {"subject": "My pack first data"}
603
+ ]
604
+ },
605
+ "en": { // English specific installed data
606
+ "post": [
607
+ {"subject": "My english first post"}
608
+ ]
609
+ }
610
+ }
611
+ }
612
+ ], user, "en");
613
+ // Returns installation summary
614
+ ```
615
+
616
+ ```javascript
617
+ const result = await installPack("61d1f1a9e3f1a9e3f1a9e3f1", user, "en");
618
+ // Returns installation summary
619
+ ```
620
+
621
+ > You can also open the pack gallery to see the JSON structure of each pack, before installing them.
622
+
623
+
624
+ ---
625
+ ### Data Auditing & History
626
+ data-primals-engine includes a built-in, automatic auditing system that creates a complete history for every record in your database.
627
+
628
+ >This feature is essential for traceability, debugging, and maintaining a clear audit trail of all data manipulations.
629
+
630
+ #### How It Works
631
+ The history feature is non-intrusive and fully automatic.
632
+
633
+ Whenever you use the standard data management functions (insertData, patchData, deleteData, etc.), the engine performs two actions:
634
+ 1. It executes the requested operation (create, update, or delete) on the target document.
635
+ 2. It saves a complete "snapshot" of the document's state into a dedicated history collection.
636
+
637
+ >Each history entry contains the original data along with crucial metadata:
638
+ - `_op`: The type of operation (i for insert, u for update, d for delete).
639
+ - `_v`: The version number of the record.
640
+ - `_user`: The username of the user who performed the action.
641
+ - `_updatedAt`: The timestamp of the operation.
642
+ - `_rid`: The ID of the original record, linking all history entries together.
643
+
644
+ ### Accessing the History
645
+ You can retrieve the full history for any record via a simple API endpoint:
646
+ ```x-sh
647
+ curl -X GET http://localhost:7633/api/data/history/:modelName/:recordId
648
+ ```
649
+
650
+ ---
651
+
652
+ ## Workflows: Automate Your Business Logic
653
+
654
+ > Workflows are the automation engine of your application.
655
+
656
+ They allow you to define complex business processes that run in response to specific events, without writing custom code.
657
+
658
+ This is perfect for tasks like **sending welcome emails**, managing **order fulfillment**, or triggering data synchronization.
659
+
660
+ A workflow is composed of two main parts: **Triggers** and **Actions**.
661
+
662
+ > A 'workflowTrigger' is the event that initiates a workflow run.
663
+ - **DataAdded**: Fires when a new document is created (e.g., a new user signs up).
664
+ - **DataEdited**: Fires when a document is updated (e.g., an order status changes to "shipped").
665
+ - **DataDeleted**: Fires when a document is removed.
666
+ - **Scheduled**: Runs at a specific time or interval using a Cron expression (e.g., 0 0 * * * for a nightly data cleanup job).
667
+ - **Manual**: Triggered on-demand via an API call, allowing you to integrate workflows into any part of your application.
668
+
669
+ > A 'workflowAction' is the individual steps a workflow executes. You can chain them together to create sophisticated logic.
670
+ - **CreateData**: Create a new document in any model.
671
+ - **UpdateData**: Modify one or more existing documents that match a filter.
672
+ - **SendEmail**: Send a transactional email using dynamic data from the trigger.
673
+ - **HttpRequest**: Make an HTTP request (GET, POST, etc.) to an external service or API.
674
+ - **ExecuteScript**: Run a custom JavaScript snippet for complex logic, data transformation, or conditional branching.
675
+ - **GenerateAIContent**: Use an integrated AI provider (like OpenAI or Gemini) to generate text, summarize content, or make decisions.
676
+ - **Wait**: Pause the workflow for a specific duration before continuing to the next step
677
+
678
+ See the details of the workflow models for more details.
679
+
680
+ ## Dynamic API Endpoints
681
+ 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.
682
+
683
+ Your code is executed in a secure, isolated sandbox, with access to the core data functions and the incoming request context.
684
+
685
+ ### How It Works
686
+ Define an Endpoint: You create a new document in the endpoint model.
687
+ Write Your Logic: In the code field, you write the JavaScript that will be executed.
688
+ Activate: The engine automatically listens for requests on /api/actions/:path that match your endpoint's definition.
689
+
690
+ ### The endpoint Model
691
+ To create a custom endpoint, you need to define a document with the following structure:
692
+ ```json
693
+ {
694
+ "name": "GetContactPostCount",
695
+ "path": "postCount/:name",
696
+ "method": "GET",
697
+ "code": "const posts = await db.find('content', { author: { $find: { $eq: ['$lastName', request.params.name]}}}); return { postCount: posts.length };",
698
+ "isActive": true,
699
+ "isPublic": true
700
+ }
701
+ ```
702
+ | Field | Type | Description |
703
+ |:---------|:--------|:---------------------------------------------------------------------|
704
+ | name | string | A descriptive name for your endpoint (e.g., "Calculate User Stats"). |
705
+ | path | string | The URL path. It can include parameters like :id. |
706
+ | method | enum | The HTTP method: GET, POST, PUT, PATCH, or DELETE. |
707
+ | code | code | The JavaScript code to execute when the endpoint is called. |
708
+ | isActive | boolean | A flag to enable or disable the endpoint without deleting it. |
709
+ | isPublic | boolean | A flag to enable public access (private by default). |
710
+ ---
711
+
712
+ ### The Execution Context
713
+ Your JavaScript code runs in an async context and has access to several global objects that are securely injected into the sandbox:
714
+ Your current user is used to make the calls.
715
+
716
+ #### The context Object
717
+ > This object contains all the information about the incoming HTTP request.
718
+ - context.request.**body**: The parsed request body (for POST, PUT, PATCH).
719
+ - context.request.**query**: The URL query parameters as an object.
720
+ - context.request.**params**: The URL path parameters (e.g., username from /user-summary/:username).
721
+ - context.request.**headers**: The incoming request headers.
722
+
723
+ #### The db Object
724
+ > 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.
725
+ - await db.**create**(modelName, dataObject): Inserts a new document.
726
+ - await db.**find**(modelName, filter): Finds multiple documents. Returns an array.
727
+ - await db.**findOne**(modelName, filter): Finds a single document. Returns an object or null.
728
+ - await db.**update**(modelName, filter, updateObject): Partially updates documents matching the filter (similar to a PATCH).
729
+ - await db.**delete**(modelName, filter): Deletes documents matching the filter.
730
+
731
+ #### The logger Object
732
+ > 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.
733
+ - logger.**info**(...args)
734
+ - logger.**warn**(...args)
735
+ - logger.**error**(...args)
736
+
737
+ #### The env Object
738
+ > Provides access to the user-defined variables stored in the env model, not the server's process.env.
739
+ - await env.**get**(variableName): Retrieves a single environment variable's value.
740
+ - await env.**getAll**(): Retrieves all user environment variables as an object.
741
+
742
+ #### Example: Creating a User Summary Endpoint
743
+ Let's create an endpoint that fetches a user's profile and counts how many posts they have published.
744
+ 1. Create the Endpoint Document
745
+ Create a new document in the endpoint model with the following data:
746
+ ```json
747
+ {
748
+ "name": "Get User Summary",
749
+ "path": "user-summary/:username",
750
+ "method": "GET",
751
+ "isActive": true,
752
+ "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});",
753
+ }
754
+ ```
755
+ 2. Call the New Endpoint
756
+ You can now call this custom endpoint like any other API route:
757
+
758
+ Expected response :
759
+ ```json
760
+ {
761
+ "profile": {
762
+ "_id": "60d0fe4f5311236168a109ca",
763
+ "username": "demo",
764
+ "bio": "A demo user profile.",
765
+ "...": "..."
766
+ },
767
+ "publishedPosts": 15
768
+ }
769
+
770
+ ```
771
+
772
+ ### Pluggable SSO Authentication (Google, SAML, Azure AD)
773
+
774
+ `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.
775
+
776
+ #### How It Works
777
+
778
+ 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.
779
+
780
+ To enable an SSO provider, follow these three steps:
781
+
782
+ #### Example: Enabling Google Sign-In
783
+
784
+ **1. Install the Provider's Library**
785
+
786
+ The required Passport strategy is a `peerDependency`. You must install it in your project:
787
+ ```bash
788
+ npm install passport-google-oauth20
789
+ ```
790
+
791
+ **2. Enable the Module**
792
+
793
+ To enable the module in your next engine initilization, just add it to the `modules` array:
794
+ ```javascript
795
+ Config.Set("modules", ["auth-google", "..."]);
796
+ ```
797
+
798
+ **3. Set Environment Variables**
799
+
800
+ Create or update your `.env` file with the credentials obtained from the Google Cloud Console:
801
+ ```env
802
+ GOOGLE_CLIENT_ID=your-google-client-id
803
+ GOOGLE_CLIENT_SECRET=your-google-client-secret
804
+ ```
805
+
806
+ The login flow will now be available at `/api/auth/google`.
807
+
808
+ #### Other Providers
809
+
810
+ The process is identical for other supported providers:
811
+
812
+ - **SAML**:
813
+ 1. `npm install passport-saml-encrypted`
814
+ 2. Enable the `auth-saml` module.
815
+ 3. Set `SAML_ENTRY_POINT`, `SAML_ISSUER`, `SAML_CERT`, and `SAML_DECRYPTION_KEY` environment variables.
816
+
817
+ - **Microsoft Azure AD**:
818
+ 1. `npm install passport-azure-ad`
819
+ 2. Enable the `auth-microsoft` module.
820
+ 3. Set `MICROSOFT_CLIENT_ID`, `MICROSOFT_CLIENT_SECRET`, and `MICROSOFT_TENANT_ID` environment variables.
821
+
822
+ This modular approach makes it simple to extend the engine with any Passport-compatible strategy to meet your authentication needs.
823
+
824
+ See implementations in the `modules` directory.
825
+
826
+ ---
827
+ ## Extensibility
828
+
829
+ ### Events (Triggers) Table
830
+ > You can use the events below to access the engine and manipulate API responses.
831
+ > It is useful for custom modules or middlewares for your application.
832
+
833
+ Just use
834
+
835
+ ```javascript
836
+ Event.Listen("OnDataAdded", (data) => {
837
+ my_callback()
838
+ }, "event", "user");
839
+ ```
840
+
841
+ or the system version
842
+ ```javascript
843
+ Event.Listen("OnDataAdded", (engine, data) => {
844
+ my_callback()
845
+ }, "event", "system");
846
+ ```
847
+
848
+ | Event | Description | Scope | Triggered by | Arguments (Payload) |
849
+ |:-----------------|:------------------------------------------------------------------------|:--------------|:---------------------|:-----------------------------------------------------------------------------------------------------------------------------------------|
850
+ | OnServerStart | Triggered once the HTTP server is started and listening. | System | engine.start() | engine |
851
+ | OnServerStop | Triggered right after the HTTP server is stopped. | System | engine.stop() | engine |
852
+ | OnModelsLoaded | Triggered after the initial models are loaded and validated at startup. | System | setupInitialModels() | engine, dbModels |
853
+ | OnModelsDeleted | Triggered after all models are deleted via the reset function. | System | engine.resetModels() | engine |
854
+ | OnUserDataDumped | Triggered after a user's data has been backed up (dumped). | System | jobDumpUserData() | engine |
855
+ | OnDataRestored | Triggered after a user's data has been restored from a backup. | System | loadFromDump() | (none) |
856
+ | OnPackInstalled | Triggered after a data pack has been successfully installed. | System | installPack() | pack |
857
+ | 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) |
858
+ | 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) |
859
+ | OnDataDeleted | Triggered just after data is actually deleted. | System & User | deleteData() | System: engine, {model, filter} (Pipeline*)<br>User: {model, filter} |
860
+ | 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) |
861
+ | 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) |
862
+ | OnDataInsert | Triggered just before data insertion. It will use the overrided data. | System | internal | (data) |
863
+ | OnDataValidate | Triggered to override validation check. | System | internal | (value, field, data) |
864
+ | OnDataFilter | Triggered to override data filtering operation. | System | internal | (filteredValue, field, data) |
865
+ | OnEmailTemplate | Triggered to override custom email templates | System | internal | (templateData, lang) |
866
+
867
+ ### Triggering events
868
+
869
+ If you want to provide your own hooks, you can call :
870
+ ```javascript
871
+ const result = await Event.Trigger("OnMyCustomEvent", "event", "user", ...args);
872
+ ```
873
+ Results are merged together if multiple events are triggered.
874
+ - strings are concatenated
875
+ - numbers are added
876
+ - booleans are ANDed
877
+ - arrays are concatenated
878
+ - objects are merged using spread operator
879
+
880
+ ---
881
+
882
+ ## ⚛️ Frontend Integration (React)
883
+
884
+ 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.
885
+
886
+ 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:
887
+
888
+ ➡️ **[View the Frontend Integration Guide](https://github.com/anonympins/data-primals-engine/tree/develop/client)**
889
+
890
+
891
+ ---
892
+
893
+ ## 🤝 Contributing
894
+
895
+ 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)
896
+
897
+ 1. Fork the repo
898
+ 2. Create your feature branch: `git checkout -b feature/your-feature`
899
+ 3. Launch ```npm run dev``` and make your changes with hot-reload on local port
900
+ 3. Commit changes: `git commit -m "Add new feature"`
901
+ 4. Push to your branch: `git push origin feature/your-feature`
902
+ 5. Open a pull request
903
+
904
+ Star ⭐ the repo if you find it useful!
905
+
906
+ ---
907
+
908
+ ## 📄 License
909
+ Distributed under the **MIT License**. See `LICENSE` file.
910
+
911
+ ---
912
+
913
+ ## [🔼](#data-primals-engine) Back to Top