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