Welcome to BAPIG, a powerful backend solution designed to streamline your development process. With over 40 built-in functionalities, BAPIG simplifies CRUD operations, facilitates authentication and encryption, handles communication tasks, and much more. Whether you're crafting a small-scale app or a robust enterprise system, BAPIG empowers you with efficiency and versatility.
BAPIG is built to work flawlessly with Node.JS, Express.JS, Mongoose, and MongoDB, making it a versatile and powerful tool for your development needs. With its efficient and intuitive interface, you can save countless hours of coding and focus on delivering the best possible user experience for your application.
If you find my work valuable and would like to support its continued development, consider buying me a coffee! Your support goes a long way in helping me maintain and improve this project.
Thank you for your support!
BAPIG goes beyond conventional operations, providing real-time capabilities for responsive and dynamic applications.
Tailored for Node.js, Express.js, Mongoose, and MongoDB, BAPIG's intuitive interface optimizes coding efforts, allowing you to focus on delivering exceptional user experiences.
From complex data queries to scalable solutions, BAPIG covers a wide spectrum of operations, ensuring adaptability to diverse project requirements.
- Developer Email: hekima.dev@gmail.com
- YouTube Channel: BAPIG on YouTube
- Telegram Group: Join the BAPIG community on Telegram for support and discussions.
- GitHub Repository: Access the sample BAPIG backend server source code on GitHub.
To install BAPIG in your project, run the following command:
npm install bapig
Follow these steps to set up and configure your BAPIG project:
-
Create a New Root Folder:
- Create a new root folder with a name of your choice.
- Open the root folder in your favorite editor.
-
Organize Your Project Structure:
- Inside the root folder, create the following:
- A folder for holding static files (e.g.,
public
). - A
.env
file for environment variables. -
package.json
,ts.config
, and any other necessary files.
- A folder for holding static files (e.g.,
- Inside the static files folder, create a new folder for file uploads (e.g.,
uploads
).
- Inside the root folder, create the following:
-
Create a Project Folder:
- Create a new project folder within the root folder (e.g.,
src
). - This folder will hold all the source code of your project.
- Create a new project folder within the root folder (e.g.,
-
Organize Mongoose Schema Files:
- Inside the project folder, create a new folder to hold all your Mongoose schema files (e.g.,
models
).
- Inside the project folder, create a new folder to hold all your Mongoose schema files (e.g.,
-
Configure .env File
-
Environment Variables:
- Set the environment variables in the
.env
file according to your project's requirements. Refer to the Environment Variables section for a detailed list.
- Set the environment variables in the
-
Start Developing:
- Your BAPIG project is now configured. Start building your backend application with ease!
For more information on available environment variables, refer to the Environment Variables section below.
Configure the following environment variables in your .env
file to customize your BAPIG project:
-
ENCRYPTION_TYPE
: Type of encryption (e.g., hex, base64). -
ENABLE_ENCRYPTION
: Enable or disable encryption. -
INITIALIZATION_VECTOR
: Initialization vector for encryption. -
ENCRYPTION_KEY
: Encryption key.
-
AFRICAS_TALKING_API_KEY
: API Key for Africa's Talking integration. -
AFRICAS_TALKING_SENDERS_ID
: Sender's ID for Africa's Talking. -
AFRICAS_TALKING_APPLICATION_NAME
: Application name for Africa's Talking.
-
SMTP
: SMTP server address. -
USER_EMAIL_ADDRESS
: User email address for sending emails. -
EMAIL_PORT_NUMBER
: Email server port number. -
USER_EMAIL_ADDRESS_PASSWORD
: Password for the user's email address.
-
WEBPUSH_PUBLIC_KEY
: Public key for Web Push notifications. -
WEBPUSH_PRIVATE_KEY
: Private key for Web Push notifications.
-
PROJECT_FOLDER_NAME
: Folder name for the project (e.g., 'dist'). -
STATIC_FILES_FOLDER_NAME
: Folder name for static files (e.g., 'public'). -
FILE_UPLOADING_FOLDER_NAME
: Folder name for file uploads (e.g., 'uploads'). -
MODELS_FOLDER_NAME_IN_PROJECT_FOLDER
: Folder name for models in the project (e.g., 'models').
-
PORT
: Port number for the server. -
DATABASE_NAME
: Name of the database. -
NUMBER_OF_CPU_TO_USE
: Number of CPU cores to use. -
ENVIRONMENT
: Environment setting (e.g., Development, Production). -
SOCKET_IO_CORS_ORIGIN
: CORS origin for Socket.IO. -
DATABASE_RETRY_SECONDS
: Seconds to wait before retrying database connection. -
DATABASE_MAXIMUM_RETRIES
: Maximum number of retries for database connection. -
DATABASE_URI
: URI for connecting to the database (e.g., MongoDB). -
SSL_KEY_PATH
: Path to SSL private key. -
SSL_CERT_PATH
: Path to SSL certificate.
# Encryption Configuration
ENCRYPTION_TYPE = hex # Type of encryption (e.g., hex, base64)
ENABLE_ENCRYPTION = false # Enable or disable encryption
INITIALIZATION_VECTOR = 2d52550dc714656b # Initialization vector for encryption
ENCRYPTION_KEY = abcdefghijkLMNOPQrstuvwX12345678 # Encryption key
# Africa's Talking Configuration
AFRICAS_TALKING_API_KEY = # API Key for Africa's Talking integration
AFRICAS_TALKING_SENDERS_ID = # Sender's ID for Africa's Talking
AFRICAS_TALKING_APPLICATION_NAME = # Application name for Africa's Talking
# Email Configuration
SMTP = # SMTP server address
USER_EMAIL_ADDRESS = # User email address for sending emails
EMAIL_PORT_NUMBER = 587 # Email server port number
USER_EMAIL_ADDRESS_PASSWORD = # Password for the user's email address
# Web Push Configuration
WEBPUSH_PUBLIC_KEY = # Public key for Web Push notifications
WEBPUSH_PRIVATE_KEY = # Private key for Web Push notifications
# Other Configuration
PROJECT_FOLDER_NAME = dist # Folder name for the project (e.g., 'dist')
STATIC_FILES_FOLDER_NAME = public # Folder name for static files (e.g., 'public')
FILE_UPLOADING_FOLDER_NAME = uploads # Folder name for file uploads (e.g., 'uploads')
MODELS_FOLDER_NAME_IN_PROJECT_FOLDER = models # Folder name for models in the project (e.g., 'models')
# Server and Database Configuration
PORT = 8080 # Port number for the server
DATABASE_NAME = bapig # Name of the database
DATABASE_CONNECTION_POOL_SIZE = 10 # Datababase pool size
NUMBER_OF_CPU_TO_USE = 1 # Number of CPU cores to use
ENVIRONMENT = Development # Environment setting (e.g., Development, Production)
SOCKET_IO_CORS_ORIGIN = * # CORS origin for Socket.IO
DATABASE_RETRY_SECONDS = 5 # Seconds to wait before retrying database connection
DATABASE_MAXIMUM_RETRIES = 3 # Maximum number of retries for database connection
DATABASE_URI = mongodb://127.0.0.1:27017 # URI for connecting to the database (e.g., MongoDB)
SSL_KEY_PATH = /etc/letsencrypt/live/your-domain.com/privkey.pem # Path to SSL private key
SSL_CERT_PATH = /etc/letsencrypt/live/your-domain.com/fullchain.pem # Path to SSL certificate
The project follows a structured organization for better clarity and maintainability. Below is an overview of the folder structure:
ROOT DIRECTORY
|_______node_modules
|
|_______public
| |
| |_____uploads
| |_____"other files and folders in public"
|
|_______src
| |
| |_____models
| |_____index.ts (server file)
| |_____"other files and folders in src"
|
|_______package.json
|_______package-lock.json
|_______.env
|_______tsconfig.json
|_______"other files and folders in root directory"
When interacting with the database in BAPIG, it is essential to provide the schema, i.e., the database model file name, that you want to use.
If you need to join foreign keys (database relationships) when querying data, consider installing the mongoose-autopopulate
package. Ensure that your database schema is designed according to the recommendations of mongoose-autopopulate
.
To integrate sockets into your application using BAPIG, follow these steps:
- Import the
io
connection instance from the BAPIG package. This allows BAPIG to establish and manage socket connections as needed.
// Example import in your code
const { io } = require('bapig');
Whenever a request or operation is made with BAPIG, the response consists of an object {} with two key-value pairs:
-
success: A boolean value (true or false) indicating the success or failure of the operation.
-
message: A field that can hold any data type, depending on the operation's success. If successful, it may contain relevant data for your application. If unsuccessful, it may contain an error message or additional information about the failure.
{ "success": true, "message": "some success response data" }
{ "success": false, "message": "some false response data" }
When encryption is enabled in your BAPIG-powered application, the response includes an object {} with a payload key and the encrypted data as the payload value.
{
"payload": "db25f0861631d0f524483aeaf8b5b14c188b7a4cab2905e4f1b57b71460e73e0b54a75814d9c566628f429e5ba86fb8f3332de83a75e27edad624b528cf0bce68c0d09978b356a6fda7f9408338b244b70113e9cf2a5585de0921a9fa8449e7302048727127ebc0162fba6d040cfeff6"
}
// Import necessary modules from 'bapig'
import { startServer } from "bapig";
// Initialize your Express application
const app = express();
// Set up your middleware and routes
// Start the server without clustering
startServer(app);
To leverage clustering and enhance server performance, you can specify the number of CPUs to use in your environment file.
-
Create a
.env
file in your project root. -
Add the following line to specify the number of CPUs:
NUMBER_OF_CPU_TO_USE = 4 // Replace 4 with the desired number of CPUs
-
Update your code to use clustering:
// Import necessary modules from 'bapig' import { useClustering } from "bapig"; // Initialize your Express application const app = express(); // Set up your middleware and routes // Start the server with clustering useClustering(app);
// Dependencies
const cors = require("cors");
const { io } = require("bapig");
const express = require("express");
const { router, helpers, startServer, useClustering, fileUpload } = require("bapig");
// Initializing Express application
const application = express();
// Applying Express middleware
application.disable("x-powered-by");
application.use(cors({ origin: "*" }));
application.use(express.json());
application.use(express.static(helpers.staticFilesDirectory));
application.use(fileUpload())
// Setting up API routes
application.use("/api", router);
// Starting the server without clustering
startServer(application);
// Starting the server with clustering
// useClustering(application);
// Setting up Socket.IO
// Note: 'io' is imported from 'bapig'
io?.on("connection", (socket) => {
// Handling incoming messages
socket.on("message", (message) => {
console.log(message);
});
});
// Importing dependencies
import cors from "cors";
import { Socket } from "socket.io";
import express, { Application } from "express";
import { io, router, helpers, startServer, useClustering, fileUpload } from "bapig";
// Initializing Express application
const application: Application = express();
// Applying Express middleware
application.disable("x-powered-by");
application.use(cors({ origin: "*" }));
application.use(express.json());
application.use(express.static(helpers.staticFilesDirectory));
application.use(fileUpload())
// Setting up API routes
application.use("/api", router);
// Starting the server without clustering
// startServer(application);
// Starting the server with clustering
useClustering(application);
// Setting up Socket.IO
// Note: 'io' is imported from 'bapig'
io?.on("connection", (socket: Socket) => {
// Handling incoming messages
socket.on("message", (message: any) => {
console.log(message);
});
});
If you are using Socket.IO in your client-side application, you can listen to specific events for CRUD operations. Here's how you can set up Socket.IO events on the client side:
Example: user-create
socket.on('user-create', (createdData) => {
console.log('New user created:', createdData);
// Handle the created data as needed
});
Example: user-update
socket.on('user-update', (updatedData) => {
console.log('New user updated:', updatedData);
// Handle the updated data as needed
});
Example: user-delete
socket.on('user-delete', (deletedData) => {
console.log('New user deleted:', deletedData);
// Handle the deleted data as needed
});
Welcome to the documentation for BAPIG routes. Below is a list of available routes, each providing a specific functionality. Click on a route title to jump to its detailed explanation.
-
GET /:
- Displays the DOCUMENTATION (Offline).
-
POST /create:
- Creates a single document.
- View Docs
-
POST /bulk-create:
- Bulk creates documents.
- View Docs
-
GET /read:
- Reads a single document.
- View Docs
-
PUT /update:
- Updates a single document.
- View Docs
-
PUT /bulk-update:
- Bulk updates documents.
- View Docs
-
DELETE /delete:
- Deletes a single document.
- View Docs
-
DELETE /bulk-delete:
- Bulk deletes documents.
- View Docs
-
GET /list:
- Lists documents.
- View Docs
-
GET /count:
- Counts documents.
- View Docs
-
GET /list-all:
- Lists all documents.
- View Docs
-
GET /validate:
- Validates a document.
- View Docs
-
POST /create-field-encryption:
- Creates field encryption.
- View Docs
-
POST /authenticate:
- Authenticates.
- View Docs
-
GET /validate-field-encryption:
- Validates field encryption.
- View Docs
-
PUT /change-field-encryption:
- Changes field encryption.
- View Docs
-
POST /upload-file:
- Uploads a file.
- View Docs
-
POST /upload-files:
- Uploads multiple files.
- View Docs
-
DELETE /delete-file:
- Deletes a file.
- View Docs
-
DELETE /delete-files:
- Deletes multiple files.
- View Docs
-
POST /send-sms:
- Sends SMS.
- View Docs
-
POST /send-email:
- Sends an email.
- View Docs
-
GET /generate-otp:
- Generates OTP.
- View Docs
-
POST /send-otp:
- Sends OTP.
- View Docs
-
POST /push-notification:
- Push notification.
- View Docs
-
GET /bulk-list-all:
- Bulk lists all documents.
- View Docs
-
GET /bulk-count:
- Bulk counts documents.
- View Docs
-
GET /bulk-read:
- Bulk reads documents.
- View Docs
-
POST /aggregation:
- Aggregates.
- View Docs
-
POST /bulk-aggregation:
- Bulk aggregates.
- View Docs
-
DELETE /delete-all-collection:
- Deletes all collections.
- View Docs
-
DELETE /delete-many:
- Deletes many documents.
- View Docs
-
DELETE /bulk-delete-many:
- Bulk deletes many documents.
- View Docs
-
PUT /bulk-update-many:
- Bulk updates many documents.
- View Docs
-
GET /list-all-collection:
- Lists all collections.
- View Docs
-
PUT /update-all-collection:
- Updates all collections.
- View Docs
-
PUT /update-many:
- Updates many documents.
- View Docs
-
GET /count-all-collection:
- Counts all collections.
- View Docs
-
GET /search:
- Search documents.
- View Docs
-
POST /transaction:
- Perform transaction.
- View Docs
The Create Single Document API enables clients to interact with the server and create a new document via the /create
route using the HTTP POST
method. This document provides comprehensive details on how to make successful requests and handle potential errors.
To create a document, the following parameters must be included in the request body in JSON format:
-
schema
(string): The name of the schema. -
documentData
(object): The data for the document.
const sampleData = {
schema: "user",
documentData: {
username: "bapig",
phone_number: "0752628215"
}
}
// Making a client-side request to create a new document
try {
const response = await fetch(`/create`, {
method: "POST",
body: JSON.stringify(sampleData),
headers: {
"Content-Type": "application/json"
}
});
// Handling the response
const result = await response.json();
console.log(result);
} catch (error) {
console.error("Error making the request:", error);
}
// Making a server-side request to handle document creation
// Require necessary dependencies
const { controllers } = require("bapig");
try {
// Invoking the createSingleDocument method from controllers
const result = await controllers.createSingleDocument(sampleData);
// Logging the result
console.log(result);
} catch (error) {
console.error("Error handling the request:", error);
}
{
"success": true,
"message": {
"_id": "some_id",
"username": "bapig",
"phone_number": "0752628215"
}
}
{
"success": false,
"message": "failed to create user"
}
The Document Bulk Create API allows clients to perform bulk creation of documents using the /bulk-create
route with the HTTP POST
method. This document provides detailed information on how to make successful requests and handle potential errors.
To perform bulk document creation, clients must send an array of objects in the request body. Each object should adhere to the following structure:
-
schema
(string): The name of the schema. -
documentData
(object): The data for the document.
const bulkCreateData = [
{
schema: "user",
documentData: {
username: "bapig",
phone_number: "0752628215"
}
},
// Additional objects as needed
];
// Making a client-side request to perform bulk document creation
try {
const response = await fetch(`/bulk-create`, {
method: "POST",
body: JSON.stringify(bulkCreateData),
headers: {
"Content-Type": "application/json"
}
});
// Handling the response
const result = await response.json();
console.log(result);
} catch (error) {
console.error("Error making the request:", error);
}
// Making a server-side request to handle bulk document creation
// Dependencies
import { documentBulkCreate } from "bapig"; // Update with your actual package path
try {
// Invoking the documentBulkCreate function
const result = await documentBulkCreate(bulkCreateData);
// Logging the result
console.log(result);
} catch (error) {
console.error("Error handling the request:", error);
}
{
"success": true,
"message": {
"passedQueries": [
{
"_id": "some_id",
"username": "bapig",
"phone_number": "0752628215"
}
// Additional successfully created documents
],
"failedQueries": [
{
"schema": "user",
"documentData": {
"username": "bapig",
"phone_number": "0752628215"
},
"reason": "failed to create user"
}
// Additional failed documents with reasons
]
}
}
The Get Single Document API allows clients to retrieve a single document using the /read
route with the HTTP GET
method. This document provides detailed information on how to make successful requests and handle potential errors.
To retrieve a single document, clients must include a query string in the request URL with the following parameters:
-
condition
(object): The condition to filter the document. -
schema
(string): The name of the schema. -
select
(object): The fields to select from the document. -
joinForeignKeys
(boolean): A flag to determine whether to autopopulate foreign keys.
/read?condition={"_id":"some_id"}&schema="user"&select={"username":1,"email":1}&joinForeignKeys=false
// Making a client-side request to retrieve a single document
try {
const response = await fetch(`/read?condition={"_id":"some_id"}&schema="user"&select={"username":1,"email":1}&joinForeignKeys=true`);
// Handling the response
const result = await response.json();
console.log(result);
} catch (error) {
console.error("Error making the request:", error);
}
// Making a server-side request to handle document retrieval
// Dependencies
import { controllers } from "bapig";
try {
// Invoking the getSingleDocument function
const result = await controllers.getSingleDocument({
condition: { "_id": "some_id" },
schema: "user",
select: { "username": 1, "email": 1 },
joinForeignKeys: true
});
// Logging the result
console.log(result);
} catch (error) {
console.error("Error handling the request:", error);
}
{
"success": true,
"message": {
"_id": "some_id",
"username": "example_user",
"email": "user@example.com"
// Additional document fields as selected
}
}
The Update Single Document API enables clients to update a single document using the /update
route with the HTTP PUT
method. This document provides detailed information on how to make successful requests and handle potential errors.
To update a single document, clients must send a request with the following parameters in the request body:
-
schema
(string): The name of the schema. -
condition
(object): The condition to identify the document to update. -
newDocumentData
(object): The updated data for the document.
const updateData = {
schema: "user",
condition: { "_id": "some_id" },
newDocumentData: {
username: "new_username",
email: "new_email@example.com"
}
};
// Making a client-side request to update a single document
try {
const response = await fetch(`/update`, {
method: "PUT",
body: JSON.stringify(updateData),
headers: {
"Content-Type": "application/json"
}
});
// Handling the response
const result = await response.json();
console.log(result);
} catch (error) {
console.error("Error making the request:", error);
}
// Making a server-side request to handle document update
// Dependencies
import { controllers } from "bapig";
try {
// Invoking the updateSingleDocument function from bapig controllers
const result = await controllers.updateSingleDocument(updateData);
// Logging the result
console.log(result);
} catch (error) {
console.error("Error handling the request:", error);
}
{
"success": true,
"message": {
"_id": "some_id",
"username": "new_username",
"email": "new_email@example.com"
// Additional updated document fields
}
}
The Document Bulk Update API allows clients to perform bulk updates of documents using the /bulk-update
route with the HTTP PUT
method. This document provides detailed information on how to make successful requests and handle potential errors.
To perform bulk document updates, clients must send an array of objects in the request body. Each object should adhere to the following structure:
-
schema
(string): The name of the schema. -
condition
(object): The condition to identify the document to update. -
newDocumentData
(object): The updated data for the document.
const bulkUpdateData = [
{
schema: "user",
condition: { "_id": "some_id" },
newDocumentData: {
username: "new_username",
email: "new_email@example.com"
}
},
// Additional objects as needed
];
// Making a client-side request to perform bulk document updates
try {
const response = await fetch(`/bulk-update`, {
method: "PUT",
body: JSON.stringify(bulkUpdateData),
headers: {
"Content-Type": "application/json"
}
});
// Handling the response
const result = await response.json();
console.log(result);
} catch (error) {
console.error("Error making the request:", error);
}
// Making a server-side request to handle bulk document updates
// Dependencies
import { controllers } from "bapig";
try {
// Invoking the documentBulkUpdate function from bapig controllers
const result = await controllers.documentBulkUpdate(bulkUpdateData);
// Logging the result
console.log(result);
} catch (error) {
console.error("Error handling the request:", error);
}
{
"success": true,
"message": {
"passedQueries": [
{
"_id": "some_id",
"username": "new_username",
"email": "new_email@example.com"
}
// Additional successfully updated documents
],
"failedQueries": [
{
"schema": "user",
"condition": { "_id": "some_id" },
"newDocumentData": {
"username": "new_username",
"email": "new_email@example.com"
},
"reason": "failed to update user"
}
// Additional failed updates with reasons
]
}
}
The Delete Single Document API allows clients to delete a single document using the /delete
route with the HTTP DELETE
method. This document provides detailed information on how to make successful requests and handle potential errors.
To delete a single document, clients must include query parameters in the request URL:
-
schema
(string): The name of the schema. -
condition
(object): The condition to identify the document to delete.
/delete?schema=user&condition={"_id":"some_id"}
// Making a client-side request to delete a single document
try {
const response = await fetch(`/delete?schema=user&condition={"_id":"some_id"}`, {
method: "DELETE",
headers: {
"Content-Type": "application/json"
}
});
// Handling the response
const result = await response.json();
console.log(result);
} catch (error) {
console.error("Error making the request:", error);
}
// Making a server-side request to handle document deletion
// Dependencies
import { controllers } from "bapig";
try {
// Invoking the deleteSingleDocument function from bapig controllers
const result = await controllers.deleteSingleDocument({
schema: "user",
condition: { "_id": "some_id" }
});
// Logging the result
console.log(result);
} catch (error) {
console.error("Error handling the request:", error);
}
{
"success": true,
"message": {
"_id": "some_id",
// Additional document fields
}
}
The Document Bulk Delete API enables clients to delete multiple documents using the /bulk-delete
route with the HTTP DELETE
method. This document provides detailed information on how to make successful requests and handle potential errors.
To perform bulk document deletion, clients must include query parameters in the request URL:
-
schema
(string): The name of the schema. -
condition
(object): The condition to identify the document to delete.
/bulk-delete?schema=user&condition={"_id":"some_id"}
// Making a client-side request to perform bulk document deletion
try {
const response = await fetch(`/bulk-delete?schema=user&condition={"_id":"some_id"}`, {
method: "DELETE",
headers: {
"Content-Type": "application/json"
}
});
// Handling the response
const result = await response.json();
console.log(result);
} catch (error) {
console.error("Error making the request:", error);
}
// Making a server-side request to handle bulk document deletion
// Dependencies
import { controllers } from "bapig";
try {
// Invoking the documentBulkDelete function from bapig controllers
const result = await controllers.documentBulkDelete({
schema: "user",
condition: { "_id": "some_id" }
});
// Logging the result
console.log(result);
} catch (error) {
console.error("Error handling the request:", error);
}
{
"success": true,
"message": {
"passedQueries": [
{
"_id": "some_id",
// Additional document fields
}
// Additional successfully deleted documents
],
"failedQueries": [
{
"schema": "user",
"condition": { "_id": "some_id" },
"reason": "failed to delete user"
}
// Additional failed deletions with reasons
]
}
}
The List Documents API allows clients to retrieve a list of documents based on specified criteria using the /list
route with the HTTP GET
method. This document provides detailed information on how to make successful requests and handle potential errors.
To retrieve a list of documents, clients must include query parameters in the request URL:
-
page
(number): The page number for pagination (default is 1). -
limit
(number): The number of documents to display per page (default is 10). -
sort
(object): The sorting criteria for the documents. -
condition
(object): The condition to filter documents. -
schema
(string): The name of the schema. -
select
(object): The fields to select from each document. -
joinForeignKeys
(boolean): A flag indicating whether to autopopulate foreign keys.
/list?page=1&limit=10&sort={"createdAt":1}&condition={"status":"active"}&schema=user&select={"username":1}&joinForeignKeys=true
// Making a client-side request to retrieve a list of documents
try {
const response = await fetch(`/list?page=1&limit=10&sort={"createdAt":1}&condition={"status":"active"}&schema=user&select={"username":1}&joinForeignKeys=true`, {
method: "GET",
headers: {
"Content-Type": "application/json"
}
});
// Handling the response
const result = await response.json();
console.log(result);
} catch (error) {
console.error("Error making the request:", error);
}
// Making a server-side request to retrieve a list of documents
// Dependencies
import { controllers } from "bapig";
try {
// Invoking the listDocuments function from bapig controllers
const result = await controllers.listDocuments({
page: 1,
limit: 10,
sort: { "createdAt": 1 },
condition: { "status": "active" },
schema: "user",
select: { "username": 1 },
joinForeignKeys: true
});
// Logging the result
console.log(result);
} catch (error) {
console.error("Error handling the request:", error);
}
{
"success": true,
"message": {
"pages": [1, 2, 3],
"nextPage": 2,
"documents": [
{
"_id": "some_id",
"username": "example_user"
// Additional document fields
}
// Additional documents based on the specified criteria
],
"totalDocuments": 30,
"previousPage": 0,
"limit": 10,
"currentPage": 1
}
}
The Count Documents API allows clients to retrieve the total number of documents based on specified criteria using the /count
route with the HTTP GET
method. This document provides detailed information on how to make successful requests and handle potential errors.
To count documents, clients must include query parameters in the request URL:
-
condition
(object): The condition to filter documents. -
schema
(string): The name of the schema.
/count?condition={"status":"active"}&schema=user
// Making a client-side request to count documents
try {
const response = await fetch(`/count?condition={"status":"active"}&schema=user`, {
method: "GET",
headers: {
"Content-Type": "application/json"
}
});
// Handling the response
const result = await response.json();
console.log(result);
} catch (error) {
console.error("Error making the request:", error);
}
// Making a server-side request to count documents
// Dependencies
import { controllers } from "bapig";
try {
// Invoking the countDocuments function from bapig controllers
const result = await controllers.countDocuments({
condition: { "status": "active" },
schema: "user"
});
// Logging the result
console.log(result);
} catch (error) {
console.error("Error handling the request:", error);
}
{
"success": true,
"message": 25
}
The List All Documents API allows clients to retrieve all documents based on specified criteria using the /list-all
route with the HTTP GET
method. This document provides detailed information on how to make successful requests and handle potential errors.
To list all documents, clients must include query parameters in the request URL:
-
sort
(object): The sorting criteria for the documents. -
condition
(object): The condition to filter documents. -
schema
(string): The name of the schema. -
select
(object): The fields to select from each document. -
joinForeignKeys
(boolean): A flag indicating whether to autopopulate foreign keys.
/list-all?sort={"createdAt":1}&condition={"status":"active"}&schema=user&select={"username":1}&joinForeignKeys=true
// Making a client-side request to list all documents
try {
const response = await fetch(`/list-all?sort={"createdAt":1}&condition={"status":"active"}&schema=user&select={"username":1}&joinForeignKeys=true`, {
method: "GET",
headers: {
"Content-Type": "application/json"
}
});
// Handling the response
const result = await response.json();
console.log(result);
} catch (error) {
console.error("Error making the request:", error);
}
// Making a server-side request to list all documents
// Dependencies
import { controllers } from "bapig";
try {
// Invoking the listAllDocuments function from bapig controllers
const result = await controllers.listAllDocuments({
sort: { "createdAt": 1 },
condition: { "status": "active" },
schema: "user",
select: { "username": 1 },
joinForeignKeys: true
});
// Logging the result
console.log(result);
} catch (error) {
console.error("Error handling the request:", error);
}
{
"success": true,
"message": [
{
"_id": "some_id",
"username": "example_user"
// Additional document fields
},
// Additional documents based on the specified criteria
]
}
The Validate Document API enables clients to validate documents based on specified criteria using the /validate
route with the HTTP GET
method. This document provides comprehensive information on how to make successful requests and handle potential errors.
To validate a document, clients must include query parameters in the request URL:
-
schema
(string): The name of the schema. -
validationType
(string): The type of validation (onCreate
oronUpdate
). -
condition
(object): The condition to filter documents. -
documentId
(string, required foronUpdate
): The ID of the document. -
joinForeignKeys
(boolean): A flag indicating whether to autopopulate foreign keys. -
select
(object): The fields to select from the document.
/validate?schema=user&validationType=onCreate&condition={"username":"example_user"}&joinForeignKeys=true&select={"username":1}
// Making a client-side request to validate a document
try {
const response = await fetch(`/validate?schema=user&validationType=onCreate&condition={"username":"example_user"}&joinForeignKeys=true&select={"username":1}`, {
method: "GET",
headers: {
"Content-Type": "application/json"
}
});
// Handling the response
const result = await response.json();
console.log(result);
} catch (error) {
console.error("Error making the request:", error);
}
// Making a server-side request to validate a document
// Dependencies
import { controllers } from "bapig";
try {
// Invoking the validateDocument function from bapig controllers
const result = await controllers.validateDocument({
schema: "user",
validationType: "onCreate",
condition: { "username": "example_user" },
joinForeignKeys: true,
select: { "username": 1 }
});
// Logging the result
console.log(result);
} catch (error) {
console.error("Error handling the request:", error);
}
{
"success": true,
"message": {
"_id": "some_id",
"username": "example_user"
// Additional document fields
}
}
The Create Document Field Encryption API allows clients to encrypt a specific field within a document using the /create-field-encryption
route with the HTTP POST
method. This document provides detailed information on making successful requests to encrypt document fields.
To encrypt a document field, clients must include the following parameters in the request body:
-
schema
(string): The name of the schema. -
fieldToEncrypt
(string): The field within the document to encrypt. -
documentData
(object): The document data containing the field to be encrypted.
{
"schema": "user",
"fieldToEncrypt": "password",
"documentData": {
"username": "example_user",
"password": "secret_password"
}
}
// Making a client-side request to encrypt a document field
try {
const response = await fetch(`/create-field-encryption`, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
"schema": "user",
"fieldToEncrypt": "password",
"documentData": {
"username": "example_user",
"password": "secret_password"
}
})
});
// Handling the response
const result = await response.json();
console.log(result);
} catch (error) {
console.error("Error making the request:", error);
}
// Making a server-side request to encrypt a document field
// Dependencies
import { controllers } from "bapig";
try {
// Invoking the createDocumentFieldEncryption function from bapig controllers
const result = await controllers.createDocumentFieldEncryption({
"schema": "user",
"fieldToEncrypt": "password",
"documentData": {
"username": "example_user",
"password": "secret_password"
}
});
// Logging the result
console.log(result);
} catch (error) {
console.error("Error handling the request:", error);
}
{
"success": true,
"message": {
"_id": "some_id",
"username": "example_user",
"password": "$2b$10$somehash"
// Additional document fields
}
}
The Authenticate API enables user authentication based on provided credentials. Clients can use the /authenticate
route with the HTTP POST
method to authenticate users. This document provides detailed information on making successful requests for user authentication.
To authenticate a user, clients must include the following parameters in the request body:
-
schema
(string): The name of the schema. -
select
(object): The fields to select from the document (optional). -
condition
(object): The conditions to find the document for authentication. -
joinForeignKeys
(boolean): Flag to enable autopopulation of foreign keys (optional). -
fieldWithEncryption
(string): The field containing the encrypted password. -
valueToCompareWithEncryption
(string): The value to compare with the encrypted password.
{
"schema": "user",
"select": { "username": 1, "email": 1 },
"condition": { "username": "example_user" },
"joinForeignKeys": true,
"fieldWithEncryption": "password",
"valueToCompareWithEncryption": "user_provided_password"
}
// Making a client-side request for user authentication
try {
const response = await fetch(`/authenticate`, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
"schema": "user",
"select": { "username": 1, "email": 1 },
"condition": { "username": "example_user" },
"joinForeignKeys": true,
"fieldWithEncryption": "password",
"valueToCompareWithEncryption": "user_provided_password"
})
});
// Handling the response
const result = await response.json();
console.log(result);
} catch (error) {
console.error("Error making the request:", error);
}
// Making a server-side request for user authentication
// Dependencies
import { controllers } from "bapig";
try {
// Invoking the authenticate function from bapig controllers
const result = await controllers.authenticate({
"schema": "user",
"select": { "username": 1, "email": 1 },
"condition": { "username": "example_user" },
"joinForeignKeys": true,
"fieldWithEncryption": "password",
"valueToCompareWithEncryption": "user_provided_password"
});
// Logging the result
console.log(result);
} catch (error) {
console.error("Error handling the request:", error);
}
The Validate Document Field Encryption API allows clients to validate a document's encrypted field. Clients can use the /validate-field-encryption
route with the HTTP GET
method to verify whether a provided value matches the encryption of a specific field in a document. This document provides detailed information on making successful requests for validating document field encryption.
To validate document field encryption, clients must include the following parameters in the request query:
-
schema
(string): The name of the schema. -
documentId
(string): The unique identifier of the document. -
valueToCompareWithEncryption
(string): The value to compare with the encrypted field. -
fieldWithEncryption
(string): The field containing the encrypted value.
/validate-field-encryption?schema=user&documentId=example_document_id&valueToCompareWithEncryption=user_provided_value&fieldWithEncryption=password
// Making a client-side request to validate document field encryption
try {
const response = await fetch(`/validate-field-encryption?schema=user&documentId=example_document_id&valueToCompareWithEncryption=user_provided_value&fieldWithEncryption=password`, {
method: "GET",
headers: {
"Content-Type": "application/json"
}
});
// Handling the response
const result = await response.json();
console.log(result);
} catch (error) {
console.error("Error making the request:", error);
}
// Making a server-side request to validate document field encryption
// Dependencies
import { controllers } from "bapig";
try {
// Invoking the validateDocumentFieldEncryption function from bapig controllers
const result = await controllers.validateDocumentFieldEncryption({
"schema": "user",
"documentId": "example_document_id",
"valueToCompareWithEncryption": "user_provided_value",
"fieldWithEncryption": "password"
});
// Logging the result
console.log(result);
} catch (error) {
console.error("Error handling the request:", error);
}
The Change Field Encryption API enables clients to modify the encryption of a specific field within a document. Clients can use the /change-field-encryption
route with the HTTP PUT
method to update the encryption of a specified field in a document. This document provides detailed information on making successful requests for changing document field encryption.
To change the document field encryption, clients must include the following parameters in the request body:
-
schema
(string): The name of the schema. -
documentId
(string): The unique identifier of the document. -
newValueToEncrypt
(string): The new value to encrypt and update. -
fieldWithEncryption
(string): The field whose encryption needs to be changed.
{
"schema": "user",
"documentId": "example_document_id",
"newValueToEncrypt": "new_secure_value",
"fieldWithEncryption": "password"
}
// Making a client-side request to change document field encryption
try {
const response = await fetch('/change-field-encryption', {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
schema: 'user',
documentId: 'example_document_id',
newValueToEncrypt: 'new_secure_value',
fieldWithEncryption: 'password',
}),
});
// Handling the response
const result = await response.json();
console.log(result);
} catch (error) {
console.error('Error making the request:', error);
}
// Making a server-side request to change document field encryption
// Dependencies
import { controllers } from 'bapig';
try {
// Invoking the changeDocumentFieldEncryption function from bapig controllers
const result = await controllers.changeDocumentFieldEncryption({
"schema": "user",
"documentId": "example_document_id",
"newValueToEncrypt": "new_secure_value",
"fieldWithEncryption": "password"
});
// Logging the result
console.log(result);
} catch (error) {
console.error("Error handling the request:", error);
}
The Upload File API allows clients to upload files to the server. Clients can use the /upload-file
route with the HTTP POST
method to upload a file. This document provides detailed information on making successful requests for uploading files.
To upload a file, clients must include the following parameters in the request body:
-
folderName
(string): The name of the folder in which the file will be stored.
{
"folderName": "uploads"
}
// Making a client-side request to upload a file
// Assuming 'fileInput' is an HTML input element of type 'file'
const fileInput = document.getElementById('fileInput');
// Assuming 'folderNameInput' is an HTML input element for entering the folder name
const folderNameInput = document.getElementById('folderNameInput');
// Assuming 'uploadButton' is an HTML button triggering the file upload
const uploadButton = document.getElementById('uploadButton');
uploadButton.addEventListener('click', async () => {
const file = fileInput.files[0];
const folderName = folderNameInput.value;
if (!file) {
console.error('No file selected');
return;
}
try {
const formData = new FormData();
formData.append('body', JSON.stringify({ folderName }));
formData.append('file', file);
const response = await fetch('/upload-file', {
method: 'POST',
body: formData,
});
// Handling the response
const result = await response.json();
console.log(result);
} catch (error) {
console.error('Error making the request:', error);
}
});
The Upload Files API allows clients to upload multiple files to the server simultaneously. Clients can use the /upload-files
route with the HTTP POST
method to upload files. This document provides detailed information on making successful requests for uploading multiple files.
To upload multiple files, clients must include the following parameters in the request body:
-
folderName
(string): The name of the folder in which the files will be stored.
{
"folderName": "uploads"
}
// Making a client-side request to upload multiple files
// Assuming 'fileInputs' is an array of HTML input elements of type 'file'
const fileInputs = document.querySelectorAll('.file-input');
// Assuming 'folderNameInput' is an HTML input element for entering the folder name
const folderNameInput = document.getElementById('folderNameInput');
// Assuming 'uploadButton' is an HTML button triggering the file upload
const uploadButton = document.getElementById('uploadButton');
uploadButton.addEventListener('click', async () => {
const files = Array.from(fileInputs).map(input => input.files[0]);
const folderName = folderNameInput.value;
if (files.length === 0) {
console.error('No files selected');
return;
}
try {
const formData = new FormData();
formData.append('body', JSON.stringify({ folderName }));
files.forEach(file => {
formData.append('files', file);
});
const response = await fetch('/upload-files', {
method: 'POST',
body: formData,
});
// Handling the response
const result = await response.json();
console.log(result);
} catch (error) {
console.error('Error making the request:', error);
}
});
The Delete Single File API allows clients to delete a specific file from the server. Clients can use the /delete-file
route with the HTTP DELETE
method to delete a single file. This document provides detailed information on making successful requests to delete a file.
To delete a single file, clients must include the following parameters in the request:
-
folderName
(string): The name of the folder where the file is located. -
fileName
(string): The name of the file to be deleted.
DELETE /delete-file?folderName=uploads&fileName=example.txt
// Making a client-side request to delete a single file
const deleteButton = document.getElementById('deleteButton');
const folderNameInput = document.getElementById('folderNameInput');
const fileNameInput = document.getElementById('fileNameInput');
deleteButton.addEventListener('click', async () => {
const folderName = folderNameInput.value;
const fileName = fileNameInput.value;
if (!folderName || !fileName) {
console.error('Please provide both folderName and fileName');
return;
}
try {
const response = await fetch(`/delete-file?folderName=${folderName}&fileName=${fileName}`, {
method: 'DELETE',
});
// Handling the response
const result = await response.json();
console.log(result);
} catch (error) {
console.error('Error making the request:', error);
}
});
The Delete Multiple Files API allows clients to delete multiple files from a specified folder. Clients can use the /delete-files
route with the HTTP DELETE
method to remove multiple files. This document provides detailed information on making successful requests for deleting multiple files.
To delete multiple files, clients must include the following query parameter in the request:
-
queries
(array): An array of objects containing the details of files to be deleted.-
fileName
(string): The name of the file to be deleted. -
folderName
(string): The name of the folder where the file is located.
-
DELETE /delete-files?queries[0][fileName]=file1.txt&queries[0][folderName]=documents&queries[1][fileName]=file2.png&queries[1][folderName]=images
// Making a client-side request to delete multiple files
try {
const response = await fetch('/delete-files', {
method: 'DELETE',
});
// Handling the response
const result = await response.json();
console.log(result);
} catch (error) {
console.error('Error making the request:', error);
}
// Making a server-side request to delete multiple files
// Dependencies
import { controllers } from 'bapig';
try {
// Invoking the fileBulkDelete function from bapig controllers
const result = await controllers.fileBulkDelete([
{ fileName: 'file1.txt', folderName: 'documents' },
{ fileName: 'file2.png', folderName: 'images' },
]);
// Logging the result
console.log(result);
} catch (error) {
console.error('Error handling the request:', error);
}
The Send SMS API allows clients to send SMS messages to multiple recipients. Clients can use the /send-sms
route with the HTTP POST
method to send SMS messages. This document provides detailed information on making successful requests for sending SMS messages.
To send an SMS, clients must include the following parameters in the request body:
-
message
(string): The content of the SMS message. -
receivers
(array of strings): An array of phone numbers to which the SMS will be sent.
POST /send-sms
Content-Type: application/json
{
"message": "Hello, this is a test SMS message.",
"receivers": ["+1234567890", "+9876543210"]
}
// Making a client-side request to send an SMS
try {
const response = await fetch('/send-sms', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
message: 'Hello, this is a test SMS message.',
receivers: ['+1234567890', '+9876543210'],
}),
});
// Handling the response
const result = await response.json();
console.log(result);
} catch (error) {
console.error('Error making the request:', error);
}
// Making a server-side request to send an SMS
// Dependencies
import { controllers } from 'bapig';
try {
// Invoking the sendMessage function from bapig controllers
const result = await controllers.sendMessage({
message: 'Hello, this is a test SMS message.',
receivers: ['+1234567890', '+9876543210'],
});
// Logging the result
console.log(result);
} catch (error) {
console.error('Error handling the request:', error);
}
The Send Email API allows clients to send email messages. Clients can use the /send-email
route with the HTTP POST
method to send emails. This document provides detailed information on making successful requests for sending email messages.
To send an email, clients must include the following parameters in the request body:
-
to
(string): The email address of the recipient. -
text
(string): The plain text content of the email. -
from
(string): The sender's email address. -
html
(string): The HTML content of the email (optional). -
subject
(string): The subject of the email.
POST /send-email
Content-Type: application/json
{
"to": "recipient@example.com",
"text": "Hello, this is a test email message.",
"from": "sender@example.com",
"html": "<p>Hello, this is a test email message.</p>",
"subject": "Test Email"
}
// Making a client-side request to send an email
try {
const response = await fetch('/send-email', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
to: 'recipient@example.com',
text: 'Hello, this is a test email message.',
from: 'sender@example.com',
html: '<p>Hello, this is a test email message.</p>',
subject: 'Test Email',
}),
});
// Handling the response
const result = await response.json();
console.log(result);
} catch (error) {
console.error('Error making the request:', error);
}
// Making a server-side request to send an email
// Dependencies
import { controllers } from 'bapig';
try {
// Invoking the sendEmail function from bapig controllers
const result = await controllers.sendEmail({
to: 'recipient@example.com',
text: 'Hello, this is a test email message.',
from: 'sender@example.com',
html: '<p>Hello, this is a test email message.</p>',
subject: 'Test Email',
});
// Logging the result
console.log(result);
} catch (error) {
console.error('Error handling the request:', error);
}
The Generate OTP (One-Time Password) API allows clients to generate a six-digit random one-time password. Clients can use the /generate-otp
route with the HTTP GET
method to obtain a new OTP. This document provides detailed information on making successful requests for generating OTP.
To generate a one-time password, clients can make a simple GET
request to the /generate-otp
endpoint.
GET /generate-otp
// Making a server-side request to generate OTP
// Dependencies
import { controllers } from 'bapig';
try {
// Invoking the generateOTP function from the controllers object
const result = controllers.generateOTP();
// Logging the result
console.log(result);
} catch (error) {
console.error('Error handling the request:', error);
}
The API responds with a JSON object containing the success status and the generated one-time password.
{
"success": true,
"message": 123456
}
The message
field in the response contains the six-digit one-time password.
The Send OTP (One-Time Password) API enables clients to generate a random OTP and send it to a specified recipient via email and/or SMS. Clients can make a POST
request to the /send-otp
route to trigger the OTP generation and delivery process. This document provides detailed information on making successful requests for sending OTP.
To send an OTP, clients can make a POST
request to the /send-otp
endpoint with a JSON body containing the necessary information.
-
receiverEmail
(string, required): The email address of the OTP recipient. -
receiverPhone
(string, optional): The phone number of the OTP recipient for SMS delivery. -
senderEmail
(string, required): The email address from which the OTP email is sent.
POST /send-otp
Content-Type: application/json
{
"receiverEmail": "recipient@example.com",
"receiverPhone": "+1234567890",
"senderEmail": "sender@example.com"
}
// Making a server-side request to send OTP
// Dependencies
import { controllers } from 'bapig';
// Sample request body
const requestBody = {
receiverEmail: 'recipient@example.com',
receiverPhone: '+1234567890',
senderEmail: 'sender@example.com'
};
try {
// Invoking the sendOTP function from the controllers object
const result = await controllers.sendOTP(requestBody);
// Logging the result
console.log(result);
} catch (error) {
console.error('Error handling the request:', error);
}
The API responds with a JSON object containing the success status and details about the OTP delivery.
{
"success": true,
"message": {
"email": "Email sent successfully",
"sms": "SMS sent successfully",
"OTP": 123456
}
}
-
email
(string): Status of the email delivery. -
sms
(string): Status of the SMS delivery (ifreceiverPhone
is provided). -
OTP
(number): The generated six-digit one-time password.
The Push Notification API allows clients to send push notifications to subscribers using the Web Push protocol. Clients can make a POST
request to the /push-notification
route to deliver push notifications. This document provides detailed information on making successful requests for push notifications.
To send a push notification, clients can make a POST
request to the /push-notification
endpoint with a JSON body containing the necessary information.
-
endpoint
(string, required): The endpoint URL of the push subscription. -
keys
(object, required): Object containing thep256dh
andauth
keys for the push subscription. -
message
(string, required): The message to be included in the push notification.
POST /push-notification
Content-Type: application/json
{
"endpoint": "https://example.com/push-endpoint",
"keys": {
"p256dh": "your_p256dh_key",
"auth": "your_auth_key"
},
"message": "Hello, this is a push notification!"
}
// Making a server-side request to send a push notification
// Dependencies
import { controllers } from 'bapig';
// Sample subscriber object
const subscriberObject = {
"endpoint": "https://example.com/push-endpoint",
"keys": {
"p256dh": "your_p256dh_key",
"auth": "your_auth_key"
},
"message": "Hello, this is a push notification!"
};
try {
// Invoking the pushNotification function from the controllers object
const result = await controllers.pushNotification(subscriberObject);
// Logging the result
console.log(result);
} catch (error) {
console.error('Error handling the request:', error);
}
The API responds with a JSON object containing the success status and details about the push notification delivery.
{
"success": true,
"message": "Push notification sent successfully"
}
-
message
(string): Status of the push notification delivery.
- The push notification is sent to the specified
endpoint
with the provided message. - The
keys
object should contain thep256dh
(public key) andauth
(authentication secret) keys required for the push subscription. - The VAPID (Voluntary Application Server Identification) details, including the public and private keys, should be provided in the
options
object for authentication. - In case of an error or exception during the push notification delivery process, the API returns a
success
status offalse
along with an error message in themessage
field.
The Document Bulk List All API allows clients to retrieve multiple documents from different schemas based on specified conditions. Clients can make a GET
request to the /bulk-list-all
route to fetch documents in bulk. This document provides detailed information on making successful requests for bulk document retrieval.
To retrieve multiple documents from various schemas, clients can make a GET
request to the /bulk-list-all
endpoint with query parameters.
-
queries
(array, required): An array of objects representing queries for document retrieval. Each query object should contain the following keys:-
schema
(string, required): The name of the schema for document retrieval. -
condition
(object, required): The condition object specifying the criteria for document retrieval. -
sort
(object, required): The sorting criteria for the retrieved documents. -
select
(object, required): The fields to be selected for the retrieved documents. -
joinForeignKeys
(boolean, required): A boolean indicating whether to autopopulate joined foreign keys.
-
// Client-side fetch example
const response = await fetch('/bulk-list-all?queries=[{"schema":"user","condition":{"status":"active"},"sort":{"createdAt":1},"select":{"name":1},"joinForeignKeys":true},{"schema":"post","condition":{"status":"published"},"sort":{"createdAt":-1},"select":{"title":1},"joinForeignKeys":false}]');
const data = await response.json();
console.log(data);
// Making a server-side request to retrieve documents in bulk
// Dependencies
import { controllers } from 'bapig';
// Sample queries array
const queries = [
{
"schema": "user",
"condition": { "status": "active" },
"sort": { "createdAt": 1 },
"select": { "name": 1 },
"joinForeignKeys": true
},
{
"schema": "post",
"condition": { "status": "published" },
"sort": { "createdAt": -1 },
"select": { "title": 1 },
"joinForeignKeys": false
}
];
try {
// Invoking the bulkListAllDocuments function from the controllers object
const result = await controllers.bulkListAllDocuments(queries);
// Logging the result
console.log(result);
} catch (error) {
console.error('Error handling the request:', error);
}
The API responds with a JSON object containing the success status and details about the retrieved documents.
{
"success": true,
"message": {
"passedQueries": {
"users": [{ "name": "John" }],
"posts": [{ "title": "Sample Post" }]
},
"failedQueries": []
}
}
-
passedQueries
(object): An object containing the retrieved documents for each schema. -
failedQueries
(array): An array containing information about queries that failed along with the reasons for failure.
The Bulk Count Documents API allows clients to retrieve the count of documents from different schemas based on specified conditions. Clients can make a GET
request to the /bulk-count
route to fetch the count of documents in bulk. This document provides detailed information on making successful requests for bulk document count.
To retrieve the count of documents from various schemas, clients can make a GET
request to the /bulk-count
endpoint with query parameters.
-
queries
(array, required): An array of objects representing queries for document count. Each query object should contain the following keys:-
schema
(string, required): The name of the schema for document count. -
condition
(object, required): The condition object specifying the criteria for document count.
-
// Client-side fetch example
const response = await fetch('/bulk-count?queries=[{"schema":"user","condition":{"status":"active"}},{"schema":"post","condition":{"status":"published"}}]');
const data = await response.json();
console.log(data);
// Making a server-side request to retrieve document counts in bulk
// Dependencies
import { controllers } from 'bapig';
// Sample queries array
const queries = [
{
"schema": "user",
"condition": { "status": "active" }
},
{
"schema": "post",
"condition": { "status": "published" }
}
];
try {
// Invoking the bulkCountDocuments function from the controllers object
const result = await controllers.bulkCountDocuments(queries);
// Logging the result
console.log(result);
} catch (error) {
console.error('Error handling the request:', error);
}
The API responds with a JSON object containing the success status and details about the count of documents.
{
"success": true,
"message": {
"passedQueries": {
"users": 25,
"posts": 50
},
"failedQueries": []
}
}
-
passedQueries
(object): An object containing the count of documents for each schema. -
failedQueries
(array): An array containing information about queries that failed along with the reasons for failure.
The Document Bulk Read API allows clients to retrieve single documents from different schemas based on specified conditions. Clients can make a GET
request to the /bulk-read
route to fetch single documents in bulk. This document provides detailed information on making successful requests for bulk document reads.
To retrieve single documents from various schemas, clients can make a GET
request to the /bulk-read
endpoint with query parameters.
-
queries
(array, required): An array of objects representing queries for document read. Each query object should contain the following keys:-
schema
(string, required): The name of the schema for document read. -
condition
(object, required): The condition object specifying the criteria for document read. -
select
(object, required): The fields to be selected from the document. -
joinForeignKeys
(boolean, required): A boolean value indicating whether to autopopulate foreign keys.
-
// Client-side fetch example
const response = await fetch('/bulk-read?queries=[{"schema":"user","condition":{"status":"active"},"select":{"name":1,"email":1},"joinForeignKeys":true},{"schema":"post","condition":{"status":"published"},"select":{"title":1},"joinForeignKeys":false}]');
const data = await response.json();
console.log(data);
// Making a server-side request to retrieve single documents in bulk
// Dependencies
import { controllers } from 'bapig';
// Sample queries array
const queries = [
{
"schema": "user",
"condition": { "status": "active" },
"select": { "name": 1, "email": 1 },
"joinForeignKeys": true
},
{
"schema": "post",
"condition": { "status": "published" },
"select": { "title": 1 },
"joinForeignKeys": false
}
];
try {
// Invoking the bulkGetSingleDocument function from the controllers object
const result = await controllers.bulkGetSingleDocument(queries);
// Logging the result
console.log(result);
} catch (error) {
console.error('Error handling the request:', error);
}
The API responds with a JSON object containing the success status and details about the single documents.
{
"success": true,
"message": {
"passedQueries": {
"users": {
"name": "John Doe",
"email": "john.doe@example.com"
},
"posts": {
"title": "Sample Post Title"
}
},
"failedQueries": []
}
}
-
passedQueries
(object): An object containing the retrieved single documents for each schema. -
failedQueries
(array): An array containing information about queries that failed along with the reasons for failure.
The Aggregation API allows clients to perform aggregations on data from a specified schema using a provided aggregation pipeline. Clients can make a POST
request to the /aggregation
route to execute aggregations. This document provides detailed information on making successful requests for aggregations.
To perform aggregations, clients can make a POST
request to the /aggregation
endpoint with a JSON object containing the necessary information.
-
schema
(string, required): The name of the schema on which the aggregation is to be performed. -
aggregation
(array, required): An array representing the aggregation pipeline.
// Client-side fetch example
const response = await fetch('/aggregation', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
"schema": "user",
"aggregation": [
{ $match: { status: "active" } },
{ $group: { _id: "$role", count: { $sum: 1 } } }
]
}),
});
const data = await response.json();
console.log(data);
// Making a server-side request to perform aggregation
// Dependencies
import { controllers } from 'bapig';
// Sample aggregation object
const aggregationRequest = {
"schema": "user",
"aggregation": [
{ $match: { status: "active" } },
{ $group: { _id: "$role", count: { $sum: 1 } } }
]
};
try {
// Invoking the aggregate function from the controllers object
const result = await controllers.aggregate(aggregationRequest);
// Logging the result
console.log(result);
} catch (error) {
console.error('Error handling the request:', error);
}
The API responds with a JSON object containing the success status and details about the aggregation result.
{
"success": true,
"message": [
{ "_id": "admin", "count": 5 },
{ "_id": "user", "count": 15 }
]
}
-
message
(array): An array containing the result of the aggregation.
- The
schema
parameter should be a string representing the name of the schema on which the aggregation is to be performed. - The
aggregation
parameter should be an array representing the aggregation pipeline. - The API returns a
success
status oftrue
even if the aggregation does not produce results. In such cases, an empty array is provided in themessage
field.
The Bulk Aggregation API allows clients to perform multiple aggregations for different schemas in a single request. Clients can make a POST
request to the /bulk-aggregation
route with an array of aggregation requests, each containing the schema and aggregation pipeline. This document provides detailed information on making successful requests for bulk aggregations.
To perform bulk aggregations, clients can make a POST
request to the /bulk-aggregation
endpoint with an array of aggregation requests.
-
bodyArray
(array, required): An array of aggregation requests, each containing theschema
andaggregation
pipeline.
// Client-side fetch example
const response = await fetch('/bulk-aggregation', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify([
{
"schema": "user",
"aggregation": [
{ $match: { status: "active" } },
{ $group: { _id: "$role", count: { $sum: 1 } } }
]
},
{
"schema": "post",
"aggregation": [
{ $match: { published: true } },
{ $group: { _id: "$category", count: { $sum: 1 } } }
]
}
]),
});
const data = await response.json();
console.log(data);
// Making a server-side request to perform bulk aggregation
// Dependencies
import { controllers } from 'bapig';
// Sample aggregation array
const bulkAggregationRequest = [
{
"schema": "user",
"aggregation": [
{ $match: { status: "active" } },
{ $group: { _id: "$role", count: { $sum: 1 } } }
]
},
{
"schema": "post",
"aggregation": [
{ $match: { published: true } },
{ $group: { _id: "$category", count: { $sum: 1 } } }
]
}
];
try {
// Invoking the bulkAggregate function from the controllers object
const result = await controllers.bulkAggregate(bulkAggregationRequest);
// Logging the result
console.log(result);
} catch (error) {
console.error('Error handling the request:', error);
}
The API responds with a JSON object containing the success status and details about the aggregated queries.
{
"success": true,
"message": {
"passedQueries": {
"users": [
{ "_id": "admin", "count": 5 },
{ "_id": "user", "count": 15 }
],
"posts": [
{ "_id": "technology", "count": 8 },
{ "_id": "science", "count": 12 }
]
},
"failedQueries": [
{ "schema": "invalidSchema", "aggregation": [{ $invalidOperator: {} }], "reason": "Invalid schema" }
]
}
}
-
passedQueries
(object): An object containing the results of successful aggregated queries, with keys representing the pluralized schema names. -
failedQueries
(array): An array containing details of aggregation requests that failed, including the schema, aggregation pipeline, and the reason for failure.
- The
bodyArray
parameter should be an array of aggregation requests, each containing theschema
andaggregation
pipeline. - The API returns a
success
status oftrue
even if some aggregation requests fail. In such cases, details of failed queries are provided in thefailedQueries
field.
The Delete All Collections API allows clients to delete all documents in multiple collections based on a specified condition. Clients can make a DELETE
request to the /delete-all-collection
route with a query object containing the condition for deletion. This document provides detailed information on making successful requests for deleting all collections.
To delete all documents in multiple collections, clients can make a DELETE
request to the /delete-all-collection
endpoint with a query object containing the condition
for deletion.
-
condition
(object, required): The condition object specifying which documents to delete.
// Client-side fetch example
const response = await fetch('/delete-all-collection?condition={"status":"inactive"}', {
method: 'DELETE',
});
const data = await response.json();
console.log(data);
// Making a server-side request to delete all documents based on a condition
// Dependencies
import { controllers } from 'bapig';
// Sample query object
const deleteQuery = {
condition: { status: 'inactive' },
};
try {
// Invoking the deleteAllCollections function from the controllers object
const result = await controllers.deleteAllCollections(deleteQuery);
// Logging the result
console.log(result);
} catch (error) {
console.error('Error handling the request:', error);
}
The API responds with a JSON object containing the success status and details about the deletion process.
{
"success": true,
"message": {
"passedQueries": {
"users": { "n": 10, "ok": 1 },
"posts": { "n": 5, "ok": 1 }
},
"failedQueries": [
{ "collectionName": "invalidCollection", "reason": "Invalid collection" }
]
}
}
-
passedQueries
(object): An object containing the results of successful deletions, with keys representing the collection names and values representing the deletion details. -
failedQueries
(array): An array containing details of collections that failed to delete, including the collection name and the reason for failure.
- The
DELETE
request should include thecondition
query parameter specifying which documents to delete. - The API returns a
success
status oftrue
even if some collections fail to delete. In such cases, details of failed deletions are provided in thefailedQueries
field.
The Delete Many Documents API allows clients to delete multiple documents in a collection based on a specified condition. Clients can make a DELETE
request to the /delete-many
route with a query object containing the schema
and condition
for deletion. This document provides detailed information on making successful requests for deleting many documents.
To delete multiple documents in a collection, clients can make a DELETE
request to the /delete-many
endpoint with a query object containing the schema
and condition
for deletion.
-
schema
(string, required): The name of the schema or collection from which documents will be deleted. -
condition
(object, required): The condition object specifying which documents to delete.
// Client-side fetch example
const response = await fetch('/delete-many?schema=users&condition={"status": "inactive"}', {
method: 'DELETE',
headers: {
'Content-Type': 'application/json',
},
});
const data = await response.json();
console.log(data);
// Making a server-side request to delete many documents based on a condition
// Dependencies
import { controllers } from 'bapig';
// Sample query object
const deleteQuery = {
schema: 'users',
condition: { status: 'inactive' },
};
try {
// Invoking the deleteManyDocument function from the controllers object
const result = await controllers.deleteManyDocument(deleteQuery);
// Logging the result
console.log(result);
} catch (error) {
console.error('Error handling the request:', error);
}
The API responds with a JSON object containing the success status and details about the deletion process.
{
"success": true,
"message": {
"n": 10,
"ok": 1
}
}
-
n
(number): The number of documents deleted. -
ok
(number): The deletion status.
The Bulk Delete Many Documents API allows clients to delete multiple documents in different collections based on specified conditions. Clients can make a DELETE
request to the /bulk-delete-many
route with an array of query objects, each containing the schema
and condition
for deletion. This document provides detailed information on making successful requests for bulk deleting many documents.
To bulk delete multiple documents in various collections, clients can make a DELETE
request to the /bulk-delete-many
endpoint with an array of query objects, each containing the schema
and condition
for deletion.
Each query object in the array should contain the following parameters:
-
schema
(string, required): The name of the schema or collection from which documents will be deleted. -
condition
(object, required): The condition object specifying which documents to delete.
// Client-side fetch example
const queries = [
{ schema: 'users', condition: { status: 'inactive' } },
{ schema: 'posts', condition: { isArchived: true } },
// Add more queries as needed
];
const queryString = queries.map(query => {
return `schema=${query.schema}&condition=${JSON.stringify(query.condition)}`;
}).join('&');
const response = await fetch(`/bulk-delete-many?${queryString}`, {
method: 'DELETE',
});
const data = await response.json();
console.log(data);
// Making a server-side request to bulk delete many documents based on conditions
// Dependencies
import { controllers } from 'bapig';
// Sample array of delete queries
const deleteQueries = [
{ schema: 'users', condition: { status: 'inactive' } },
{ schema: 'posts', condition: { isArchived: true } },
// Add more queries as needed
];
try {
// Invoking the documentBulkDeleteMany function from the controllers object
const result = await controllers.documentBulkDeleteMany(deleteQueries);
// Logging the result
console.log(result);
} catch (error) {
console.error('Error handling the request:', error);
}
The API responds with a JSON object containing the success status and details about the bulk deletion process.
{
"success": true,
"message": {
"passedQueries": [
{ "n": 10, "ok": 1 },
{ "n": 5, "ok": 1 }
// Add more results for each query
],
"failedQueries": [
{ "schema": "users", "condition": { "status": "inactive" }, "reason": "Failed to delete users" },
// Add more details for each failed query
]
}
}
-
passedQueries
(array): An array containing details about successful deletions for each query. -
failedQueries
(array): An array containing details about failed deletions for each query, including theschema
,condition
, andreason
for the failure.
The Bulk Update Many Documents API allows clients to update multiple documents in different collections based on specified conditions. Clients can make a PUT
request to the /bulk-update-many
route with an array of update objects, each containing the schema
, condition
, and newDocumentData
for updating documents. This document provides detailed information on making successful requests for bulk updating many documents.
To bulk update multiple documents in various collections, clients can make a PUT
request to the /bulk-update-many
endpoint with an array of update objects, each containing the schema
, condition
, and newDocumentData
for updating.
The request body should be an array of update objects, each with the following parameters:
-
schema
(string, required): The name of the schema or collection in which documents will be updated. -
condition
(object, required): The condition object specifying which documents to update. -
newDocumentData
(object, required): The new data that will replace the existing document data.
// Client-side fetch example
const updates = [
{ schema: 'users', condition: { status: 'active' }, newDocumentData: { status: 'inactive' } },
{ schema: 'posts', condition: { isArchived: false }, newDocumentData: { isArchived: true } },
// Add more updates as needed
];
const response = await fetch('/bulk-update-many', {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(updates),
});
const data = await response.json();
console.log(data);
// Making a server-side request to bulk update many documents based on conditions
// Dependencies
import { controllers } from 'bapig';
// Sample array of updates
const updateArray = [
{ schema: 'users', condition: { status: 'active' }, newDocumentData: { status: 'inactive' } },
{ schema: 'posts', condition: { isArchived: false }, newDocumentData: { isArchived: true } },
// Add more updates as needed
];
try {
// Invoking the bulkUpdateManyDocument function from the controllers object
const result = await controllers.bulkUpdateManyDocument(updateArray);
// Logging the result
console.log(result);
} catch (error) {
console.error('Error handling the request:', error);
}
The API responds with a JSON object containing the success status and details about the bulk update process.
{
"success": true,
"message": {
"passedQueries": [
{ "n": 10, "nModified": 5, "ok": 1 },
{ "n": 5, "nModified": 2, "ok": 1 }
// Add more results for each query
],
"failedQueries": [
{ "schema": "users", "condition": { "status": "active" }, "newDocumentData": { "status": "inactive" }, "reason": "Failed to update users" },
// Add more details for each failed query
]
}
}
-
passedQueries
(array): An array containing details about successful updates for each query. -
failedQueries
(array): An array containing details about failed updates for each query, including theschema
,condition
,newDocumentData
, andreason
for the failure.
The List All Collections API allows clients to retrieve data from all collections based on specified conditions. Clients can make a GET
request to the /list-all-collection
route with parameters in the query string to filter, sort, and optionally join foreign keys. This document provides detailed information on making successful requests for listing all collections.
To retrieve data from all collections, clients can make a GET
request to the /list-all-collection
endpoint with parameters in the query string.
-
condition
(object, optional): Specifies the conditions for filtering documents. -
sort
(object, optional): Specifies the sorting criteria for the result. -
joinForeignKeys
(boolean, optional): If set totrue
, the API will automatically populate joined foreign keys in the result.
// Client-side fetch example
const queryParams = {
condition: { status: 'active' },
sort: { createdAt: 'desc' },
joinForeignKeys: true,
};
const response = await fetch(`/list-all-collection?${new URLSearchParams(queryParams)}`, {
method: 'GET',
});
const data = await response.json();
console.log(data);
// Making a server-side request to list data from all collections based on conditions
// Dependencies
import { controllers } from 'bapig';
// Sample query parameters
const query = {
condition: { status: 'active' },
sort: { createdAt: 'desc' },
joinForeignKeys: true,
};
try {
// Invoking the listAllCollections function from the controllers object
const result = await controllers.listAllCollections(query);
// Logging the result
console.log(result);
} catch (error) {
console.error('Error handling the request:', error);
}
The API responds with a JSON object containing the success status and data retrieved from all collections based on the specified conditions.
{
"success": true,
"message": {
"users": [
{ "_id": "60abcf091fd3b73a1b38a22c", "username": "john_doe", "status": "active", "createdAt": "2022-05-24T12:30:45Z" },
// Add more user data as needed
],
"posts": [
{ "_id": "60abcf091fd3b73a1b38a22d", "title": "Sample Post", "content": "Lorem ipsum...", "createdAt": "2022-05-25T09:15:30Z" },
// Add more post data as needed
],
// Add more collections as needed
}
}
The Update All Collections API allows clients to update multiple documents in all collections based on specified conditions. Clients can make a PUT
request to the /update-all-collection
route with parameters in the request body to set conditions and provide new data for the update. This document provides detailed information on making successful requests for updating all collections.
To update multiple documents in all collections, clients can make a PUT
request to the /update-all-collection
endpoint with parameters in the request body.
-
condition
(object, required): Specifies the conditions for updating documents. -
newDocumentData
(object, required): Specifies the new data that will replace existing data.
// Client-side fetch example
const requestBody = {
condition: { status: 'active' },
newDocumentData: { $set: { status: 'inactive' } },
};
const response = await fetch(`/update-all-collection`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(requestBody),
});
const data = await response.json();
console.log(data);
// Making a server-side request to update multiple documents in all collections based on conditions
// Dependencies
import { controllers } from 'bapig';
// Sample request body
const requestBody = {
condition: { status: 'active' },
newDocumentData: { $set: { status: 'inactive' } },
};
try {
// Invoking the updateAllCollections function from the controllers object
const result = await controllers.updateAllCollections(requestBody);
// Logging the result
console.log(result);
} catch (error) {
console.error('Error handling the request:', error);
}
The API responds with a JSON object containing the success status and information about the updated and failed collections.
{
"success": true,
"message": {
"passedQueries": {
"users": { "n": 5, "nModified": 5, "ok": 1 },
"posts": { "n": 10, "nModified": 10, "ok": 1 },
// Add more collections as needed
},
"failedQueries": [
{ "condition": { "status": "active" }, "newDocumentData": { "$set": { "status": "inactive" } }, "reason": "Failed to update collection comments" },
// Add more failed queries as needed
]
}
}
- The
success
field indicates whether the request was successful (true
) or not (false
). - The
message
field contains an object with two properties:-
passedQueries
: An object where each key represents a collection, and the corresponding value is information about the update operation. -
failedQueries
: An array of objects containing the conditions, new document data, and the reason for failure for each collection that failed to update.
-
The Update Many Documents API allows clients to update multiple documents in a specific collection based on specified conditions. Clients can make a PUT
request to the /update-many
route with parameters in the request body to set conditions and provide new data for the update. This document provides detailed information on making successful requests for updating many documents.
To update multiple documents in a specific collection, clients can make a PUT
request to the /update-many
endpoint with parameters in the request body.
-
schema
(string, required): Specifies the schema or collection name. -
condition
(object, required): Specifies the conditions for updating documents. -
newDocumentData
(object, required): Specifies the new data that will replace existing data.
// Client-side fetch example
const requestBody = {
schema: 'users',
condition: { status: 'active' },
newDocumentData: { $set: { status: 'inactive' } },
};
const response = await fetch(`/update-many`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(requestBody),
});
const data = await response.json();
console.log(data);
// Making a server-side request to update multiple documents in a specific collection based on conditions
// Dependencies
import { controllers } from 'bapig';
// Sample request body
const requestBody = {
schema: 'users',
condition: { status: 'active' },
newDocumentData: { $set: { status: 'inactive' } },
};
try {
// Invoking the updateManyDocument function from the controllers object
const result = await controllers.updateManyDocument(requestBody);
// Logging the result
console.log(result);
} catch (error) {
console.error('Error handling the request:', error);
}
The API responds with a JSON object containing the success status and information about the updated documents.
{
"success": true,
"message": {
"n": 5,
"nModified": 5,
"ok": 1
}
}
- The
success
field indicates whether the request was successful (true
) or not (false
). - The
message
field contains information about the update operation, including the number of documents matched (n
), the number of documents modified (nModified
), and the operation status (ok
).
The Count All Collections API allows clients to count the number of documents in all collections based on specified conditions. Clients can make a GET
request to the /count-all-collection
route with parameters in the request query to set conditions for counting documents. This document provides detailed information on making successful requests for counting documents in all collections.
To count the number of documents in all collections based on specified conditions, clients can make a GET
request to the /count-all-collection
endpoint with parameters in the request query.
-
condition
(object, required): Specifies the conditions for counting documents.
// Client-side fetch example
const condition = { status: 'active' };
const response = await fetch(`/count-all-collection?condition=${JSON.stringify(condition)}`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
});
const data = await response.json();
console.log(data);
// Making a server-side request to count documents in all collections based on conditions
// Dependencies
import { controllers } from 'bapig';
// Sample request query
const condition = { status: 'active' };
try {
// Invoking the countAllCollections function from the controllers object
const result = await controllers.countAllCollections({ condition });
// Logging the result
console.log(result);
} catch (error) {
console.error('Error handling the request:', error);
}
The API responds with a JSON object containing the success status and information about the counts in each collection.
{
"success": true,
"message": {
"users": 100,
"posts": 250,
"comments": 50
}
}
The Search Documents API allows clients to search for documents in a specific collection based on a keyword and other optional parameters. Clients can make a GET
request to the /search
route with parameters in the request query to perform a search. This document provides detailed information on making successful requests for searching documents.
To search for documents based on a keyword and other optional parameters, clients can make a GET
request to the /search
endpoint with parameters in the request query.
-
condition
(object, optional): Specifies additional conditions for the search. -
schema
(string, required): Specifies the schema or collection name for the search. -
keyword
(string, required): Specifies the keyword to search for. -
sort
(object, optional): Specifies the sorting criteria for the search results. -
fields
(array of strings, optional): Specifies the fields to search within. -
select
(object, optional): Specifies the fields to include or exclude in the search results. -
joinForeignKeys
(boolean, optional): Specifies whether to populate foreign key fields in the search results.
// Client-side fetch example
const query = {
condition: { status: 'active' },
schema: 'product',
keyword: 'laptop',
sort: { price: 'asc' },
fields: ['name', 'description'],
select: { name: 1, price: 1, _id: 0 },
joinForeignKeys: true,
};
const response = await fetch(`/search?${new URLSearchParams(query)}`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
});
const data = await response.json();
console.log(data);
// Making a server-side request to search for documents based on a keyword
// Dependencies
import { controllers } from 'bapig';
// Sample search query
const searchQuery = {
condition: { status: 'active' },
schema: 'product',
keyword: 'laptop',
sort: { price: 'asc' },
fields: ['name', 'description'],
select: { name: 1, price: 1, _id: 0 },
joinForeignKeys: true,
};
try {
// Invoking the search function from the controllers object
const result = await controllers.search(searchQuery);
// Logging the result
console.log(result);
} catch (error) {
console.error('Error handling the request:', error);
}
The API responds with a JSON object containing the success status and the search results.
{
"success": true,
"message": [
{
"name": "Laptop XYZ",
"description": "Powerful laptop for gaming and work",
"price": 1200
},
{
"name": "Slim Laptop",
"description": "Lightweight laptop with long battery life",
"price": 900
}
]
}
- The
success
field indicates whether the request was successful (true
) or not (false
). - The
message
field contains an array of search results based on the specified conditions.
- The
GET
request should include query parameters with at least theschema
andkeyword
keys. - Additional parameters such as
condition
,sort
,fields
,select
, andjoinForeignKeys
can be included based on the specific requirements of the search. - The API returns a
success
status oftrue
if the search operation is successful, along with the search results. If no documents are found, it returns asuccess
status offalse
with an appropriate message.
The Transaction API allows clients to perform a series of database operations within a transaction. Clients can make a POST
request to the /transaction
route with an array of transaction operations. This document provides detailed information on making successful requests for performing transactions.
To perform a transaction with a series of database operations, clients can make a POST
request to the /transaction
endpoint with an array of transaction operations in the request body.
-
operations
(array of objects, required): Specifies the array of transaction operations. Each operation object should contain the following keys:-
schema
(string, required): Specifies the schema or collection name for the operation. -
method
(string, required): Specifies the database operation method (create
,updateOne
,updateMany
,deleteOne
,deleteMany
). -
documentData
(object, required): Specifies the data for the database operation. -
condition
(object, optional): Specifies the condition for the operation (used in update and delete operations).
-
// Client-side fetch example
const transactionData = {
operations: [
{
schema: 'product',
method: 'create',
documentData: { name: 'New Product', price: 99.99, quantity: 50 },
},
{
schema: 'product',
method: 'updateOne',
documentData: { price: 79.99 },
condition: { name: 'New Product' },
},
{
schema: 'product',
method: 'deleteOne',
condition: { quantity: 0 },
},
],
};
const response = await fetch('/transaction', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(transactionData),
});
const data = await response.json();
console.log(data);
// Making a server-side request to perform a transaction with database operations
// Dependencies
import { controllers } from 'bapig';
// Sample transaction data
const transactionData = {
operations: [
{
schema: 'product',
method: 'create',
documentData: { name: 'New Product', price: 99.99, quantity: 50 },
},
{
schema: 'product',
method: 'updateOne',
documentData: { price: 79.99 },
condition: { name: 'New Product' },
},
{
schema: 'product',
method: 'deleteOne',
condition: { quantity: 0 },
},
],
};
try {
// Invoking the performTransaction function from the controllers object
const result = await controllers.performTransaction(transactionData);
// Logging the result
console.log(result);
} catch (error) {
console.error('Error handling the request:', error);
}
The API responds with a JSON object containing the success status and the result of the transaction operations.
{
"success": true,
"message": {
"product": {
"create": {
"_id": "609c34378006de001e0a15a4",
"name": "New Product",
"price": 99.99,
"quantity": 50
},
"updateOne": {
"n": 1,
"nModified": 1,
"ok": 1
},
"deleteOne": {
"n": 1,
"ok": 1
}
}
}
}
- The
success
field indicates whether the transaction was successful (true
) or not (false
). - The
message
field contains the result of each transaction operation grouped by schema and method.
- The
POST
request should include theoperations
array in the request body. - Each operation within the
operations
array should includeschema
,method
, anddocumentData
keys. - The API returns a
success
status oftrue
if the transaction is successful, along with the result of each operation. If any operation fails, it returns asuccess
status offalse
with an appropriate message.