data-primals-engine 1.3.1 β†’ 1.3.3-rc.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.
package/README.md CHANGED
@@ -1,782 +1,782 @@
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
- - **Dynamic Data Modeling**: Define and update schemas using 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 deep relation expansion, complex lookups, and dynamic calculated fields.
25
- - **Integrated Backup & Restore**: Secure, encrypted user data backups with rotation policies, supporting both local and AWS S3 storage.
26
- - **Automatic Data Auditing**: Automatically tracks all changes (create, update, delete) for every record, providing a complete version history for auditing and traceability.
27
- - **Event-Driven & Extensible**: A core event system allows for deep customization and the easy creation of new modules or plugins.
28
- - **Authentication & Authorization**: Robust role-based access control (RBAC) and pluggable user providers.
29
- - **Built-in File Management**: Handle file uploads seamlessly with integrated support for AWS S3 storage.
30
- - **🧠 AI Integration**: Natively supports OpenAI, DeepSeek and Google Gemini models via LangChain for content generation, analysis, and more.
31
- - **🌐 Internationalization (i18n)**: Fully supports multilingual interfaces and user-specific translated data.
32
- - **πŸ“¦ Starter Packs**: Quickly bootstrap applications with pre-built data packs for CRM, e-commerce, and more.
33
- - **πŸ“„Auto-Generated API Documentation**: Interactive API documentation available via the interface or at `/api-docs`.
34
-
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 OpenAI/Gemini
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
- ### Models
120
- Define schemas using JSON:
121
- ```json
122
- {
123
- "name": "product",
124
- "description": "E-commerce product schema",
125
- "fields": [
126
- { "name": "name", "type": "string", "required": true },
127
- { "name": "price", "type": "number", "required": true },
128
- { "name": "stock", "type": "number", "default": 0 },
129
- { "name": "category", "type": "relation", "relation": "taxonomy",
130
- "relationFilter": { "$eq": ["$type", "category"] }
131
- },
132
- { "name": "tags", "type": "relation", "relation": "taxonomy", "multiple": true,
133
- "relationFilter": { "$eq": ["$type", "keyword"] }
134
- }
135
- ]
136
- }
137
- ```
138
- ### Smart Relations
139
- - Handles up to 2,000 direct relations by default (can be customized)
140
- - For larger datasets, use intermediate collections
141
- - Automatic indexing on key fields
142
- - Custom indexing on fields
143
- - Custom fields :
144
-
145
- | Type | Description | Properties/Notes |
146
- |:------------|:------------------------------------------------------------------------------------|:--------------------------------------------------------------------------|
147
- | string | Character string. | minLength, maxLength |
148
- | string_t | International character string ID. | same as string, translated in { key, value } |
149
- | number | Numeric value (integer or float). | min, max |
150
- | boolean | Boolean value (true/false). | – |
151
- | date | Stores a ISO date. | – |
152
- | datetime | Stores an ISO date and time. | – |
153
- | richtext | Rich text field (HTML) for WYSIWYG editors. | |
154
- | richtext_t | International rich text field (HTML) for WYSIWYG editors. | i18n |
155
- | email | String validated as an email address. | – |
156
- | password | String that will be automatically hashed. | – |
157
- | enum | Allows selecting a value from a predefined list. | items: ["value1", "value2"] |
158
- | relation | Creates a link to a document in another model. | relation: "target_model_name", multiple: true/false |
159
- | file | For uploading a file (stored on S3 if configured). | allowedTypes:['image/jpeg', 'image/png', 'image/bmp'], maxSize: 1024*1000 |
160
- | image | Specialized file type for images, with preview. | – |
161
- | array | Stores a list of values. | itemsType: 'enum' // any type except relations |
162
- | object | Stores a nested JSON object. – | |
163
- | code | Stores language="*" as string, stores language="json" as arbitrary JSON structure. | language="json" conditionBuilder=true |
164
- | color | Stores an hexadecimal value of an RGB color | '#FF0000' |
165
- | model | Stores a model by name | – |
166
- | modelField | Stores a model field path | – |
167
-
168
- ### Model constraints
169
- ```javascript
170
- {
171
- "name": "modelName",
172
- "fields": [
173
- { "name": "fieldName1", .... },
174
- { "name": "fieldName2", .... }
175
- ],
176
- "constraints": [
177
- // uniqueness
178
- { "name": "uniqueConstraint", type: "unique", keys: ["fieldName1", "fieldName2"] }
179
- ]
180
- }
181
- ```
182
-
183
- ## πŸ—οΈ Use Case Examples
184
-
185
- ### πŸ›’ E-Commerce Backoffice
186
- - Install ecommerce-starter pack
187
- - Add products via API/UI
188
- - Customize order workflows
189
-
190
- ### 🎫 Support Ticket System
191
- - Create ticket model with [open, pending, resolved] statuses
192
- - Configure notification workflows
193
- - Add custom endpoints or dashboards/kpi for analytics
194
-
195
- ### πŸ€– AI Chatbot
196
- - Define your model
197
- - Set up workflow: "When new entry β†’ generate AI content"
198
-
199
- ### πŸ“§ Email Campaign Management
200
- The "Marketing & Campaigning" starter pack provides a powerful solution for sending large-scale email campaigns without overloading your server.
201
-
202
- - **Install the Pack**: A single command installs the necessary models (`campaign`, `audience`) and a sophisticated workflow.
203
- - **Dynamic Audiences**: Create target audiences with MongoDB filters. For example, select all contacts with the "newsletter" tag or located in a specific country.
204
- - **Personalized Content**: Use variables like `{recipient.firstName}` in the subject and body of your emails for a personal touch.
205
- - **Automated & Scalable Sending**: When you schedule a campaign, a pre-configured workflow takes over:
206
- - It processes your audience in small batches (e.g., 10 recipients at a time).
207
- - It sends emails to each batch and waits before processing the next, ensuring stability.
208
- - It tracks processed recipients to avoid duplicates and allow the campaign to be safely paused and resumed.
209
- - Once all emails are sent, the campaign is automatically marked as "completed".
210
-
211
- This use case demonstrates how starter packs and workflows can automate complex, performance-critical business logic right out of the box.
212
-
213
- ---
214
-
215
- ## πŸ“ Project Structure
216
- ```
217
- data-primals-engine/
218
- β”œβ”€β”€ src/
219
- β”‚ β”œβ”€β”€ middlewares/
220
- β”‚ β”œβ”€β”€ migrations/
221
- β”‚ β”œβ”€β”€ modules/
222
- β”‚ β”œβ”€β”€ workers/
223
- β”‚ β”œβ”€β”€ engine.js // The Express engine that serves the API
224
- β”‚ β”œβ”€β”€ constants.js // The inner-application constants definitions
225
- β”‚ β”œβ”€β”€ packs.js // The packs that will be loaded and available with installPack() method
226
- β”‚ β”œβ”€β”€ defaultModels.js // The default models available at startup.
227
- β”‚ β”œβ”€β”€ ...
228
- └── server.js
229
- ```
230
-
231
- ---
232
-
233
- ## πŸ”Œ API Examples (using `curl`)
234
-
235
- ### πŸ“ Model Management
236
-
237
- #### Create a model
238
- ```bash
239
- curl -X POST http://localhost:7633/api/model?_user=demo \
240
- -H "Authorization: Bearer demotoken" \
241
- -H "Content-Type: application/json" \
242
- -d '{
243
- "name": "newModel",
244
- "description": "A test model.",
245
- "fields": [
246
- {"name": "title", "type": "string", "required": true},
247
- {"name": "price", "type": "number"}
248
- ]
249
- }'
250
- ```
251
-
252
- #### Update a model
253
- ```bash
254
- curl -X PUT http://localhost:7633/api/model/60d0fe4f5311236168a109ca?_user=demo \
255
- -H "Authorization: Bearer demotoken" \
256
- -H "Content-Type: application/json" \
257
- -d '{
258
- "name": "updatedModel",
259
- "description": "Updated description.",
260
- "fields": [
261
- {"name": "title", "type": "string", "required": true},
262
- {"name": "status", "type": "enum", "items": ["active", "inactive"]}
263
- ]
264
- }'
265
- ```
266
-
267
- #### Delete a model
268
- ```bash
269
- curl -X DELETE "http://localhost:7633/api/model?_user=demo&name=newModel" \
270
- -H "Authorization: Bearer demotoken"
271
- ```
272
-
273
- ### πŸ—‚οΈ Data Management
274
-
275
- #### Create a document
276
- ```bash
277
- curl -X POST http://localhost:7633/api/data?_user=demo \
278
- -H "Authorization: Bearer demotoken" \
279
- -H "Content-Type: application/json" \
280
- -d '{
281
- "model": "product",
282
- "data": {
283
- "name": "Widget Extraordinaire",
284
- "price": 99.99,
285
- "stock": 150,
286
- "published": true
287
- }
288
- }'
289
- ```
290
-
291
- #### Search documents
292
- ```bash
293
- curl -X POST http://localhost:7633/api/data/search?_user=demo \
294
- -H "Authorization: Bearer demotoken" \
295
- -H "Content-Type: application/json" \
296
- -d '{
297
- "model": "product",
298
- "filter": { "price": { "$gt": 50 } }
299
- }'
300
- ```
301
-
302
- #### Update a document by ID
303
- ```bash
304
- curl -X PUT http://localhost:7633/api/data/64a31c123ef59d4c8d55aa99?_user=demo \
305
- -H "Authorization: Bearer demotoken" \
306
- -H "Content-Type: application/json" \
307
- -d '{
308
- "model": "product",
309
- "data": { "price": 109.99 }
310
- }'
311
- ```
312
-
313
- #### Bulk update
314
- ```bash
315
- curl -X PUT http://localhost:7633/api/data?_user=demo \
316
- -H "Authorization: Bearer demotoken" \
317
- -H "Content-Type: application/json" \
318
- -d '{
319
- "model": "product",
320
- "data": { "stock": 999 }
321
- }'
322
- ```
323
-
324
- #### Delete documents
325
- ```bash
326
- curl -X DELETE http://localhost:7633/api/data?_user=demo \
327
- -H "Authorization: Bearer demotoken" \
328
- -H "Content-Type: application/json" \
329
- -d '{
330
- "ids": ["64a31c123ef59d4c8d55aa99"]
331
- }'
332
- ```
333
-
334
- ## Other operations
335
-
336
- Make sure you use the code below to initialize the user :
337
- ```javascript
338
- import express from "express";
339
- import {Engine, insertData, searchData } from 'data-primals-engine';
340
-
341
- // Ensure the engine is initialized
342
-
343
- const app = express();
344
- const engine = await Engine.Create({ app });
345
- const currentUser = await engine.userProvider.findUserByUsername('demo');
346
- if (!currentUser) {
347
- throw new Error("Could not retrieve the user. Please check credentials or user provider.");
348
- }
349
- console.log(`Successfully authenticated as ${currentUser.username}`);
350
- ```
351
-
352
- ### insertData(modelName, data, files, user)
353
-
354
- > Inserts one or more documents, intelligently handling nested relationships.
355
-
356
- ```javascript
357
- // Uses the `currentUser` object defined above
358
- const newProduct = { name: 'Super Widget', price: 99.99, status: 'available' };
359
- const result = await insertData('product', newProduct, {}, currentUser);
360
-
361
- if (result.success) {
362
- console.log(`Successfully inserted document with ID: ${result.insertedIds[0]}`);
363
- }
364
- ```
365
-
366
- ### editData(modelName, filter, data, files, user)
367
-
368
- > Updates existing data matching the filter.
369
-
370
- Example:
371
-
372
- ```javascript
373
- await editData(
374
- "userProfile",
375
- { _id: "507f1f77bcf86cd799439011" },
376
- { bio: "Updated bio text" },
377
- null, // No files
378
- currentUser
379
- );
380
- ```
381
-
382
- ### patchData(modelName, filter, data, files, user)
383
-
384
- > Partially updates data (only modifies specified fields).
385
-
386
- Example:
387
-
388
- ```javascript
389
- await patchData(
390
- "settings",
391
- { userId: "507f1f77bcf86cd799439011" },
392
- { theme: "dark" },
393
- null,
394
- currentUser
395
- );
396
- ```
397
-
398
- ### deleteData(modelName, filter, user)
399
-
400
- >Deletes data with cascading relation cleanup.
401
-
402
- Examples:
403
-
404
- ```javascript
405
- // Delete by IDs
406
- await deleteData("comments", ["61d1f1a9e3f1a9e3f1a9e3f1"], user);
407
-
408
- // Delete by filter
409
- await deleteData("logs", { createdAt: { $lt: "2023-01-01" } }, user);
410
- ```
411
-
412
- ### searchData(query, user)
413
-
414
- Powerful search with relation expansion and filtering.
415
-
416
- Query Options:
417
-
418
- - model: Model name to search
419
- - filter: MongoDB-style filter
420
- - depth: Relation expansion depth (default: 1)
421
- - limit/page: Pagination
422
- - sort: Sorting criteria
423
-
424
- Example:
425
- ```javascript
426
- const results = await searchData({
427
- model: "blogPost",
428
- filter: { status: "published" },
429
- depth: 2, // Expand author and comments
430
- limit: 10,
431
- sort: "createdAt:DESC"
432
- }, user);
433
- ```
434
-
435
- ## Import/Export
436
- ### importData(options, files, user)
437
- > Imports data from Excel / JSON / CSV files.
438
-
439
- Supported Formats:
440
-
441
- - Excel with headers or field mapping
442
- - CSV with headers or field mapping
443
- - JSON arrays
444
- - JSON with model-keyed objects
445
-
446
- Example:
447
-
448
- ```javascript
449
- const result = await importData(
450
- {
451
- model: "products",
452
- hasHeaders: true
453
- },
454
- {
455
- file: req.files.myFileField // from multipart body
456
- },
457
- currentUser
458
- );
459
- ```
460
-
461
- ### exportData(options, user)
462
- > Exports data to a structured format.
463
-
464
- Example:
465
-
466
- ```javascript
467
- await exportData(
468
- {
469
- models: ["products", "categories"],
470
- depth: 1, // Include relations
471
- lang: "fr" // Localized data
472
- },
473
- currentUser
474
- );
475
- // Returns: { success: true, data: { products: [...], categories: [...] } }
476
- ```
477
-
478
- ## Backup & Restore
479
- ### dumpUserData(user)
480
- > Creates an encrypted backup of user data.
481
-
482
- Features:
483
-
484
- - Automatic encryption
485
- - S3 or local storage
486
- - Retention policies by plan (daily/weekly/monthly)
487
-
488
- Example:
489
-
490
- ```javascript
491
- await dumpUserData(currentUser);
492
- // Backup saved to S3 or ./backups/
493
- ```
494
-
495
- ### loadFromDump(user, options)
496
-
497
- > Restores user data from backup.
498
-
499
- Options:
500
- - modelsOnly: Restore only model definitions
501
-
502
- Example:
503
-
504
- ```javascript
505
- await loadFromDump(currentUser, { modelsOnly: false });
506
- // Full restore including data
507
- ```
508
-
509
- ## Pack Management
510
-
511
- ### installPack(packId, user, lang)
512
-
513
- > Installs a data pack.
514
-
515
- Example:
516
-
517
- ```javascript
518
- const result = await installPack([
519
- {
520
- "name": "My custom pack",
521
- "description": "Markdown **description** of the pack",
522
- "tags": ["customPack", "tag1", "tag2"],
523
- "models": [
524
- "env", // default model
525
- {
526
- "name": "post",
527
- "description": "Defines a post",
528
- "fields": [
529
- {"name": "subject", "type": "string", "required": true},
530
- ]
531
- }, // or custom
532
- ],
533
- "data": {
534
- "all": { // all languages installed data
535
- "post": [
536
- {"subject": "My pack first data"}
537
- ]
538
- },
539
- "en": { // English specific installed data
540
- "post": [
541
- {"subject": "My english first post"}
542
- ]
543
- }
544
- }
545
- }
546
- ], user, "en");
547
- // Returns installation summary
548
- ```
549
-
550
- ```javascript
551
- const result = await installPack("61d1f1a9e3f1a9e3f1a9e3f1", user, "en");
552
- // Returns installation summary
553
- ```
554
-
555
- > You can also open the pack gallery to see the JSON structure of each pack, before installing them.
556
-
557
- ---
558
- ### Data Auditing & History
559
- data-primals-engine includes a built-in, automatic auditing system that creates a complete history for every record in your database.
560
-
561
- >This feature is essential for traceability, debugging, and maintaining a clear audit trail of all data manipulations.
562
-
563
- #### How It Works
564
- The history feature is non-intrusive and fully automatic.
565
-
566
- Whenever you use the standard data management functions (insertData, patchData, deleteData, etc.), the engine performs two actions:
567
- 1. It executes the requested operation (create, update, or delete) on the target document.
568
- 2. It saves a complete "snapshot" of the document's state into a dedicated history collection.
569
-
570
- >Each history entry contains the original data along with crucial metadata:
571
- - `_op`: The type of operation (i for insert, u for update, d for delete).
572
- - `_v`: The version number of the record.
573
- - `_user`: The username of the user who performed the action.
574
- - `_updatedAt`: The timestamp of the operation.
575
- - `_rid`: The ID of the original record, linking all history entries together.
576
-
577
- ### Accessing the History
578
- You can retrieve the full history for any record via a simple API endpoint:
579
- ```x-sh
580
- curl -X GET http://localhost:7633/api/data/history/:modelName/:recordId
581
- ```
582
-
583
- ---
584
-
585
- ## Workflows: Automate Your Business Logic
586
-
587
- > Workflows are the automation engine of your application.
588
-
589
- They allow you to define complex business processes that run in response to specific events, without writing custom code.
590
-
591
- This is perfect for tasks like **sending welcome emails**, managing **order fulfillment**, or triggering data synchronization.
592
-
593
- A workflow is composed of two main parts: **Triggers** and **Actions**.
594
-
595
- > A 'workflowTrigger' is the event that initiates a workflow run.
596
- - **DataAdded**: Fires when a new document is created (e.g., a new user signs up).
597
- - **DataEdited**: Fires when a document is updated (e.g., an order status changes to "shipped").
598
- - **DataDeleted**: Fires when a document is removed.
599
- - **Scheduled**: Runs at a specific time or interval using a Cron expression (e.g., 0 0 * * * for a nightly data cleanup job).
600
- - **Manual**: Triggered on-demand via an API call, allowing you to integrate workflows into any part of your application.
601
-
602
- > A 'workflowAction' is the individual steps a workflow executes. You can chain them together to create sophisticated logic.
603
- - **CreateData**: Create a new document in any model.
604
- - **UpdateData**: Modify one or more existing documents that match a filter.
605
- - **SendEmail**: Send a transactional email using dynamic data from the trigger.
606
- - **HttpRequest**: Make an HTTP request (GET, POST, etc.) to an external service or API.
607
- - **ExecuteScript**: Run a custom JavaScript snippet for complex logic, data transformation, or conditional branching.
608
- - **GenerateAIContent**: Use an integrated AI provider (like OpenAI or Gemini) to generate text, summarize content, or make decisions.
609
- - **Wait**: Pause the workflow for a specific duration before continuing to the next step
610
-
611
- See the details of the workflow models for more details.
612
-
613
- ## ⚑ Dynamic API Endpoints
614
- 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.
615
-
616
- Your code is executed in a secure, isolated sandbox, with access to the core data functions and the incoming request context.
617
-
618
- ### How It Works
619
- Define an Endpoint: You create a new document in the endpoint model.
620
- Write Your Logic: In the code field, you write the JavaScript that will be executed.
621
- Activate: The engine automatically listens for requests on /api/actions/:path that match your endpoint's definition.
622
-
623
- ### The endpoint Model
624
- To create a custom endpoint, you need to define a document with the following structure:
625
- ```json
626
- {
627
- "name": "GetContactPostCount",
628
- "path": "postCount/:name",
629
- "method": "GET",
630
- "code": "const posts = await db.find('content', { author: { $find: { $eq: ['$lastName', request.params.name]}}}); return { postCount: posts.length };",
631
- "isActive": true,
632
- "isPublic": true
633
- }
634
- ```
635
- | Field | Type | Description |
636
- |:---------|:--------|:---------------------------------------------------------------------|
637
- | name | string | A descriptive name for your endpoint (e.g., "Calculate User Stats"). |
638
- | path | string | The URL path. It can include parameters like :id. |
639
- | method | enum | The HTTP method: GET, POST, PUT, PATCH, or DELETE. |
640
- | code | code | The JavaScript code to execute when the endpoint is called. |
641
- | isActive | boolean | A flag to enable or disable the endpoint without deleting it. |
642
- | isPublic | boolean | A flag to enable public access (private by default). |
643
- ---
644
-
645
- ### The Execution Context
646
- Your JavaScript code runs in an async context and has access to several global objects that are securely injected into the sandbox:
647
- Your current user is used to make the calls.
648
-
649
- #### The context Object
650
- > This object contains all the information about the incoming HTTP request.
651
- - context.request.**body**: The parsed request body (for POST, PUT, PATCH).
652
- - context.request.**query**: The URL query parameters as an object.
653
- - context.request.**params**: The URL path parameters (e.g., username from /user-summary/:username).
654
- - context.request.**headers**: The incoming request headers.
655
-
656
- #### The db Object
657
- > 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.
658
- - await db.**create**(modelName, dataObject): Inserts a new document.
659
- - await db.**find**(modelName, filter): Finds multiple documents. Returns an array.
660
- - await db.**findOne**(modelName, filter): Finds a single document. Returns an object or null.
661
- - await db.**update**(modelName, filter, updateObject): Partially updates documents matching the filter (similar to a PATCH).
662
- - await db.**delete**(modelName, filter): Deletes documents matching the filter.
663
-
664
- #### The logger Object
665
- > 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.
666
- - logger.**info**(...args)
667
- - logger.**warn**(...args)
668
- - logger.**error**(...args)
669
-
670
- #### The env Object
671
- > Provides access to the user-defined variables stored in the env model, not the server's process.env.
672
- - await env.**get**(variableName): Retrieves a single environment variable's value.
673
- - await env.**getAll**(): Retrieves all user environment variables as an object.
674
-
675
- #### Example: Creating a User Summary Endpoint
676
- Let's create an endpoint that fetches a user's profile and counts how many posts they have published.
677
- 1. Create the Endpoint Document
678
- Create a new document in the endpoint model with the following data:
679
- ```json
680
- {
681
- "name": "Get User Summary",
682
- "path": "user-summary/:username",
683
- "method": "GET",
684
- "isActive": true,
685
- "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});",
686
- }
687
- ```
688
- 2. Call the New Endpoint
689
- You can now call this custom endpoint like any other API route:
690
-
691
- Expected response :
692
- ```json
693
- {
694
- "profile": {
695
- "_id": "60d0fe4f5311236168a109ca",
696
- "username": "demo",
697
- "bio": "A demo user profile.",
698
- "...": "..."
699
- },
700
- "publishedPosts": 15
701
- }
702
-
703
- ```
704
-
705
- ---
706
- ## Extensibility
707
-
708
- ### Events (Triggers) Table
709
- > You can use the events below to access the engine and manipulate API responses.
710
- > It is useful for custom modules or middlewares for your application.
711
-
712
- Just use
713
-
714
- ```javascript
715
- Event.Listen("OnDataAdded", (data) => {
716
- my_callback()
717
- }, "event", "user");
718
- ```
719
-
720
- or the system version
721
- ```javascript
722
- Event.Listen("OnDataAdded", (engine, data) => {
723
- my_callback()
724
- }, "event", "system");
725
- ```
726
-
727
- | Event | Description | Scope | Triggered by | Arguments (Payload) |
728
- |:-----------------|:------------------------------------------------------------------------|:--------------|:---------------------|:-----------------------------------------------------------------------------------------------------------------------------------------|
729
- | OnServerStart | Triggered once the HTTP server is started and listening. | System | engine.start() | engine |
730
- | OnServerStop | Triggered right after the HTTP server is stopped. | System | engine.stop() | engine |
731
- | OnModelsLoaded | Triggered after the initial models are loaded and validated at startup. | System | setupInitialModels() | engine, dbModels |
732
- | OnModelsDeleted | Triggered after all models are deleted via the reset function. | System | engine.resetModels() | engine |
733
- | OnUserDataDumped | Triggered after a user's data has been backed up (dumped). | System | jobDumpUserData() | engine |
734
- | OnDataRestored | Triggered after a user's data has been restored from a backup. | System | loadFromDump() | (none) |
735
- | OnPackInstalled | Triggered after a data pack has been successfully installed. | System | installPack() | pack |
736
- | 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) |
737
- | 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) |
738
- | OnDataDeleted | Triggered just after data is actually deleted. | System & User | deleteData() | System: engine, {model, filter} (Pipeline*)<br>User: {model, filter} |
739
- | 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) |
740
- | 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) |
741
- | OnDataInsert | Triggered just before data insertion. It will use the overrided data. | System | internal | (data) |
742
- | OnDataValidate | Triggered to override validation check. | System | internal | (value, field, data) |
743
- | OnDataFilter | Triggered to override data filtering operation. | System | internal | (filteredValue, field, data) |
744
- | OnEmailTemplate | Triggered to override custom email templates | System | internal | (filteredValue, field, data) |
745
-
746
- ### Triggering events
747
-
748
- If you want to provide your own hooks, you can call :
749
- ```javascript
750
- const result = await Event.Trigger("OnMyCustomEvent", "event", "user", ...args);
751
- ```
752
- Results are merged together if multiple events are triggered.
753
- - strings are concatenated
754
- - numbers are added
755
- - booleans are ANDed
756
- - arrays are concatenated
757
- - objects are merged using spread operator
758
-
759
-
760
- ---
761
-
762
- ## 🀝 Contributing
763
-
764
- 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)
765
-
766
- 1. Fork the repo
767
- 2. Create your feature branch: `git checkout -b feature/your-feature`
768
- 3. Launch ```npm run dev``` and make your changes with hot-reload on local port
769
- 3. Commit changes: `git commit -m "Add new feature"`
770
- 4. Push to your branch: `git push origin feature/your-feature`
771
- 5. Open a pull request
772
-
773
- Star ⭐ the repo if you find it useful!
774
-
775
- ---
776
-
777
- ## πŸ“„ License
778
- Distributed under the **MIT License**. See `LICENSE` file.
779
-
780
- ---
781
-
782
- ## [πŸ”Ό](https://github.com/anonympins/data-primals-engine?tab=readme-ov-file#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
+ - **Dynamic Data Modeling**: Define and update schemas using 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 deep relation expansion, complex lookups, and dynamic calculated fields.
25
+ - **Integrated Backup & Restore**: Secure, encrypted user data backups with rotation policies, supporting both local and AWS S3 storage.
26
+ - **Automatic Data Auditing**: Automatically tracks all changes (create, update, delete) for every record, providing a complete version history for auditing and traceability.
27
+ - **Event-Driven & Extensible**: A core event system allows for deep customization and the easy creation of new modules or plugins.
28
+ - **Authentication & Authorization**: Robust role-based access control (RBAC) and pluggable user providers.
29
+ - **Built-in File Management**: Handle file uploads seamlessly with integrated support for AWS S3 storage.
30
+ - **🧠 AI Integration**: Natively supports OpenAI, DeepSeek and Google Gemini models via LangChain for content generation, analysis, and more.
31
+ - **🌐 Internationalization (i18n)**: Fully supports multilingual interfaces and user-specific translated data.
32
+ - **πŸ“¦ Starter Packs**: Quickly bootstrap applications with pre-built data packs for CRM, e-commerce, and more.
33
+ - **πŸ“„Auto-Generated API Documentation**: Interactive API documentation available via the interface or at `/api-docs`.
34
+
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
+ ### Models
120
+ Define schemas using JSON:
121
+ ```json
122
+ {
123
+ "name": "product",
124
+ "description": "E-commerce product schema",
125
+ "fields": [
126
+ { "name": "name", "type": "string", "required": true },
127
+ { "name": "price", "type": "number", "required": true },
128
+ { "name": "stock", "type": "number", "default": 0 },
129
+ { "name": "category", "type": "relation", "relation": "taxonomy",
130
+ "relationFilter": { "$eq": ["$type", "category"] }
131
+ },
132
+ { "name": "tags", "type": "relation", "relation": "taxonomy", "multiple": true,
133
+ "relationFilter": { "$eq": ["$type", "keyword"] }
134
+ }
135
+ ]
136
+ }
137
+ ```
138
+ ### Smart Relations
139
+ - Handles up to 2,000 direct relations by default (can be customized)
140
+ - For larger datasets, use intermediate collections
141
+ - Automatic indexing on key fields
142
+ - Custom indexing on fields
143
+ - Custom fields :
144
+
145
+ | Type | Description | Properties/Notes |
146
+ |:------------|:------------------------------------------------------------------------------------|:--------------------------------------------------------------------------|
147
+ | string | Character string. | minLength, maxLength |
148
+ | string_t | International character string ID. | same as string, translated in { key, value } |
149
+ | number | Numeric value (integer or float). | min, max |
150
+ | boolean | Boolean value (true/false). | – |
151
+ | date | Stores a ISO date. | – |
152
+ | datetime | Stores an ISO date and time. | – |
153
+ | richtext | Rich text field (HTML) for WYSIWYG editors. | |
154
+ | richtext_t | International rich text field (HTML) for WYSIWYG editors. | i18n |
155
+ | email | String validated as an email address. | – |
156
+ | password | String that will be automatically hashed. | – |
157
+ | enum | Allows selecting a value from a predefined list. | items: ["value1", "value2"] |
158
+ | relation | Creates a link to a document in another model. | relation: "target_model_name", multiple: true/false |
159
+ | file | For uploading a file (stored on S3 if configured). | allowedTypes:['image/jpeg', 'image/png', 'image/bmp'], maxSize: 1024*1000 |
160
+ | image | Specialized file type for images, with preview. | – |
161
+ | array | Stores a list of values. | itemsType: 'enum' // any type except relations |
162
+ | object | Stores a nested JSON object. – | |
163
+ | code | Stores language="*" as string, stores language="json" as arbitrary JSON structure. | language="json" conditionBuilder=true |
164
+ | color | Stores an hexadecimal value of an RGB color | '#FF0000' |
165
+ | model | Stores a model by name | – |
166
+ | modelField | Stores a model field path | – |
167
+
168
+ ### Model constraints
169
+ ```javascript
170
+ {
171
+ "name": "modelName",
172
+ "fields": [
173
+ { "name": "fieldName1", .... },
174
+ { "name": "fieldName2", .... }
175
+ ],
176
+ "constraints": [
177
+ // uniqueness
178
+ { "name": "uniqueConstraint", type: "unique", keys: ["fieldName1", "fieldName2"] }
179
+ ]
180
+ }
181
+ ```
182
+
183
+ ## πŸ—οΈ Use Case Examples
184
+
185
+ ### πŸ›’ E-Commerce Backoffice
186
+ - Install ecommerce-starter pack
187
+ - Add products via API/UI
188
+ - Customize order workflows
189
+
190
+ ### 🎫 Support Ticket System
191
+ - Create ticket model with [open, pending, resolved] statuses
192
+ - Configure notification workflows
193
+ - Add custom endpoints or dashboards/kpi for analytics
194
+
195
+ ### πŸ€– AI Chatbot
196
+ - Define your model
197
+ - Set up workflow: "When new entry β†’ generate AI content"
198
+
199
+ ### πŸ“§ Email Campaign Management
200
+ The "Marketing & Campaigning" starter pack provides a powerful solution for sending large-scale email campaigns without overloading your server.
201
+
202
+ - **Install the Pack**: A single command installs the necessary models (`campaign`, `audience`) and a sophisticated workflow.
203
+ - **Dynamic Audiences**: Create target audiences with MongoDB filters. For example, select all contacts with the "newsletter" tag or located in a specific country.
204
+ - **Personalized Content**: Use variables like `{recipient.firstName}` in the subject and body of your emails for a personal touch.
205
+ - **Automated & Scalable Sending**: When you schedule a campaign, a pre-configured workflow takes over:
206
+ - It processes your audience in small batches (e.g., 10 recipients at a time).
207
+ - It sends emails to each batch and waits before processing the next, ensuring stability.
208
+ - It tracks processed recipients to avoid duplicates and allow the campaign to be safely paused and resumed.
209
+ - Once all emails are sent, the campaign is automatically marked as "completed".
210
+
211
+ This use case demonstrates how starter packs and workflows can automate complex, performance-critical business logic right out of the box.
212
+
213
+ ---
214
+
215
+ ## πŸ“ Project Structure
216
+ ```
217
+ data-primals-engine/
218
+ β”œβ”€β”€ src/
219
+ β”‚ β”œβ”€β”€ middlewares/
220
+ β”‚ β”œβ”€β”€ migrations/
221
+ β”‚ β”œβ”€β”€ modules/
222
+ β”‚ β”œβ”€β”€ workers/
223
+ β”‚ β”œβ”€β”€ engine.js // The Express engine that serves the API
224
+ β”‚ β”œβ”€β”€ constants.js // The inner-application constants definitions
225
+ β”‚ β”œβ”€β”€ packs.js // The packs that will be loaded and available with installPack() method
226
+ β”‚ β”œβ”€β”€ defaultModels.js // The default models available at startup.
227
+ β”‚ β”œβ”€β”€ ...
228
+ └── server.js
229
+ ```
230
+
231
+ ---
232
+
233
+ ## πŸ”Œ API Examples (using `curl`)
234
+
235
+ ### πŸ“ Model Management
236
+
237
+ #### Create a model
238
+ ```bash
239
+ curl -X POST http://localhost:7633/api/model?_user=demo \
240
+ -H "Authorization: Bearer demotoken" \
241
+ -H "Content-Type: application/json" \
242
+ -d '{
243
+ "name": "newModel",
244
+ "description": "A test model.",
245
+ "fields": [
246
+ {"name": "title", "type": "string", "required": true},
247
+ {"name": "price", "type": "number"}
248
+ ]
249
+ }'
250
+ ```
251
+
252
+ #### Update a model
253
+ ```bash
254
+ curl -X PUT http://localhost:7633/api/model/60d0fe4f5311236168a109ca?_user=demo \
255
+ -H "Authorization: Bearer demotoken" \
256
+ -H "Content-Type: application/json" \
257
+ -d '{
258
+ "name": "updatedModel",
259
+ "description": "Updated description.",
260
+ "fields": [
261
+ {"name": "title", "type": "string", "required": true},
262
+ {"name": "status", "type": "enum", "items": ["active", "inactive"]}
263
+ ]
264
+ }'
265
+ ```
266
+
267
+ #### Delete a model
268
+ ```bash
269
+ curl -X DELETE "http://localhost:7633/api/model?_user=demo&name=newModel" \
270
+ -H "Authorization: Bearer demotoken"
271
+ ```
272
+
273
+ ### πŸ—‚οΈ Data Management
274
+
275
+ #### Create a document
276
+ ```bash
277
+ curl -X POST http://localhost:7633/api/data?_user=demo \
278
+ -H "Authorization: Bearer demotoken" \
279
+ -H "Content-Type: application/json" \
280
+ -d '{
281
+ "model": "product",
282
+ "data": {
283
+ "name": "Widget Extraordinaire",
284
+ "price": 99.99,
285
+ "stock": 150,
286
+ "published": true
287
+ }
288
+ }'
289
+ ```
290
+
291
+ #### Search documents
292
+ ```bash
293
+ curl -X POST http://localhost:7633/api/data/search?_user=demo \
294
+ -H "Authorization: Bearer demotoken" \
295
+ -H "Content-Type: application/json" \
296
+ -d '{
297
+ "model": "product",
298
+ "filter": { "price": { "$gt": 50 } }
299
+ }'
300
+ ```
301
+
302
+ #### Update a document by ID
303
+ ```bash
304
+ curl -X PUT http://localhost:7633/api/data/64a31c123ef59d4c8d55aa99?_user=demo \
305
+ -H "Authorization: Bearer demotoken" \
306
+ -H "Content-Type: application/json" \
307
+ -d '{
308
+ "model": "product",
309
+ "data": { "price": 109.99 }
310
+ }'
311
+ ```
312
+
313
+ #### Bulk update
314
+ ```bash
315
+ curl -X PUT http://localhost:7633/api/data?_user=demo \
316
+ -H "Authorization: Bearer demotoken" \
317
+ -H "Content-Type: application/json" \
318
+ -d '{
319
+ "model": "product",
320
+ "data": { "stock": 999 }
321
+ }'
322
+ ```
323
+
324
+ #### Delete documents
325
+ ```bash
326
+ curl -X DELETE http://localhost:7633/api/data?_user=demo \
327
+ -H "Authorization: Bearer demotoken" \
328
+ -H "Content-Type: application/json" \
329
+ -d '{
330
+ "ids": ["64a31c123ef59d4c8d55aa99"]
331
+ }'
332
+ ```
333
+
334
+ ## Other operations
335
+
336
+ Make sure you use the code below to initialize the user :
337
+ ```javascript
338
+ import express from "express";
339
+ import {Engine, insertData, searchData } from 'data-primals-engine';
340
+
341
+ // Ensure the engine is initialized
342
+
343
+ const app = express();
344
+ const engine = await Engine.Create({ app });
345
+ const currentUser = await engine.userProvider.findUserByUsername('demo');
346
+ if (!currentUser) {
347
+ throw new Error("Could not retrieve the user. Please check credentials or user provider.");
348
+ }
349
+ console.log(`Successfully authenticated as ${currentUser.username}`);
350
+ ```
351
+
352
+ ### insertData(modelName, data, files, user)
353
+
354
+ > Inserts one or more documents, intelligently handling nested relationships.
355
+
356
+ ```javascript
357
+ // Uses the `currentUser` object defined above
358
+ const newProduct = { name: 'Super Widget', price: 99.99, status: 'available' };
359
+ const result = await insertData('product', newProduct, {}, currentUser);
360
+
361
+ if (result.success) {
362
+ console.log(`Successfully inserted document with ID: ${result.insertedIds[0]}`);
363
+ }
364
+ ```
365
+
366
+ ### editData(modelName, filter, data, files, user)
367
+
368
+ > Updates existing data matching the filter.
369
+
370
+ Example:
371
+
372
+ ```javascript
373
+ await editData(
374
+ "userProfile",
375
+ { _id: "507f1f77bcf86cd799439011" },
376
+ { bio: "Updated bio text" },
377
+ null, // No files
378
+ currentUser
379
+ );
380
+ ```
381
+
382
+ ### patchData(modelName, filter, data, files, user)
383
+
384
+ > Partially updates data (only modifies specified fields).
385
+
386
+ Example:
387
+
388
+ ```javascript
389
+ await patchData(
390
+ "settings",
391
+ { userId: "507f1f77bcf86cd799439011" },
392
+ { theme: "dark" },
393
+ null,
394
+ currentUser
395
+ );
396
+ ```
397
+
398
+ ### deleteData(modelName, filter, user)
399
+
400
+ >Deletes data with cascading relation cleanup.
401
+
402
+ Examples:
403
+
404
+ ```javascript
405
+ // Delete by IDs
406
+ await deleteData("comments", ["61d1f1a9e3f1a9e3f1a9e3f1"], user);
407
+
408
+ // Delete by filter
409
+ await deleteData("logs", { createdAt: { $lt: "2023-01-01" } }, user);
410
+ ```
411
+
412
+ ### searchData(query, user)
413
+
414
+ Powerful search with relation expansion and filtering.
415
+
416
+ Query Options:
417
+
418
+ - model: Model name to search
419
+ - filter: MongoDB-style filter
420
+ - depth: Relation expansion depth (default: 1)
421
+ - limit/page: Pagination
422
+ - sort: Sorting criteria
423
+
424
+ Example:
425
+ ```javascript
426
+ const results = await searchData({
427
+ model: "blogPost",
428
+ filter: { status: "published" },
429
+ depth: 2, // Expand author and comments
430
+ limit: 10,
431
+ sort: "createdAt:DESC"
432
+ }, user);
433
+ ```
434
+
435
+ ## Import/Export
436
+ ### importData(options, files, user)
437
+ > Imports data from Excel / JSON / CSV files.
438
+
439
+ Supported Formats:
440
+
441
+ - Excel with headers or field mapping
442
+ - CSV with headers or field mapping
443
+ - JSON arrays
444
+ - JSON with model-keyed objects
445
+
446
+ Example:
447
+
448
+ ```javascript
449
+ const result = await importData(
450
+ {
451
+ model: "products",
452
+ hasHeaders: true
453
+ },
454
+ {
455
+ file: req.files.myFileField // from multipart body
456
+ },
457
+ currentUser
458
+ );
459
+ ```
460
+
461
+ ### exportData(options, user)
462
+ > Exports data to a structured format.
463
+
464
+ Example:
465
+
466
+ ```javascript
467
+ await exportData(
468
+ {
469
+ models: ["products", "categories"],
470
+ depth: 1, // Include relations
471
+ lang: "fr" // Localized data
472
+ },
473
+ currentUser
474
+ );
475
+ // Returns: { success: true, data: { products: [...], categories: [...] } }
476
+ ```
477
+
478
+ ## Backup & Restore
479
+ ### dumpUserData(user)
480
+ > Creates an encrypted backup of user data.
481
+
482
+ Features:
483
+
484
+ - Automatic encryption
485
+ - S3 or local storage
486
+ - Retention policies by plan (daily/weekly/monthly)
487
+
488
+ Example:
489
+
490
+ ```javascript
491
+ await dumpUserData(currentUser);
492
+ // Backup saved to S3 or ./backups/
493
+ ```
494
+
495
+ ### loadFromDump(user, options)
496
+
497
+ > Restores user data from backup.
498
+
499
+ Options:
500
+ - modelsOnly: Restore only model definitions
501
+
502
+ Example:
503
+
504
+ ```javascript
505
+ await loadFromDump(currentUser, { modelsOnly: false });
506
+ // Full restore including data
507
+ ```
508
+
509
+ ## Pack Management
510
+
511
+ ### installPack(packId, user, lang)
512
+
513
+ > Installs a data pack.
514
+
515
+ Example:
516
+
517
+ ```javascript
518
+ const result = await installPack([
519
+ {
520
+ "name": "My custom pack",
521
+ "description": "Markdown **description** of the pack",
522
+ "tags": ["customPack", "tag1", "tag2"],
523
+ "models": [
524
+ "env", // default model
525
+ {
526
+ "name": "post",
527
+ "description": "Defines a post",
528
+ "fields": [
529
+ {"name": "subject", "type": "string", "required": true},
530
+ ]
531
+ }, // or custom
532
+ ],
533
+ "data": {
534
+ "all": { // all languages installed data
535
+ "post": [
536
+ {"subject": "My pack first data"}
537
+ ]
538
+ },
539
+ "en": { // English specific installed data
540
+ "post": [
541
+ {"subject": "My english first post"}
542
+ ]
543
+ }
544
+ }
545
+ }
546
+ ], user, "en");
547
+ // Returns installation summary
548
+ ```
549
+
550
+ ```javascript
551
+ const result = await installPack("61d1f1a9e3f1a9e3f1a9e3f1", user, "en");
552
+ // Returns installation summary
553
+ ```
554
+
555
+ > You can also open the pack gallery to see the JSON structure of each pack, before installing them.
556
+
557
+ ---
558
+ ### Data Auditing & History
559
+ data-primals-engine includes a built-in, automatic auditing system that creates a complete history for every record in your database.
560
+
561
+ >This feature is essential for traceability, debugging, and maintaining a clear audit trail of all data manipulations.
562
+
563
+ #### How It Works
564
+ The history feature is non-intrusive and fully automatic.
565
+
566
+ Whenever you use the standard data management functions (insertData, patchData, deleteData, etc.), the engine performs two actions:
567
+ 1. It executes the requested operation (create, update, or delete) on the target document.
568
+ 2. It saves a complete "snapshot" of the document's state into a dedicated history collection.
569
+
570
+ >Each history entry contains the original data along with crucial metadata:
571
+ - `_op`: The type of operation (i for insert, u for update, d for delete).
572
+ - `_v`: The version number of the record.
573
+ - `_user`: The username of the user who performed the action.
574
+ - `_updatedAt`: The timestamp of the operation.
575
+ - `_rid`: The ID of the original record, linking all history entries together.
576
+
577
+ ### Accessing the History
578
+ You can retrieve the full history for any record via a simple API endpoint:
579
+ ```x-sh
580
+ curl -X GET http://localhost:7633/api/data/history/:modelName/:recordId
581
+ ```
582
+
583
+ ---
584
+
585
+ ## Workflows: Automate Your Business Logic
586
+
587
+ > Workflows are the automation engine of your application.
588
+
589
+ They allow you to define complex business processes that run in response to specific events, without writing custom code.
590
+
591
+ This is perfect for tasks like **sending welcome emails**, managing **order fulfillment**, or triggering data synchronization.
592
+
593
+ A workflow is composed of two main parts: **Triggers** and **Actions**.
594
+
595
+ > A 'workflowTrigger' is the event that initiates a workflow run.
596
+ - **DataAdded**: Fires when a new document is created (e.g., a new user signs up).
597
+ - **DataEdited**: Fires when a document is updated (e.g., an order status changes to "shipped").
598
+ - **DataDeleted**: Fires when a document is removed.
599
+ - **Scheduled**: Runs at a specific time or interval using a Cron expression (e.g., 0 0 * * * for a nightly data cleanup job).
600
+ - **Manual**: Triggered on-demand via an API call, allowing you to integrate workflows into any part of your application.
601
+
602
+ > A 'workflowAction' is the individual steps a workflow executes. You can chain them together to create sophisticated logic.
603
+ - **CreateData**: Create a new document in any model.
604
+ - **UpdateData**: Modify one or more existing documents that match a filter.
605
+ - **SendEmail**: Send a transactional email using dynamic data from the trigger.
606
+ - **HttpRequest**: Make an HTTP request (GET, POST, etc.) to an external service or API.
607
+ - **ExecuteScript**: Run a custom JavaScript snippet for complex logic, data transformation, or conditional branching.
608
+ - **GenerateAIContent**: Use an integrated AI provider (like OpenAI or Gemini) to generate text, summarize content, or make decisions.
609
+ - **Wait**: Pause the workflow for a specific duration before continuing to the next step
610
+
611
+ See the details of the workflow models for more details.
612
+
613
+ ## ⚑ Dynamic API Endpoints
614
+ 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.
615
+
616
+ Your code is executed in a secure, isolated sandbox, with access to the core data functions and the incoming request context.
617
+
618
+ ### How It Works
619
+ Define an Endpoint: You create a new document in the endpoint model.
620
+ Write Your Logic: In the code field, you write the JavaScript that will be executed.
621
+ Activate: The engine automatically listens for requests on /api/actions/:path that match your endpoint's definition.
622
+
623
+ ### The endpoint Model
624
+ To create a custom endpoint, you need to define a document with the following structure:
625
+ ```json
626
+ {
627
+ "name": "GetContactPostCount",
628
+ "path": "postCount/:name",
629
+ "method": "GET",
630
+ "code": "const posts = await db.find('content', { author: { $find: { $eq: ['$lastName', request.params.name]}}}); return { postCount: posts.length };",
631
+ "isActive": true,
632
+ "isPublic": true
633
+ }
634
+ ```
635
+ | Field | Type | Description |
636
+ |:---------|:--------|:---------------------------------------------------------------------|
637
+ | name | string | A descriptive name for your endpoint (e.g., "Calculate User Stats"). |
638
+ | path | string | The URL path. It can include parameters like :id. |
639
+ | method | enum | The HTTP method: GET, POST, PUT, PATCH, or DELETE. |
640
+ | code | code | The JavaScript code to execute when the endpoint is called. |
641
+ | isActive | boolean | A flag to enable or disable the endpoint without deleting it. |
642
+ | isPublic | boolean | A flag to enable public access (private by default). |
643
+ ---
644
+
645
+ ### The Execution Context
646
+ Your JavaScript code runs in an async context and has access to several global objects that are securely injected into the sandbox:
647
+ Your current user is used to make the calls.
648
+
649
+ #### The context Object
650
+ > This object contains all the information about the incoming HTTP request.
651
+ - context.request.**body**: The parsed request body (for POST, PUT, PATCH).
652
+ - context.request.**query**: The URL query parameters as an object.
653
+ - context.request.**params**: The URL path parameters (e.g., username from /user-summary/:username).
654
+ - context.request.**headers**: The incoming request headers.
655
+
656
+ #### The db Object
657
+ > 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.
658
+ - await db.**create**(modelName, dataObject): Inserts a new document.
659
+ - await db.**find**(modelName, filter): Finds multiple documents. Returns an array.
660
+ - await db.**findOne**(modelName, filter): Finds a single document. Returns an object or null.
661
+ - await db.**update**(modelName, filter, updateObject): Partially updates documents matching the filter (similar to a PATCH).
662
+ - await db.**delete**(modelName, filter): Deletes documents matching the filter.
663
+
664
+ #### The logger Object
665
+ > 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.
666
+ - logger.**info**(...args)
667
+ - logger.**warn**(...args)
668
+ - logger.**error**(...args)
669
+
670
+ #### The env Object
671
+ > Provides access to the user-defined variables stored in the env model, not the server's process.env.
672
+ - await env.**get**(variableName): Retrieves a single environment variable's value.
673
+ - await env.**getAll**(): Retrieves all user environment variables as an object.
674
+
675
+ #### Example: Creating a User Summary Endpoint
676
+ Let's create an endpoint that fetches a user's profile and counts how many posts they have published.
677
+ 1. Create the Endpoint Document
678
+ Create a new document in the endpoint model with the following data:
679
+ ```json
680
+ {
681
+ "name": "Get User Summary",
682
+ "path": "user-summary/:username",
683
+ "method": "GET",
684
+ "isActive": true,
685
+ "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});",
686
+ }
687
+ ```
688
+ 2. Call the New Endpoint
689
+ You can now call this custom endpoint like any other API route:
690
+
691
+ Expected response :
692
+ ```json
693
+ {
694
+ "profile": {
695
+ "_id": "60d0fe4f5311236168a109ca",
696
+ "username": "demo",
697
+ "bio": "A demo user profile.",
698
+ "...": "..."
699
+ },
700
+ "publishedPosts": 15
701
+ }
702
+
703
+ ```
704
+
705
+ ---
706
+ ## Extensibility
707
+
708
+ ### Events (Triggers) Table
709
+ > You can use the events below to access the engine and manipulate API responses.
710
+ > It is useful for custom modules or middlewares for your application.
711
+
712
+ Just use
713
+
714
+ ```javascript
715
+ Event.Listen("OnDataAdded", (data) => {
716
+ my_callback()
717
+ }, "event", "user");
718
+ ```
719
+
720
+ or the system version
721
+ ```javascript
722
+ Event.Listen("OnDataAdded", (engine, data) => {
723
+ my_callback()
724
+ }, "event", "system");
725
+ ```
726
+
727
+ | Event | Description | Scope | Triggered by | Arguments (Payload) |
728
+ |:-----------------|:------------------------------------------------------------------------|:--------------|:---------------------|:-----------------------------------------------------------------------------------------------------------------------------------------|
729
+ | OnServerStart | Triggered once the HTTP server is started and listening. | System | engine.start() | engine |
730
+ | OnServerStop | Triggered right after the HTTP server is stopped. | System | engine.stop() | engine |
731
+ | OnModelsLoaded | Triggered after the initial models are loaded and validated at startup. | System | setupInitialModels() | engine, dbModels |
732
+ | OnModelsDeleted | Triggered after all models are deleted via the reset function. | System | engine.resetModels() | engine |
733
+ | OnUserDataDumped | Triggered after a user's data has been backed up (dumped). | System | jobDumpUserData() | engine |
734
+ | OnDataRestored | Triggered after a user's data has been restored from a backup. | System | loadFromDump() | (none) |
735
+ | OnPackInstalled | Triggered after a data pack has been successfully installed. | System | installPack() | pack |
736
+ | 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) |
737
+ | 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) |
738
+ | OnDataDeleted | Triggered just after data is actually deleted. | System & User | deleteData() | System: engine, {model, filter} (Pipeline*)<br>User: {model, filter} |
739
+ | 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) |
740
+ | 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) |
741
+ | OnDataInsert | Triggered just before data insertion. It will use the overrided data. | System | internal | (data) |
742
+ | OnDataValidate | Triggered to override validation check. | System | internal | (value, field, data) |
743
+ | OnDataFilter | Triggered to override data filtering operation. | System | internal | (filteredValue, field, data) |
744
+ | OnEmailTemplate | Triggered to override custom email templates | System | internal | (filteredValue, field, data) |
745
+
746
+ ### Triggering events
747
+
748
+ If you want to provide your own hooks, you can call :
749
+ ```javascript
750
+ const result = await Event.Trigger("OnMyCustomEvent", "event", "user", ...args);
751
+ ```
752
+ Results are merged together if multiple events are triggered.
753
+ - strings are concatenated
754
+ - numbers are added
755
+ - booleans are ANDed
756
+ - arrays are concatenated
757
+ - objects are merged using spread operator
758
+
759
+
760
+ ---
761
+
762
+ ## 🀝 Contributing
763
+
764
+ 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)
765
+
766
+ 1. Fork the repo
767
+ 2. Create your feature branch: `git checkout -b feature/your-feature`
768
+ 3. Launch ```npm run dev``` and make your changes with hot-reload on local port
769
+ 3. Commit changes: `git commit -m "Add new feature"`
770
+ 4. Push to your branch: `git push origin feature/your-feature`
771
+ 5. Open a pull request
772
+
773
+ Star ⭐ the repo if you find it useful!
774
+
775
+ ---
776
+
777
+ ## πŸ“„ License
778
+ Distributed under the **MIT License**. See `LICENSE` file.
779
+
780
+ ---
781
+
782
+ ## [πŸ”Ό](https://github.com/anonympins/data-primals-engine?tab=readme-ov-file#data-primals-engine) Back to Top