AuteurLabb Networking Platform - Complete Documentation

AuteurLabb is a networking platform that connects filmmakers, studios, investors, and supporters to collaborate on film projects with secure access and role-based workflows.

This document contains the full documentation for all services in the AuteurLabb Networking Platform project. It is designed for comprehensive reference by both humans and AI agents.


Table of Contents

Getting Started

Frontend Prompts

Auth Service

ProjectPortfolio Service

MessagingCenter Service

ModerationAdmin Service

AgentHub Service

Bff Service

Notification Service

LLM Documents


Getting Started

AuteurLabb Networking Platform

AuteurLabb Networking Platform

Version : 1.0.71

AuteurLabb is a networking platform that connects filmmakers, studios, investors, and supporters to collaborate on film projects with secure access and role-based workflows.

How to Use Project Documents

The Auteurlabb project has been designed and generated using Mindbricks, a powerful microservice-based backend generation platform. All documentation is automatically produced by the Mindbricks Genesis Engine, based on the high-level architectural patterns defined by the user or inferred by AI.

This documentation set is intended for both AI agents and human developers—including frontend and backend engineers—who need precise and structured information about how to interact with the backend services of this project. Each document reflects the live architecture of the system, providing a reliable reference for API consumption, data models, authentication flows, and business logic.

By following this documentation, developers can seamlessly integrate with the backend, while AI agents can use it to reason about the service structure, make accurate decisions, or even generate compatible client-side code.

Accessing Project Services

Each service generated by Mindbricks is exposed via a dedicated REST API endpoint. Every service documentation set includes the base URL of that service along with the specific API paths for each available route.

Before consuming any API, developers or agents must understand the service URL structure and environment-specific endpoints.

Service Endpoint Structure

Environment URL Pattern Example
Preview https://auteurlabb.prw.mindbricks.com/auth-api
Staging https://auteurlabb-stage.mindbricks.co/auth-api
Production https://auteurlabb.mindbricks.co/auth-api

Replace auth with the actual service name as lower case (e.g., order-api, bff-service, customermanagement-api etc.).

Environment Usage Notes

Frontend applications should be designed to easily switch between environments, allowing dynamic endpoint targeting for Preview, Staging, and Production.

Getting Started: Use the Auth Service First

Before interacting with other services in the Auteurlabb project, AI agents and developers should begin by integrating with the Auth Service.

Mindbricks automatically generates a dedicated authentication microservice based on the project’s authentication definitions provided by the architect. This service provides the essential user and access management foundation for the project.

Agents should first utilize the Auth Service to:

Auth Service Documentation

Use the following resources to understand and integrate the Auth Service:

Note: For most frontend use cases, the REST API Guide will be the primary source. The Event Guide and Service Design documents are especially useful when integrating with other backend microservices or building systems that interact with the auth service indirectly.

Using the BFF (Backend-for-Frontend) Service

In Mindbricks, all backend services are designed with an advanced CQRS (Command Query Responsibility Segregation) architecture. Within this architecture, business services are responsible for managing their respective domains and ensuring the accuracy and freshness of domain data.

The BFF service complements these business services by providing a read-only aggregation and query layer tailored specifically for frontend and client-side applications.

Key Principles of the BFF Service

BFF Service Documentation

Tip: Use the BFF service as the main entry point for all frontend data queries. It simplifies access, reduces round-trips, and ensures that data is shaped appropriately for the UI layer.

Business Services Overview

The AuteurLabb Networking Platform project consists of multiple business services, each responsible for managing a specific domain within the system. These services expose their own REST APIs and documentation sets, and are accessible based on the environment (Preview, Staging, Production).

Usage Guidance

Business services are primarily designed to:

For advanced query needs across multiple services or aggregated views, prefer using the BFF service.

Available Business Services

projectPortfolio Service

Description: Handles the lifecycle of film projects and access management, allowing filmmakers & studios to submit, update, publish (public/private), withdraw projects, and manage project access for investors/bookmarks. Enforces admin approval & efficient searching/filtering. Connects projects to user (and optionally studio) ownership.

Documentation:

Base URL Examples:

Environment URL
Preview https://auteurlabb.prw.mindbricks.com/projectportfolio-api
Staging https://auteurlabb-stage.mindbricks.co/projectportfolio-api
Production https://auteurlabb.mindbricks.co/projectportfolio-api

messagingCenter Service

Description: Facilitates secure messaging between filmmakers, studios, and investors, enabling message threads, moderation, and notifications for industry collaborations.

Documentation:

Base URL Examples:

Environment URL
Preview https://auteurlabb.prw.mindbricks.com/messagingcenter-api
Staging https://auteurlabb-stage.mindbricks.co/messagingcenter-api
Production https://auteurlabb.mindbricks.co/messagingcenter-api

moderationAdmin Service

Description: Handles approval workflows for studios, investors, and projects; facilitates platform content moderation, user suspensions, and records all related admin actions for audit and compliance.

Documentation:

Base URL Examples:

Environment URL
Preview https://auteurlabb.prw.mindbricks.com/moderationadmin-api
Staging https://auteurlabb-stage.mindbricks.co/moderationadmin-api
Production https://auteurlabb.mindbricks.co/moderationadmin-api

agentHub Service

Description: AI Agent Hub

Documentation:

Base URL Examples:

Environment URL
Preview https://auteurlabb.prw.mindbricks.com/agenthub-api
Staging https://auteurlabb-stage.mindbricks.co/agenthub-api
Production https://auteurlabb.mindbricks.co/agenthub-api

Connect via MCP (Model Context Protocol)

All backend services in the Auteurlabb project expose their Business APIs as MCP tools. These tools are aggregated by the MCP-BFF service into a single unified endpoint that external AI tools can connect to.

Unified MCP Endpoint

Environment StreamableHTTP (recommended) SSE (legacy fallback)
Preview https://auteurlabb.prw.mindbricks.com/mcpbff-api/mcp https://auteurlabb.prw.mindbricks.com/mcpbff-api/mcp/sse
Staging https://auteurlabb-stage.mindbricks.co/mcpbff-api/mcp https://auteurlabb-stage.mindbricks.co/mcpbff-api/mcp/sse
Production https://auteurlabb.mindbricks.co/mcpbff-api/mcp https://auteurlabb.mindbricks.co/mcpbff-api/mcp/sse

Authentication

MCP connections require authentication via the Authorization header:

OAuth is not supported for MCP connections at this time.

Connecting from Cursor

Add the following to your project’s .cursor/mcp.json:

{
  "mcpServers": {
    "auteurlabb": {
      "url": "https://auteurlabb.prw.mindbricks.com/mcpbff-api/mcp",
      "headers": {
        "Authorization": "Bearer sk_mbx_your_api_key_here"
      }
    }
  }
}

Connecting from Claude Desktop

Add to your Claude Desktop configuration (claude_desktop_config.json):

{
  "mcpServers": {
    "auteurlabb": {
      "url": "https://auteurlabb.prw.mindbricks.com/mcpbff-api/mcp",
      "headers": {
        "Authorization": "Bearer sk_mbx_your_api_key_here"
      }
    }
  }
}

What’s Available

Once connected, the AI tool can discover and call all Business API tools from all services — CRUD operations, custom queries, file operations, and more. The MCP-BFF handles routing each tool call to the correct backend service and propagates your authentication context.


Conclusion

This documentation set provides a comprehensive guide for understanding and consuming the AuteurLabb Networking Platform backend, generated by the Mindbricks platform. It is structured to support both AI agents and human developers in navigating authentication, data access, service responsibilities, and system architecture.

To summarize:

Each service offers a complete set of documentation—REST API guides, event interface definitions, and design insights—to help you integrate efficiently and confidently.

Whether you are building a frontend application, configuring an automation agent, or simply exploring the architecture, this documentation is your primary reference for working with the backend of this project.

For environment-specific access, ensure you’re using the correct base URLs (Preview, Staging, Production), and coordinate with the project owner for any custom deployments.


Frontend Prompts

Project Introduction & Setup

AUTEURLABB

FRONTEND GUIDE FOR AI CODING AGENTS - PART 1 - Project Introduction & Setup

This is the introductory document for the auteurlabb frontend project. It is designed for AI agents that will generate frontend code to consume the project’s backend. Read it carefully — it describes the project scope, architecture, API conventions, and initial screens you must build before proceeding to the feature-specific prompts that follow.

This prompt will help you set up the project infrastructure, create the initial layout, home page, navigation, and any dummy screens. The subsequent prompts will provide detailed API documentation for each feature area.

Project Introduction

AuteurLabb is a networking platform that connects filmmakers, studios, investors, and supporters to collaborate on film projects with secure access and role-based workflows.

Project Services Overview

The project has 1 auth service, 1 notification service, 1 BFF service, and 4 business services, plus other helper services such as bucket and realtime.

Each service is a separate microservice application and listens for HTTP requests at different service URLs.

# Service Description API Prefix
1 auth Authentication and user management /auth-api
2 projectPortfolio Handles the lifecycle of film projects and access management, allowing filmmakers & studios to submit, update, publish (public/private), withdraw projects, and manage project access for investors/bookmarks. Enforces admin approval & efficient searching/filtering. Connects projects to user (and optionally studio) ownership. /projectPortfolio-api
3 messagingCenter Facilitates secure messaging between filmmakers, studios, and investors, enabling message threads, moderation, and notifications for industry collaborations. /messagingCenter-api
4 moderationAdmin Handles approval workflows for studios, investors, and projects; facilitates platform content moderation, user suspensions, and records all related admin actions for audit and compliance. /moderationAdmin-api
5 agentHub AI Agent Hub /agentHub-api

Detailed API documentation for each service will be given in the following prompts. In this document, you will build the initial project structure, home pages, and navigation.

API Structure

Object Structure of a Successful Response

When the service processes requests successfully, it wraps the requested resource(s) within a JSON envelope. This envelope includes the data and essential metadata such as configuration details and pagination information, providing context to the client.

HTTP Status Codes:

Success Response Format:

For successful operations, the response includes a "status": "OK" property, signaling that the request executed successfully. The structure of a successful response is outlined below:

{
  "status":"OK",
  "statusCode": 200,   
  "elapsedMs":126,
  "ssoTime":120,
  "source": "db",
  "cacheKey": "hexCode",
  "userId": "ID",
  "sessionId": "ID",
  "requestId": "ID",
  "dataName":"products",
  "method":"GET",
  "action":"list",
  "appVersion":"Version",
  "rowCount":3,
  "products":[{},{},{}],
  "paging": {
    "pageNumber":1, 
    "pageRowCount":25, 
    "totalRowCount":3,
    "pageCount":1
  },
  "filters": [],
  "uiPermissions": []
}

Additional Data

Each API may include additional data besides the main data object, depending on the business logic of the API. These will be provided in each API’s response signature.

Error Response

If a request encounters an issue—whether due to a logical fault or a technical problem—the service responds with a standardized JSON error structure. The HTTP status code indicates the nature of the error, using commonly recognized codes for clarity:

Each error response is structured to provide meaningful insight into the problem, assisting in efficient diagnosis and resolution.

{
  "result": "ERR",
  "status": 400,
  "message": "errMsg_organizationIdisNotAValidID",
  "errCode": 400,
  "date": "2024-03-19T12:13:54.124Z",
  "detail": "String"
}

Accessing the Backend

Each backend service has its own URL for each deployment environment. Users may want to test the frontend in one of the three deployments—preview, staging, or production. Please ensure that the home page includes a deployment server selection option so that, as the frontend coding agent, you can set the base URL for all services.

The base URL of the application in each environment is as follows:

For the auth service, the base URLs are:

For each other service, append /{serviceName}-api to the environment base URL.

Any request that requires login must include a valid token in the Bearer authorization header.

Please note that for each service in the project (which will be introduced in following prompts) will use a different address so it is a good practice to define a separate client for each service in the frontend application lib source. Not only the different base urls, some services even may need different access rules when shaping the request.

Services may be deployed to the preview server, staging server, or production server. Therefore, each service has 3 access URLs. The frontend application must support all deployment environments during development, and the user should be able to select the target API server on the home page.

Home Page

First build a home page which shows some static content about the application, and has got login and registration (if is public) buttons. The home page should be updated later according to the content that each service provides, as a frontend developer use best and common practices to reflect the service content to the home page. User may also give extra information for the home page content in addition to this prompt.

Note that this page should include a deployment (environment) selection option to set the base URL. Set the default to production.

After user logs in, page header should show the current login state as in modern web pages, logged in user fullname, avatar, email and with a logout link, make a fancy current user component. The home page may have different views before and after login.

Initial Navigation Structure

Build the initial navigation/sidebar with placeholder pages for each area of the application. These will be implemented in detail by the subsequent prompts:

Create these as placeholder/dummy pages with a title and “Coming soon” note. They will be filled in by the following prompts.

What To Build Now

With this prompt, build:

  1. Project infrastructure — routing, layout, environment config, API client setup (one client per service)
  2. Home page with environment selector, login/register buttons, project description
  3. Placeholder pages for all navigation items listed above
  4. Common components — header with user info, navigation sidebar/menu, layout wrapper

Do not implement authentication flows, registration, or any service-specific features yet — those will be covered in the next prompts.

Common Reminders

  1. When the application starts, please ensure that the baseUrl is set to the production server URL, and that the environment selector dropdown has the Production option selected by default.
  2. Note that any API call to the application backend is based on a service base URL. Auth APIs use /auth-api prefix, and each business service uses /{serviceName}-api prefix after the application’s base URL.
  3. The deployment environment selector will only be used in the home page. If any page is called directly bypassing the home page, the page will use the stored or default environment.

Authentication Management

AUTEURLABB

FRONTEND GUIDE FOR AI CODING AGENTS - PART 2 - Authentication Management

This document covers the authentication features of the auteurlabb project: registration, login, logout, and session management. The project introduction, API conventions, base URLs, home page, and multi-tenancy setup were covered in the previous introductory prompt — make sure those are implemented before proceeding.

All auth APIs use the auth service base URL with the /auth-api prefix (e.g., https://auteurlabb.mindbricks.co/auth-api).

FRONTEND_URL

The FRONTEND_URL environment variable is automatically set on the auth service from the project’s frontendUrl setting in Basic Project Settings. It contains the base URL of the frontend application for the current deployment environment (e.g., http://localhost:5173 for dev, https://myapp.com for production). Defaults if not configured:

Environment Default
dev http://localhost:5173
test https://auteurlabb.prw.mindbricks.com
stage https://auteurlabb-stage.mindbricks.co
prod https://auteurlabb.mindbricks.co

This variable is used by the auth service for:

You can customize FRONTEND_URL per environment by configuring the frontendUrl field in your project’s Basic Project Settings (e.g., when using a custom domain).

Registration Management

User Registration

User registration is public in the application. Please create a simple and polished registration page that includes only the necessary fields of the registration API.

Using the registeruser route of the auth API, send the required fields from your registration page.

The registerUser API in the auth service is described with the request and response structure below.

Note that since the registerUser API is a business API, it is versioned; call it with the given version like /v1/registeruser.

Register User API

This api is used by public users to register themselves

Rest Route

The registerUser API REST controller can be triggered via the following route:

/v1/registeruser

Rest Request Parameters

The registerUser api has got 4 regular request parameters

Parameter Type Required Population
avatar String false request.body?.[“avatar”]
password String true request.body?.[“password”]
fullname String true request.body?.[“fullname”]
email String true request.body?.[“email”]
avatar : The avatar url of the user. If not sent, a default random one will be generated.
password : The password defined by the the user that is being registered.
fullname : The fullname defined by the the user that is being registered.
email : The email defined by the the user that is being registered.

REST Request To access the api you can use the REST controller with the path POST /v1/registeruser

  axios({
    method: 'POST',
    url: '/v1/registeruser',
    data: {
            avatar:"String",  
            password:"String",  
            fullname:"String",  
            email:"String",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "user",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"user": {
		"id": "ID",
		"email": "String",
		"password": "String",
		"fullname": "String",
		"avatar": "String",
		"roleId": "String",
		"emailVerified": "Boolean",
		"approvalStatus": "Enum",
		"approvalStatus_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

After a successful registration, the frontend code should handle any verification requirements. Verification Management will be given in the next prompt.

The registration response will include a user object in the root envelope; this object contains user information with an id field.

Login Management

Login Identifier Model

The primary login identifier for this application is the email address. Users register and log in using their email and password. No mobile field is stored in the user data model. The login page should include an email input and a password input.

Login Flow

After successful registration and completing any required verifications, the user can log in. Please create a minimal, polished login page as described above. Note that this page should respect the deployment (environment) selection option made in the home page to set the base URL. If the user reaches this page directly skipping home page, the default production deployment will be used.

The login API returns a created session. This session can be retrieved later with the access token using the /currentuser system route.

Any request that requires login must include a valid token. When a user logs in successfully, the response JSON includes a JWT access token in the accessToken field. Under normal conditions, this token is also set as a cookie and consumed automatically. However, since AI coding agents’ preview options may fail to use cookies, ensure that each request includes the access token in the Bearer authorization header.

If the login fails due to verification requirements, the response JSON includes an errCode. If it is EmailVerificationNeeded, start the email verification flow; if it is MobileVerificationNeeded, start the mobile verification flow.

After a successful login, you can access session (user) information at any time with the /currentuser API. On inner pages, show brief profile information (avatar, name, etc.) using the session information from this API.

Note that the currentuser API returns a session object, so there is no id property; instead, the values for the user and session are exposed as userId and sessionId. The response combines user and session information.

The login, logout, and currentuser APIs are as follows. They are system routes and are not versioned.

POST /login — User Login

Purpose: Verifies user credentials and creates an authenticated session with a JWT access token.

Access Routes:

Request Parameters

Parameter Type Required Source
username String Yes request.body.username
password String Yes request.body.password

Behavior

Example

axios.post("/login", {
  email: "user@example.com",
  password: "securePassword"
});

Success Response

{
  "sessionId": "e81c7d2b-4e95-9b1e-842e-3fb9c8c1df38",
  "userId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38",
  "email": "user@example.com",
  "fullname": "John Doe",
  //...
  "accessToken": "ey7....",
  "userBucketToken": "e56d....",
  "sessionNeedsEmail2FA": true,
  "sessionNeedsMobile2FA": true,

}

Note on bucket tokens: The userBucketToken is for the external bucket service (used for general file uploads like documents and product images). User avatars do not use the external bucket service — they are uploaded via database buckets (dbBuckets) built into the auth service using the regular accessToken. See the Profile or Bucket Management sections for dbBucket avatar upload details.

Two-Factor Authentication (2FA): When the login response contains sessionNeedsEmail2FA: true or sessionNeedsMobile2FA: true, the session is not yet fully authorized. The accessToken is valid but all protected API calls will return 403 until 2FA is completed. Do not treat this login as successful — instead, store the accessToken, userId, and sessionId, and navigate the user to a 2FA verification page. The 2FA flow details are covered in the Verification Management prompt.

Error Responses


POST /logout — User Logout

Purpose: Terminates the current session and clears associated authentication tokens.

Behavior

Example

axios.post("/logout", {}, {
  headers: { "Authorization": "Bearer your-jwt-token" }
});

Notes

Success Response

{ "status": "OK", "message": "User logged out successfully" }

GET /currentuser — Current Session

Purpose Returns the currently authenticated user’s session.

Route Type sessionInfo

Authentication Requires a valid access token (header or cookie).

Request

No parameters.

Example

axios.get("/currentuser", {
  headers: { Authorization: "Bearer <jwt>" }
});

Success (200)

Returns the session object (identity, tenancy, token metadata):

{
  "sessionId": "9cf23fa8-07d4-4e7c-80a6-ec6d6ac96bb9",
  "userId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38",
  "email": "user@example.com",
  "fullname": "John Doe",
  "roleId": "user",
  "tenantId": "abc123",
  "accessToken": "jwt-token-string",
  "...": "..."
}

Note that the currentuser API returns a session object, so there is no id property, instead, the values for the user and session are exposed as userId and sessionId. The response is a mix of user and session information.

Errors

Notes

After you complete this step, please ensure you have not made the following common mistakes:

  1. The /currentuser API returns a mix of session and user data. There is no id property —use userId and sessionId.
  2. Note that any API call to the auth service should use the /auth-api prefix after the application’s base URL.

After this prompt, the user may give you new instructions to update your output or provide subsequent prompts about the project.


Verification Management

AUTEURLABB

FRONTEND GUIDE FOR AI CODING AGENTS - PART 3 - Verification Management

This document is a part of a REST API guide for the auteurlabb project. It is designed for AI agents that will generate frontend code to consume the project’s backend.

This document includes the verification processes for the autheitcation flow. Please read it carefully and implement all requirements described here.

The project has 1 auth service, 1 notification service, 1 BFF service, and 4 business services, plus other helper services such as bucket and realtime. In this document you will be informed only about the auth service.

Each service is a separate microservice application and listens for HTTP requests at different service URLs.

Services may be deployed to the preview server, staging server, or production server. Therefore, each service has 3 access URLs. The frontend application must support all deployment environments during development, and the user should be able to select the target API server on the home page.

Accessing the backend

Each backend service has its own URL for each deployment environment. Users may want to test the frontend in one of the three deployments—preview, staging, or production. Please ensure that the home page includes a deployment server selection option so that, as the frontend coding agent, you can set the base URL for all services.

For the auth service, the base URLs are:

Any request that requires login must include a valid token in the Bearer authorization header.

After User Registration

Frontend should also be aware of verification after any login attempt. The login request may return a 401 or 403 with the error codes that indicates the verification needs.

{
  //...
  "errCode": "EmailVerificationNeeded",
  // or
  "errCode": "MobileVerificationNeeded",
}

Email Verification

In the registration response, check the emailVerificationNeeded property in the response root. If it is true, start the email verification flow.

After the login process, if you receive an HTTP error and the response contains an errCode with the value EmailVerificationNeeded, start the email verification flow.

  1. Call the email verification start route of the backend (described below) with the user’s email. The backend will send a secret code to the provided email address. The backend can send the email if the architect has configured a real mail service or SMTP server. During development, the backend also returns the secret code to the frontend. You can read this code from the secretCode property of the response.
  2. The secret code in the email will be a 6-digit code. Provide an input page so the user can paste this code into the frontend application. Navigate to this input page after starting the verification process. If the secretCode is sent to the frontend for testing, display it on the input page so the user can copy and paste it.
  3. The start response includes a codeIndex property. Display its value on the input page so the user can match the index in the message with the one on the screen.
  4. When the user submits the code, complete the email verification using the complete route of the backend (described below) with the user’s email and the secret code.
  5. After a successful email verification response, please check the response object to have the property ‘mobileVerificationNeeded’ as true, if so navigate to the mobile verification flow as described below. If no mobile verification is needed then just navigate the login page.

Below are the start and complete routes for email verification. These are system routes and therefore are not versioned.

POST /verification-services/email-verification/start

Purpose: Starts email verification by generating and sending a secret code.

Parameter Type Required Description
email String Yes User’s email address to verify

Example Request

{ "email": "user@example.com" }

Success Response

{
  "status": "OK", 
  "codeIndex": 1,
  // timeStamp : Milliseconds since Jan 1, 1970, 00:00:00.000 GMT
  "timeStamp": 1784578660000,
  "date": "Mon Jul 20 2026 23:17:40 GMT+0300 (GMT+03:00)",
  // expireTime: in seconds
  "expireTime": 86400,
  "verificationType": "byLink",

  // in testMode
  "secretCode": "123456",
  "userId": "user-uuid"
}

⚠️ In production, secretCode is not returned — it is only sent via email.

Error Responses


POST /verification-services/email-verification/complete

Purpose: Completes verification using the received code.

Parameter Type Required Description
email String Yes User’s email
secretCode String Yes Verification code

Success Response

{
  "status": "OK", 
  "isVerified": true,
  "email": "user@email.com",
  // in testMode
  "userId": "user-uuid"
}

Error Responses


Mobile Verification

Mobile numbers must be in E.164 format (+ followed by country code and subscriber number, e.g. +905551234567). Use the PhoneInput component for mobile number inputs on verification pages.

In the registration response, check the mobileVerificationNeeded property in the response root. If it is true, start the mobile verification flow.

After the login process, if you receive a 403 error and the response contains an errCode with the value MobileVerificationNeeded, start the mobile verification flow.

  1. Call the mobile verification start route of the backend (described below) with the user’s email. The backend will send a secret code to the user’s mobile number. If a real texting service is configured, the backend sends the SMS. During development, the backend also returns the secret code to the frontend in the secretCode property.
  2. The secret code in the SMS will be a 6-digit code. Provide an input page so the user can paste this code. Navigate to this input page after starting the verification process. If the secretCode is returned for testing, display it on the input page for easy copy/paste.
  3. When the user submits the code, complete mobile verification using the complete route of the backend (described below) with the user’s email and the secret code.
  4. The start response includes a codeIndex property. Display its value on the input page so the user can match the index shown in the message with the one on the screen.
  5. After a successful mobile verification response, navigate to the login page.

Verification Order If both emailVerificationNeeded and mobileVerificationNeeded are true, handle both verification flows in order. First complete email verification, then mobile verification.

Below are the start and complete routes for mobile verification. These are system routes and therefore are not versioned.

POST /verification-services/mobile-verification/start

Parameter Type Required Description
email String Yes User’s email to locate mobile record

Success Response

{
  "status": "OK", 
  "codeIndex": 1,
  // timeStamp : Milliseconds since Jan 1, 1970, 00:00:00.000 GMT
  "timeStamp": 1784578660000,
  "date": "Mon Jul 20 2026 23:17:40 GMT+0300 (GMT+03:00)",
  // expireTime: in seconds
  "expireTime": 180,
  "verificationType": "byCode",

  // in testMode
  "secretCode": "123456",
  "userId": "user-uuid"
}

⚠️ secretCode is returned only in development.

Errors


POST /verification-services/mobile-verification/complete

Parameter Type Required Description
email String Yes Associated email
secretCode String Yes Code received via SMS

Success Response

{
  "status": "OK", 
  "isVerified": true,
  "mobile": "+1 333 ...",
  // in testMode
  "userId": "user-uuid"
}

Resetting Password

Users can reset their forgotten passwords without a login required, through email and mobile verification. To be able to start a password reset flow, users will click on the “Reset Password” link in the login page.

Since there are two verification methods, by email or by mobile, for password reset, when the reset password link is clicked, frontend should ask user if they want to make the verification through email of mobile. According to the users selection the frontend shoudl start the related flow as explaned below step by step.

Password Reset By Email Flow

  1. Call the password reset by email verification start route of the backend (described below) with the user’s email. The backend will send a secret code to the provided email address. The backend can send the email if the architect has configured a real mail service or SMTP server. During development, the backend also returns the secret code to the frontend. You can read this code from the secretCode property of the response.
  2. The secret code in the email will be a 6-digit code. Provide an input page so the user can paste this code into the frontend application. Navigate to this input page after starting the verification process. If the secretCode is sent to the frontend for testing, display it on the input page so the user can copy and paste it.
  3. The start response includes a codeIndex property. Display its value on the input page so the user can match the index in the message with the one on the screen.
  4. The input page should also include a double input area for the user to enter and confirm their new password.
  5. When the user submits the code and the new password, complete the password reset by email using the complete route of the backend (described below) with the user’s email , the secret code and new password.
  6. After a successful verification response, navigate to the login page.

Below are the start and complete routes for password reset by email verification. These are system routes and therefore are not versioned.

POST /verification-services/password-reset-by-email/start

Purpose:
Starts the password reset process by generating and sending a secret verification code.

Request Body

Parameter Type Required Description
email String Yes The email address of the user
{
  "email": "user@example.com"
}

Success Response

Returns secret code details (only in development environment) and confirmation that the verification step has been started.

{
  "userId": "user-uuid",
  "email": "user@example.com",
  "codeIndex": 1,
  "secretCode": "123456", 
  "timeStamp": 1765484354,
  "expireTime": 86400,
  "date": "2024-04-29T10:00:00.000Z",
  "verificationType": "byLink",
}

⚠️ In production, the secret code is only sent via email and not exposed in the API response.

Error Responses


POST /verification-services/password-reset-by-email/complete

Purpose:
Completes the password reset process by validating the secret code and updating the user’s password.

Request Body

Parameter Type Required Description
email String Yes The email address of the user
secretCode String Yes The code received via email
password String Yes The new password the user wants to set
{
  "email": "user@example.com",
  "secretCode": "123456",
  "password": "newSecurePassword123"
}

Success Response

{
  "userId": "user-uuid",
  "email": "user@example.com",
  "isVerified": true
}

Error Responses


Password Reset By Mobile Flow

  1. Call the password reset by mobile verification start route of the backend (described below) with the user’s email. The backend will send a secret code to the user’s mobile number. If a real texting service is configured, the backend sends the SMS. During development, the backend also returns the secret code to the frontend in the secretCode property.
  2. The secret code in the SMS will be a 6-digit code. Provide an input page so the user can paste this code. Navigate to this input page after starting the verification process. If the secretCode is returned for testing, display it on the input page for easy copy/paste.
  3. The start response includes a codeIndex property. Display its value on the input page so the user can match the index in the message with the one on the screen. Also display the half masked mobilenumber that comes in the response, to tell the user that their code is sent to this number.
  4. The input page should also include a double input area for the user to enter and confirm their new password.
  5. When the user submits the code, complete mobile verification using the complete route of the backend (described below) with the user’s email and the secret code.
  6. After a successful mobile verification response, navigate to the login page.

Below are the start and complete routes for password reset by mobile verification. These are system routes and therefore are not versioned.

POST /verification-services/password-reset-by-mobile/start

Purpose:
Initiates the mobile-based password reset by sending a verification code to the user’s mobile.

Request Body

Parameter Type Required Description
email String Yes The email of the user that resets the password
{
  "email": "user@user.com"
}

Success Response

Returns the verification context (code returned only in development):

{
  "status": "OK",
  "codeIndex": 1,
  timeStamp: 133241255,
  "mobile": "+905.....67",
  "secretCode": "123456", 
  "expireTime": 86400,
  "date": "2024-04-29T10:00:00.000Z",
  verificationType: "byLink"
}

⚠️ In production, the secretCode is not included in the response and is only sent via SMS.

Error Responses


POST /verification-services/password-reset-by-mobile/complete

Purpose:
Finalizes the password reset process by validating the received verification code and updating the user’s password.

Request Body

Parameter Type Required Description
email String Yes The email address of the user
secretCode String Yes The code received via SMS
password String Yes The new password to assign
{
  "email": "user@example.com",
  "secretCode": "123456",
  "password": "NewSecurePassword123!"
}

Success Response

{
  "userId": "user-uuid",
  "isVerified": true
}

Two-Factor Authentication (2FA)

This project has email and mobile two-factor authentication enabled. 2FA is different from email/mobile verification: verification proves ownership during registration (one-time), while 2FA runs on every login as an additional security layer.

How 2FA Works After Login

When a user logs in successfully, the login response includes accessToken, userId, sessionId, and all session data. However, when 2FA is active, the response also contains one or both of these flags:

When any of these flags are true, the session is NOT fully authorized. The accessToken is valid only for calling the 2FA verification endpoints. All other protected API calls will return 403 Forbidden with error code EmailTwoFactorNeeded or MobileTwoFactorNeeded until 2FA is completed.

2FA Frontend Flow

  1. After a successful login, check the response for sessionNeedsEmail2FA or sessionNeedsMobile2FA.
  2. If either is true, do not treat the user as authenticated. Store the accessToken, userId, and sessionId temporarily.
  3. Navigate the user to a 2FA verification page.
  4. On the 2FA page, immediately call the 2FA start endpoint (described below) with the userId and sessionId. This triggers sending the verification code to the user’s email or mobile.
  5. Display a 6-digit code input. If the response contains secretCode (test/development mode), display it on the page so the user can copy and paste it.
  6. The start response includes a codeIndex property. Display its value on the page so the user can match the index in the message with the one on the screen.
  7. When the user submits the code, call the 2FA complete endpoint with userId, sessionId, and secretCode.
  8. On success, the complete endpoint returns the updated session object with the 2FA flag cleared. Now set the user as fully authenticated and navigate to the main application page.
  9. Provide a “Resend Code” button with a 60-second cooldown to prevent spam.
  10. Provide a “Cancel” option that discards the partial session and returns the user to the login page.

2FA Type Selection

When both email and mobile 2FA are enabled, the login response may have both sessionNeedsEmail2FA: true and sessionNeedsMobile2FA: true. In this case, handle email 2FA first, then mobile 2FA — similar to the verification order for email and mobile verification.

Email 2FA Endpoints

POST /verification-services/email-2factor-verification/start

Purpose: Starts email-based 2FA by generating and sending a verification code to the user’s email.

Parameter Type Required Description
userId String Yes The user’s ID
sessionId String Yes The current session ID

Example Request

{
  "userId": "user-uuid",
  "sessionId": "session-uuid"
}

Success Response

{
  "status": "OK",
  "sessionId": "session-uuid",
  "userId": "user-uuid",
  "codeIndex": 1,
  "timeStamp": 1784578660000,
  "date": "Mon Jul 20 2026 23:17:40 GMT+0300",
  "expireTime": 86400,
  "verificationType": "byCode",

  // in testMode only
  "secretCode": "123456"
}

⚠️ In production, secretCode is not returned — it is only sent via email.

Error Responses


POST /verification-services/email-2factor-verification/complete

Purpose: Completes email 2FA by validating the code and clearing the session 2FA flag.

Parameter Type Required Description
userId String Yes The user’s ID
sessionId String Yes The session ID
secretCode String Yes Verification code from email

Success Response

Returns the updated session with sessionNeedsEmail2FA: false:

{
  "sessionId": "session-uuid",
  "userId": "user-uuid",
  "email": "user@example.com",
  "fullname": "John Doe",
  "roleId": "user",
  "sessionNeedsEmail2FA": false,
  "accessToken": "jwt-token",
  "...": "..."
}

Error Responses


Mobile 2FA Endpoints

Important: Mobile 2FA requires that the user has a verified mobile number. If the user’s mobile is not verified, the start endpoint will return a 403 error.

POST /verification-services/mobile-2factor-verification/start

Purpose: Starts mobile-based 2FA by generating and sending a verification code via SMS.

Parameter Type Required Description
userId String Yes The user’s ID
sessionId String Yes The current session ID

Example Request

{
  "userId": "user-uuid",
  "sessionId": "session-uuid"
}

Success Response

{
  "status": "OK",
  "sessionId": "session-uuid",
  "userId": "user-uuid",
  "codeIndex": 1,
  "timeStamp": 1784578660000,
  "date": "Mon Jul 20 2026 23:17:40 GMT+0300",
  "expireTime": 300,
  "verificationType": "byCode",

  // in testMode only
  "secretCode": "654321"
}

⚠️ In production, secretCode is not returned — it is only sent via SMS.

Error Responses


POST /verification-services/mobile-2factor-verification/complete

Purpose: Completes mobile 2FA by validating the code and clearing the session 2FA flag.

Parameter Type Required Description
userId String Yes The user’s ID
sessionId String Yes The session ID
secretCode String Yes Code received via SMS

Success Response

Returns the updated session with sessionNeedsMobile2FA: false:

{
  "sessionId": "session-uuid",
  "userId": "user-uuid",
  "mobile": "+15551234567",
  "fullname": "John Doe",
  "roleId": "user",
  "sessionNeedsMobile2FA": false,
  "accessToken": "jwt-token",
  "...": "..."
}

Error Responses


Important 2FA Notes

** Please dont forget to arrange the code to be able to navigate to the verification pages both after registrations and login attempts if verification is needed.**

After this prompt, the user may give you new instructions to update your first output or provide subsequent prompts about the project.


Profile Management

AUTEURLABB

FRONTEND GUIDE FOR AI CODING AGENTS - PART 4 - Profile Management

This document is a part of a REST API guide for the auteurlabb project. It is designed for AI agents that will generate frontend code to consume the project’s backend.

This document includes information and api descriptions about building a profile page in the frontend using the auth service profile api calls. Avatar images are stored in the auth service’s database buckets — no external bucket service is needed for avatars.

The project has 1 auth service, 1 notification service, 1 BFF service, and 4 business services, plus other helper services such as bucket and realtime. In this document you will use the auth service (including its database bucket endpoints for avatar uploads).

Each service is a separate microservice application and listens for HTTP requests at different service URLs.

Services may be deployed to the preview server, staging server, or production server. Therefore, each service has 3 access URLs. The frontend application must support all deployment environments during development, and the user should be able to select the target API server on the home page.

Accessing the backend

Each backend service has its own URL for each deployment environment. Users may want to test the frontend in one of the three deployments—preview, staging, or production. Please ensure that the register and login pages include a deployment server selection option so that, as the frontend coding agent, you can set the base URL for all services.

The base URL of the application in each environment is as follows:

For the auth service, service urls are as follows:

For each other service, the service URL will be given in the service sections.

Any request that requires login must include a valid token in the Bearer authorization header.

Avatar Storage (Database Buckets)

User avatars and tenant avatars are stored directly in the auth service database using database buckets (dbBuckets). This means avatar files are uploaded to and downloaded from the auth service itself — no external bucket service is needed.

The auth service provides these avatar buckets:

User Avatar Bucket

Upload: POST {authBaseUrl}/bucket/userAvatars/upload Download by ID: GET {authBaseUrl}/bucket/userAvatars/download/{fileId} Download by Key: GET {authBaseUrl}/bucket/userAvatars/download/key/{accessKey}

Upload example (multipart/form-data):

const formData = new FormData();
formData.append('file', croppedImageBlob, 'avatar.png');

const response = await fetch(`${authBaseUrl}/bucket/userAvatars/upload`, {
  method: 'POST',
  headers: {
    'Authorization': `Bearer ${accessToken}`,
  },
  body: formData,
});

const result = await response.json();
// result.file.id — the file ID (use for download URL)
// result.file.accessKey — 12-char key for public sharing
// result.file.fileName, result.file.mimeType, result.file.fileSize

After uploading, update the user’s avatar field with the download URL:

const avatarUrl = `${authBaseUrl}/bucket/userAvatars/download/${result.file.id}`;
// OR use the access key for a shorter, shareable URL:
const avatarUrl = `${authBaseUrl}/bucket/userAvatars/download/key/${result.file.accessKey}`;

await updateProfile({ avatar: avatarUrl });

Displaying avatars: Since read access is public, avatar URLs can be used directly in <img> tags without any authentication token:

<img src={user.avatar} alt="Avatar" />

Listing and Deleting Avatars

The auth service also provides metadata APIs for each bucket (auto-generated):

API Method Path Description
getUserAvatarsFile GET /v1/userAvatarsFiles/:id Get file metadata (no binary)
listUserAvatarsFiles GET /v1/userAvatarsFiles List files with filtering
deleteUserAvatarsFile DELETE /v1/userAvatarsFiles/:id Delete file and its data

Profile Page

Design a profile page to manage (view and edit) user information. The profile page should include an avatar upload component that uploads to the database bucket.

On the profile page, you will need 4 business APIs: getUser , updateProfile, updateUserPassword and archiveProfile. Do not rely on the /currentuser response for profile data, because it contains session information. The most recent user data is in the user database and should be accessed via the getUser business API.

The updateProfile, updateUserPassword and archiveProfile api can only be called by the users themselves. They are designed specific to the profile page.

Avatar upload workflow:

  1. User selects an image → crop with react-easy-crop (install it, do not implement your own)
  2. Convert cropped area to a Blob
  3. Upload to POST {authBaseUrl}/bucket/userAvatars/upload with the access token
  4. Get back the file metadata (id, accessKey)
  5. Construct the download URL: {authBaseUrl}/bucket/userAvatars/download/key/{accessKey}
  6. Call updateProfile({ avatar: downloadUrl }) to save it

Note that the user cannot change/update their email or roleId.

For password update you should make a separate block in the UI, so that user can enter old password, new password and confirm new password before calling the updateUserPassword.

Here are the 3 auth APIs—getUser , updateProfile and updateUserPassword— as follows: You can access these APIs through the auth service base URL, {appUrl}/auth-api.

Get User API

This api is used by admin roles or the users themselves to get the user profile information.

Rest Route

The getUser API REST controller can be triggered via the following route:

/v1/users/:userId

Rest Request Parameters

The getUser api has got 1 regular request parameter

Parameter Type Required Population
userId ID true request.params?.[“userId”]
userId : This id paremeter is used to query the required data object.

REST Request To access the api you can use the REST controller with the path GET /v1/users/:userId

  axios({
    method: 'GET',
    url: `/v1/users/${userId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "user",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"user": {
		"id": "ID",
		"email": "String",
		"password": "String",
		"fullname": "String",
		"avatar": "String",
		"roleId": "String",
		"emailVerified": "Boolean",
		"approvalStatus": "Enum",
		"approvalStatus_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Update Profile API

This route is used by users to update their profiles.

Rest Route

The updateProfile API REST controller can be triggered via the following route:

/v1/profile/:userId

Rest Request Parameters

The updateProfile api has got 4 regular request parameters

Parameter Type Required Population
userId ID true request.params?.[“userId”]
fullname String false request.body?.[“fullname”]
avatar String false request.body?.[“avatar”]
approvalStatus Enum false request.body?.[“approvalStatus”]
userId : This id paremeter is used to select the required data object that will be updated
fullname : A string value to represent the fullname of the user
avatar : The avatar url of the user. A random avatar will be generated if not provided
approvalStatus : Admin approval status for the user account (pending, approved, rejected).

REST Request To access the api you can use the REST controller with the path PATCH /v1/profile/:userId

  axios({
    method: 'PATCH',
    url: `/v1/profile/${userId}`,
    data: {
            fullname:"String",  
            avatar:"String",  
            approvalStatus:"Enum",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "user",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"user": {
		"id": "ID",
		"email": "String",
		"password": "String",
		"fullname": "String",
		"avatar": "String",
		"roleId": "String",
		"emailVerified": "Boolean",
		"approvalStatus": "Enum",
		"approvalStatus_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Update Userpassword API

This route is used to update the password of users in the profile page by users themselves

Rest Route

The updateUserPassword API REST controller can be triggered via the following route:

/v1/userpassword/:userId

Rest Request Parameters

The updateUserPassword api has got 3 regular request parameters

Parameter Type Required Population
userId ID true request.params?.[“userId”]
oldPassword String true request.body?.[“oldPassword”]
newPassword String true request.body?.[“newPassword”]
userId : This id paremeter is used to select the required data object that will be updated
oldPassword : The old password of the user that will be overridden bu the new one. Send for double check.
newPassword : The new password of the user to be updated

REST Request To access the api you can use the REST controller with the path PATCH /v1/userpassword/:userId

  axios({
    method: 'PATCH',
    url: `/v1/userpassword/${userId}`,
    data: {
            oldPassword:"String",  
            newPassword:"String",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "user",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"user": {
		"id": "ID",
		"email": "String",
		"password": "String",
		"fullname": "String",
		"avatar": "String",
		"roleId": "String",
		"emailVerified": "Boolean",
		"approvalStatus": "Enum",
		"approvalStatus_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Archiving A Profile

A user may want to archive their profile. So the profile page should include an archive section for the users to archive their accounts. When an account is archived, it is marked as archived and an aarchiveDate is atteched to the profile. All user data is kept in the database for 1 month after user archived. If user tries to login or register with the same email, the account will be activated again. But if no login or register occures in 1 month after archiving, the profile and its related data will be deleted permanenetly. So in the profile page,

  1. The arcihve options should be accepted after user writes a text like (“ARCHİVE MY ACCOUNT”) to a confirmation dialog, so that frontend UX can ensure this is not an unconscious request.
  2. The user should be warned about the process, that his account will be available for a restore for 1 month.

The archive api, can only be called by the users themselves and its used as follows.

Archive Profile API

This api is used by users to archive their profiles.

Rest Route

The archiveProfile API REST controller can be triggered via the following route:

/v1/archiveprofile/:userId

Rest Request Parameters

The archiveProfile api has got 1 regular request parameter

Parameter Type Required Population
userId ID true request.params?.[“userId”]
userId : This id paremeter is used to select the required data object that will be deleted

REST Request To access the api you can use the REST controller with the path DELETE /v1/archiveprofile/:userId

  axios({
    method: 'DELETE',
    url: `/v1/archiveprofile/${userId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "user",
	"method": "DELETE",
	"action": "delete",
	"appVersion": "Version",
	"rowCount": 1,
	"user": {
		"id": "ID",
		"email": "String",
		"password": "String",
		"fullname": "String",
		"avatar": "String",
		"roleId": "String",
		"emailVerified": "Boolean",
		"approvalStatus": "Enum",
		"approvalStatus_idx": "Integer",
		"isActive": false,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

After you complete this step, please ensure you have not made the following common mistakes:

  1. Avatar uploads go to the auth service’s database bucket endpoints (/bucket/userAvatars/upload), not to an external bucket service. Use the same accessToken (Bearer header) for both auth APIs and avatar bucket uploads — no bucket-specific tokens are needed.
  2. Note that any api call to the application backend is based on a service base url, in this prompt all auth apis (including avatar bucket endpoints) should be called by the auth service base url.
  3. On the profile page, fetch the latest user data from the service using getUser. The /currentuser API is session-stored data; the latest data is in the database.
  4. When you upload the avatar image on the profile page, use the returned download URL as the user’s avatar property and update the user record when the Save button is clicked.

After this prompt, the user may give you new instructions to update your first output or provide subsequent prompts about the project.


User Management

AUTEURLABB

FRONTEND GUIDE FOR AI CODING AGENTS - PART 5 - User Management

This document is the 2nd part of a REST API guide for the auteurlabb project. It is designed for AI agents that will generate frontend code to consume the project’s backend.

This document provides extensive instruction for administrative user management.

Service Access

User management is handled through auth service again.

Auth service may be deployed to the preview server, staging server, or production server. Therefore,it has 3 access URLs. The frontend application must support all deployment environments during development, and the user should be able to select the target API server on the login page (already handled in first part.).

For the auth service, the base URLs are:

Please note that any feature in this document is open to admins only. When the user logins, the response includes a roleId field.

This roleId should one of these following admin roles. superAdmin, admin,

Scope

Auth service provides following feature for user management in auteurlabb application.

These features are already handled in the previous part.

  1. User Registration
  2. User Authentication
  3. Password Reset
  4. Email (and/or) Mobile Verification
  5. Profile Management

These features will be handled in this part.

API Structure

Object Structure of a Successful Response

When the service processes requests successfully, it wraps the requested resource(s) within a JSON envelope. This envelope includes the data and essential metadata such as configuration details and pagination information, providing context to the client.

HTTP Status Codes:

Success Response Format:

For successful operations, the response includes a "status": "OK" property, signaling that the request executed successfully. The structure of a successful response is outlined below:

{
  "status":"OK",
  "statusCode": 200,   
  "elapsedMs":126,
  "ssoTime":120,
  "source": "db",
  "cacheKey": "hexCode",
  "userId": "ID",
  "sessionId": "ID",
  "requestId": "ID",
  "dataName":"products",
  "method":"GET",
  "action":"list",
  "appVersion":"Version",
  "rowCount":3,
  "products":[{},{},{}],
  "paging": {
    "pageNumber":1, 
    "pageRowCount":25, 
    "totalRowCount":3,
    "pageCount":1
  },
  "filters": [],
  "uiPermissions": []
}

Additional Data

Each API may include additional data besides the main data object, depending on the business logic of the API. These will be provided in each API’s response signature.

Error Response

If a request encounters an issue—whether due to a logical fault or a technical problem—the service responds with a standardized JSON error structure. The HTTP status code indicates the nature of the error, using commonly recognized codes for clarity:

Each error response is structured to provide meaningful insight into the problem, assisting in efficient diagnosis and resolution.

{
  "result": "ERR",
  "status": 400,
  "message": "errMsg_organizationIdisNotAValidID",
  "errCode": 400,
  "date": "2024-03-19T12:13:54.124Z",
  "detail": "String"
}

User Management

User management will be one of the main parts of the administrative manageemnts, so there will be a minimal but fancy users page in the admin dashboard.

User Roles

Along with the default roles, this project also configured to have the following roles: filmmaker studio investor normalUser

The roles object is a hardcoded object in the generated code, and it contains the following roles:

{
  "superAdmin": "'superAdmin'",
  "admin": "'admin'",
  "user": "'user'",
  "filmmaker": "'filmmaker'",
  "studio": "'studio'",
  "investor": "'investor'",
  "normalUser": "'normalUser'"
}

Each user may have only one role, and it is given in /login , /currentuser or /users/:userId response as follows

{
  // ...
  "roleId":"superAdmin",
  // ...
}

Listing Users

You can list users using the listUsers api.

List Users API

The list of users is filtered by the tenantId.

Rest Route

The listUsers API REST controller can be triggered via the following route:

/v1/users

Rest Request Parameters

Filter Parameters

The listUsers api supports 3 optional filter parameters for filtering list results:

email (String): A string value to represent the user’s email.

fullname (String): A string value to represent the fullname of the user

roleId (String): A string value to represent the roleId of the user.

REST Request To access the api you can use the REST controller with the path GET /v1/users

  axios({
    method: 'GET',
    url: '/v1/users',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section above)
        // email: '<value>' // Filter by email
        // fullname: '<value>' // Filter by fullname
        // roleId: '<value>' // Filter by roleId
            }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "users",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"users": [
		{
			"id": "ID",
			"email": "String",
			"password": "String",
			"fullname": "String",
			"avatar": "String",
			"roleId": "String",
			"emailVerified": "Boolean",
			"approvalStatus": "Enum",
			"approvalStatus_idx": "Integer",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID"
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Searching Users

You may search users with their full names, emails. The search is done in elasticsearch index of the user table so a fast response is provided by the backend. You can send search request on each character update in the search box but start searching after 3 chars. The keyword parameter that is used in the business logic of the api, is read from the keyword query parameter.

eg: GET /v1/searchusers?keyword=Joe

When the user deletes the search keyword, use the listUsers api to get the full list again.

Search Users API

The list of users is filtered by the tenantId.

Rest Route

The searchUsers API REST controller can be triggered via the following route:

/v1/searchusers

Rest Request Parameters

The searchUsers api has got 1 regular request parameter

Parameter Type Required Population
keyword String true request.query?.[“keyword”]
keyword :

Filter Parameters

The searchUsers api supports 1 optional filter parameter for filtering list results:

roleId (String): A string value to represent the roleId of the user.

REST Request To access the api you can use the REST controller with the path GET /v1/searchusers

  axios({
    method: 'GET',
    url: '/v1/searchusers',
    data: {
    
    },
    params: {
             keyword:'"String"',  
    
        // Filter parameters (see Filter Parameters section above)
        // roleId: '<value>' // Filter by roleId
            }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "users",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"users": [
		{
			"id": "ID",
			"email": "String",
			"password": "String",
			"fullname": "String",
			"avatar": "String",
			"roleId": "String",
			"emailVerified": "Boolean",
			"approvalStatus": "Enum",
			"approvalStatus_idx": "Integer",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID"
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Pagination

When you list the users please use pagination. To be able to use pagination you should provide a pageNumber paramater in the query. The default row count for one page is 25, add an option for user to change it to 50 or 100. You can provide this value to the api through the pageRowCount parameter;

GET /users?pageNumber=1&pageRowCount=50

Creating Users

The user management console in the admin dashboard should provide UX components for user creating by admins. When creating users, it should also be possible to upload user avatar. Note that when creating, updating users, admins can not set emailVerified as true, since it is a logical mechanism and should be verified only through verification processes.

Create User API

This api is used by admin roles to create a new user manually from admin panels

Rest Route

The createUser API REST controller can be triggered via the following route:

/v1/users

Rest Request Parameters

The createUser api has got 4 regular request parameters

Parameter Type Required Population
avatar String false request.body?.[“avatar”]
email String true request.body?.[“email”]
password String true request.body?.[“password”]
fullname String true request.body?.[“fullname”]
avatar : The avatar url of the user. If not sent, a default random one will be generated.
email : A string value to represent the user’s email.
password : A string value to represent the user’s password. It will be stored as hashed.
fullname : A string value to represent the fullname of the user

REST Request To access the api you can use the REST controller with the path POST /v1/users

  axios({
    method: 'POST',
    url: '/v1/users',
    data: {
            avatar:"String",  
            email:"String",  
            password:"String",  
            fullname:"String",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "user",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"user": {
		"id": "ID",
		"email": "String",
		"password": "String",
		"fullname": "String",
		"avatar": "String",
		"roleId": "String",
		"emailVerified": "Boolean",
		"approvalStatus": "Enum",
		"approvalStatus_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Avatar Upload

Avatars are stored in the auth service’s database bucket — no external bucket service needed. Upload the avatar image to the auth service’s userAvatars bucket endpoint:

POST {authBaseUrl}/bucket/userAvatars/upload

Use the regular access token (Bearer header) for authentication — the same token used for all other API calls. The upload body is multipart/form-data with a file field.

After upload, the response returns file metadata including id and accessKey. Construct a public download URL and save it in the user’s avatar field:

const avatarUrl = `${authBaseUrl}/bucket/userAvatars/download/key/${result.file.accessKey}`;
await updateUser(userId, { avatar: avatarUrl });

Since the userAvatars bucket has public read access, avatar URLs work directly in <img> tags without auth.

Before the avatar upload, use the react-easy-crop lib for zoom, pan and crop. This component is also used in the profile page — reuse the existing code.

Updating Users

User update is possible by updateUserapi. However since this update api is also called by teh user themselves it is lmited with name and avatar change (or any other user related property). For roleId and password updates seperate apis are used. So arrange the user update UI as to update the user info, as to set roleId and as to update password.

Update User API

This route is used by admins to update user profiles.

Rest Route

The updateUser API REST controller can be triggered via the following route:

/v1/users/:userId

Rest Request Parameters

The updateUser api has got 4 regular request parameters

Parameter Type Required Population
userId ID true request.params?.[“userId”]
fullname String false request.body?.[“fullname”]
avatar String false request.body?.[“avatar”]
approvalStatus Enum false request.body?.[“approvalStatus”]
userId : This id paremeter is used to select the required data object that will be updated
fullname : A string value to represent the fullname of the user
avatar : The avatar url of the user. A random avatar will be generated if not provided
approvalStatus : Admin approval status for the user account (pending, approved, rejected).

REST Request To access the api you can use the REST controller with the path PATCH /v1/users/:userId

  axios({
    method: 'PATCH',
    url: `/v1/users/${userId}`,
    data: {
            fullname:"String",  
            avatar:"String",  
            approvalStatus:"Enum",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "user",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"user": {
		"id": "ID",
		"email": "String",
		"password": "String",
		"fullname": "String",
		"avatar": "String",
		"roleId": "String",
		"emailVerified": "Boolean",
		"approvalStatus": "Enum",
		"approvalStatus_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

For role updates there are some rules.

  1. Superadmin role can not be unassigned even by superadmin.
  2. Admin roles can be assgined or unassgined only by superadmin.
  3. All other roles can be assigned and unassgined by admins and superadmin.

For password updates there are some rules.

  1. Superadmin and admin passwords can be updated only by superadmin.
  2. Admins can update only non-admin passwords.

Update Userrole API

This route is used by admin roles to update the user role.The default role is user when a user is registered. A user’s role can be updated by superAdmin or admin

Rest Route

The updateUserRole API REST controller can be triggered via the following route:

/v1/userrole/:userId

Rest Request Parameters

The updateUserRole api has got 2 regular request parameters

Parameter Type Required Population
userId ID true request.params?.[“userId”]
roleId String true request.body?.[“roleId”]
userId : This id paremeter is used to select the required data object that will be updated
roleId : The new roleId of the user to be updated

REST Request To access the api you can use the REST controller with the path PATCH /v1/userrole/:userId

  axios({
    method: 'PATCH',
    url: `/v1/userrole/${userId}`,
    data: {
            roleId:"String",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "user",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"user": {
		"id": "ID",
		"email": "String",
		"password": "String",
		"fullname": "String",
		"avatar": "String",
		"roleId": "String",
		"emailVerified": "Boolean",
		"approvalStatus": "Enum",
		"approvalStatus_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Update Userpasswordbyadmin API

This route is used to change any user password by admins only. Superadmin can chnage all passwords, admins can change only nonadmin passwords

Rest Route

The updateUserPasswordByAdmin API REST controller can be triggered via the following route:

/v1/userpasswordbyadmin/:userId

Rest Request Parameters

The updateUserPasswordByAdmin api has got 2 regular request parameters

Parameter Type Required Population
userId ID true request.params?.[“userId”]
password String true request.body?.[“password”]
userId : This id paremeter is used to select the required data object that will be updated
password : The new password of the user to be updated

REST Request To access the api you can use the REST controller with the path PATCH /v1/userpasswordbyadmin/:userId

  axios({
    method: 'PATCH',
    url: `/v1/userpasswordbyadmin/${userId}`,
    data: {
            password:"String",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "user",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"user": {
		"id": "ID",
		"email": "String",
		"password": "String",
		"fullname": "String",
		"avatar": "String",
		"roleId": "String",
		"emailVerified": "Boolean",
		"approvalStatus": "Enum",
		"approvalStatus_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Deleting Users

Deleting users is possible in certain conditions.

  1. SuperAdmin can not be deleted.
  2. Admins can be deleted by only superadmin.
  3. Users can be deleted by admins or superadmin.

Delete User API

This api is used by admins to delete user profiles.

Rest Route

The deleteUser API REST controller can be triggered via the following route:

/v1/users/:userId

Rest Request Parameters

The deleteUser api has got 1 regular request parameter

Parameter Type Required Population
userId ID true request.params?.[“userId”]
userId : This id paremeter is used to select the required data object that will be deleted

REST Request To access the api you can use the REST controller with the path DELETE /v1/users/:userId

  axios({
    method: 'DELETE',
    url: `/v1/users/${userId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "user",
	"method": "DELETE",
	"action": "delete",
	"appVersion": "Version",
	"rowCount": 1,
	"user": {
		"id": "ID",
		"email": "String",
		"password": "String",
		"fullname": "String",
		"avatar": "String",
		"roleId": "String",
		"emailVerified": "Boolean",
		"approvalStatus": "Enum",
		"approvalStatus_idx": "Integer",
		"isActive": false,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

When you list user group members, a user object will also be inserted in each userGroupMember object, with fullname, avatar, email.

Avatar Storage (Database Buckets)

(This information is also covered in the Profile prompt.)

Avatars are stored in the auth service’s database buckets — uploaded to and downloaded from the auth service directly using the regular access token.

User Avatar Bucket:

When uploading an avatar (for user creation or update), send the image to the bucket, get back the accessKey, construct the download URL, and store it in the user’s avatar field via the update API.

After this prompt, the user may give you new instructions to update the output of this prompt or provide subsequent prompts about the project.


MCP BFF Integration

AUTEURLABB

FRONTEND GUIDE FOR AI CODING AGENTS - PART 6 - MCP BFF Integration

This document is a part of a REST API guide for the auteurlabb project. It is designed for AI agents that will generate frontend code to consume the project’s backend.

This document provides comprehensive instructions for integrating the MCP BFF (Model Context Protocol - Backend for Frontend) service into the frontend application. The MCP BFF is the central gateway between the frontend AI chat and all backend services.


MCP BFF Architecture Overview

The Auteurlabb application uses an MCP BFF service that aggregates multiple backend MCP servers into a single frontend-facing API. Instead of the frontend connecting to each service’s MCP endpoint directly, it communicates exclusively through the MCP BFF.

┌────────────┐     ┌───────────┐     ┌─────────────────┐
│  Frontend   │────▶│  MCP BFF  │────▶│  Auth Service    │
│  (Chat UI)  │     │  :3005    │────▶│  Business Svc 1  │
│             │◀────│           │────▶│  Business Svc N  │
└────────────┘ SSE └───────────┘     └─────────────────┘

Key Responsibilities

MCP BFF Service URLs

For the MCP BFF service, the base URLs are:

All endpoints below are relative to the MCP BFF base URL.


Authentication

All MCP BFF endpoints require authentication. The user’s access token (obtained from the Auth service login) must be included in every request:

const headers = {
  'Content-Type': 'application/json',
  'Authorization': `Bearer ${accessToken}`,
};

Chat API (AI Interaction)

The chat API is the primary interface for AI-powered conversations. It supports both regular HTTP responses and SSE streaming for real-time output.

POST /api/chat — Regular Chat

Send a message and receive the complete AI response.

const response = await fetch(`${mcpBffUrl}/api/chat`, {
  method: 'POST',
  headers,
  body: JSON.stringify({
    message: "Show me all orders from last week",
    conversationId: "optional-conversation-id",  // for conversation context
    context: {}  // additional context
  }),
});

POST /api/chat/stream — SSE Streaming Chat (Recommended)

Stream the AI response in real-time using Server-Sent Events (SSE). This is the recommended approach for chat UIs as it provides immediate feedback while the AI is thinking, calling tools, and generating text.

Request:

const response = await fetch(`${mcpBffUrl}/api/chat/stream`, {
  method: 'POST',
  headers,
  body: JSON.stringify({
    message: "Create a new product called Widget",
    conversationId: conversationId,       // optional, auto-generated if omitted
    disabledServices: [],                 // optional, service names to exclude
  }),
});

Response: The server responds with Content-Type: text/event-stream. Each SSE frame follows the standard format:

event: <eventType>\n
data: <JSON>\n
\n

SSE Event Types

The streaming endpoint emits the following event types in order:

Event When Data Shape
start First event, once per stream { conversationId, provider, aliasMapSummary }
text AI text token streamed (many per response) { content }
tool_start AI decided to call a tool { tool }
tool_executing Tool invocation started with resolved args { tool, args }
tool_result Tool execution completed { tool, result, success, error? }check for __frontendAction
error Unrecoverable error { message }
done Last event, once per stream { conversationId, toolCalls, processingTime, aliasMapSummary }

SSE Event Data Reference

start — Always the first event. Use conversationId for subsequent requests in the same conversation.

{
  "conversationId": "1d143df6-29fd-49f6-823b-524b8b3b4453",
  "provider": "anthropic",
  "aliasMapSummary": { "enabled": true, "count": 0, "samples": [] }
}

text — Streamed token-by-token as the AI generates its response. Concatenate content fields to build the full markdown message.

{ "content": "Here" }
{ "content": "'s your" }
{ "content": " current session info" }

tool_start — The AI decided to call a tool. Use this to show a loading/spinner UI for the tool.

{ "tool": "currentuser" }

tool_executing — Tool is now executing with these arguments. Use this to display what the tool is doing.

{ "tool": "currentuser", "args": { "organizationCodename": "babil" } }

tool_result — Tool finished. Check success to determine if it succeeded. The result field contains the MCP tool response envelope.

{
  "tool": "currentuser",
  "result": {
    "success": true,
    "service": "auth",
    "tool": "currentuser",
    "result": {
      "content": [{ "type": "text", "text": "{...JSON...}" }]
    }
  },
  "success": true
}

On failure, success is false and an error string is present:

{
  "tool": "listProducts",
  "error": "Connection refused",
  "success": false
}

done — Always the last event. Contains a summary of all tool calls made and total processing time in milliseconds.

{
  "conversationId": "1d143df6-29fd-49f6-823b-524b8b3b4453",
  "toolCalls": [
    { "tool": "currentuser", "result": { "success": true, "..." : "..." } }
  ],
  "processingTime": 10026,
  "aliasMapSummary": {
    "enabled": true,
    "count": 6,
    "samples": [{ "alias": "user_admin_admin_com" }, { "alias": "tenant_admin_admin_com" }]
  }
}

error — Sent when an unrecoverable error occurs (e.g., AI service unavailable). The stream ends after this event.

{ "message": "AI service not configured. Please configure OPENAI_API_KEY or ANTHROPIC_API_KEY in environment variables" }

SSE Event Lifecycle

A typical conversation stream follows this lifecycle:

start
├── text (repeated)              ← AI's initial text tokens
├── tool_start                   ← AI decides to call a tool
├── tool_executing               ← tool running with resolved args
├── tool_result                  ← tool finished
├── text (repeated)              ← AI continues writing after tool result
├── tool_start → tool_executing → tool_result   ← may repeat
├── text (repeated)              ← AI's final text tokens
done

Multiple tool calls can happen in a single stream. The AI interleaves text and tool calls — text before tools (explanation), tools in the middle (data retrieval), and text after tools (formatted response using the tool results).

Inline Segment Rendering (Critical UX Pattern)

Tool cards MUST be rendered inline inside the assistant message bubble, at the exact position where they occur in the stream — not grouped at the top, not grouped at the bottom, and not outside the bubble.

The assistant message is an ordered list of segments: text segments and tool segments, interleaved in the order they arrive. Each segment appears inside the same message bubble, in sequence:

┌─────────────────────────────────────────────────┐
│  [Rendered Markdown — text before tool call]     │
│                                                  │
│  ┌─ Tool Card ─────────────────────────────────┐ │
│  │ 🔧 currentuser                    ✓ success │ │
│  │ args: { organizationCodename: "babil" }     │ │
│  └─────────────────────────────────────────────┘ │
│                                                  │
│  [Rendered Markdown — text after tool call]       │
│                                                  │
│  ┌─ Tool Card ─────────────────────────────────┐ │
│  │ 🔧 listProducts                  ✓ success  │ │
│  └─────────────────────────────────────────────┘ │
│                                                  │
│  [Rendered Markdown — final text]                │
└─────────────────────────────────────────────────┘

To achieve this, maintain an ordered segments array. Each segment is either { type: 'text', content: string } or { type: 'tool', ... }. When SSE events arrive:

  1. text — Append to the last segment if it is a text segment; otherwise push a new text segment.
  2. tool_start — Push a new tool segment (status: running). This “cuts” the current text segment — any further text events after the tool completes will start a new text segment.
  3. tool_executing — Update the current tool segment with args.
  4. tool_result — Update the current tool segment with result, success, error. Check for __frontendAction.
  5. After tool_result, the next text event creates a new text segment (the AI is now responding after reviewing the tool result).

Render the message bubble by mapping over the segments array in order, rendering each text segment as markdown and each tool segment as a collapsible tool card.

Parsing SSE Events (Frontend Implementation)

Use the fetch API with a streaming reader. SSE frames can arrive split across chunks, so buffer partial lines:

async function streamChat(mcpBffUrl, headers, message, conversationId, onEvent) {
  const response = await fetch(`${mcpBffUrl}/api/chat/stream`, {
    method: 'POST',
    headers,
    body: JSON.stringify({ message, conversationId }),
  });

  const reader = response.body.getReader();
  const decoder = new TextDecoder();
  let buffer = '';

  while (true) {
    const { done, value } = await reader.read();
    if (done) break;

    buffer += decoder.decode(value, { stream: true });
    const parts = buffer.split('\n\n');
    buffer = parts.pop(); // keep incomplete frame in buffer

    for (const part of parts) {
      let eventType = 'message';
      let dataStr = '';

      for (const line of part.split('\n')) {
        if (line.startsWith('event: ')) {
          eventType = line.slice(7).trim();
        } else if (line.startsWith('data: ')) {
          dataStr += line.slice(6);
        }
      }

      if (dataStr) {
        try {
          const data = JSON.parse(dataStr);
          onEvent(eventType, data);
        } catch (e) {
          console.warn('Failed to parse SSE data:', dataStr);
        }
      }
    }
  }
}

Building the Segments Array (React Example)

// segments: Array<{ type: 'text', content: string } | { type: 'tool', tool, args?, result?, success?, error?, status }>
let segments = [];

streamChat(mcpBffUrl, headers, userMessage, conversationId, (event, data) => {
  switch (event) {
    case 'start':
      conversationId = data.conversationId;
      segments = [];
      break;

    case 'text': {
      const last = segments[segments.length - 1];
      if (last && last.type === 'text') {
        last.content += data.content;        // append to current text segment
      } else {
        segments.push({ type: 'text', content: data.content }); // new text segment
      }
      rerenderBubble(segments);
      break;
    }

    case 'tool_start':
      // push a new tool segment — this "cuts" the text flow
      segments.push({ type: 'tool', tool: data.tool, status: 'running' });
      rerenderBubble(segments);
      break;

    case 'tool_executing': {
      const toolSeg = findLastToolSegment(segments, data.tool);
      if (toolSeg) toolSeg.args = data.args;
      rerenderBubble(segments);
      break;
    }

    case 'tool_result': {
      const toolSeg = findLastToolSegment(segments, data.tool);
      if (toolSeg) {
        toolSeg.status = data.success ? 'complete' : 'error';
        toolSeg.result = data.result;
        toolSeg.error = data.error;
        toolSeg.success = data.success;
        // Check for frontend action (QR code, data view, payment, secret)
        toolSeg.frontendAction = extractFrontendAction(data.result);
      }
      rerenderBubble(segments);
      break;
    }

    case 'error':
      segments.push({ type: 'text', content: `**Error:** ${data.message}` });
      rerenderBubble(segments);
      break;

    case 'done':
      // Store final metadata (processingTime, aliasMapSummary) for the message
      finalizeMessage(segments, data);
      break;
  }
});

function findLastToolSegment(segments, toolName) {
  for (let i = segments.length - 1; i >= 0; i--) {
    if (segments[i].type === 'tool' && segments[i].tool === toolName) return segments[i];
  }
  return null;
}

Rendering the Message Bubble

Render each segment in order inside a single assistant message bubble:

function AssistantMessageBubble({ segments }) {
  return (
    <div className="assistant-bubble">
      {segments.map((segment, i) => {
        if (segment.type === 'text') {
          return <MarkdownRenderer key={i} content={segment.content} />;
        }
        if (segment.type === 'tool') {
          if (segment.frontendAction) {
            return <ActionCard key={i} action={segment.frontendAction} />;
          }
          return <ToolCard key={i} segment={segment} />;
        }
        return null;
      })}
    </div>
  );
}

function ToolCard({ segment }) {
  const isRunning = segment.status === 'running';
  const isError = segment.status === 'error';

  return (
    <div className={`tool-card ${segment.status}`}>
      <div className="tool-header">
        {isRunning && <Spinner size="sm" />}
        <span className="tool-name">{segment.tool}</span>
        {!isRunning && (isError ? <ErrorIcon /> : <CheckIcon />)}
      </div>
      {segment.args && (
        <CollapsibleSection label="Arguments">
          <pre>{JSON.stringify(segment.args, null, 2)}</pre>
        </CollapsibleSection>
      )}
      {segment.result && (
        <CollapsibleSection label="Result" defaultCollapsed>
          <pre>{JSON.stringify(segment.result, null, 2)}</pre>
        </CollapsibleSection>
      )}
      {segment.error && <div className="tool-error">{segment.error}</div>}
    </div>
  );
}

The tool card should be compact by default (just tool name + status icon) with collapsible sections for args and result, so it doesn’t dominate the reading flow. While a tool is running (status: 'running'), show a spinner. When complete, show a check or error icon.

Handling __frontendAction in Tool Results

When the AI calls certain tools (e.g., QR code, data view, payment, secret reveal), the tool result contains a __frontendAction object. This signals the frontend to render a special UI component inline in the bubble at the tool segment’s position instead of the default collapsible ToolCard. This is already handled in the segments code above — when segment.frontendAction is present, render an ActionCard instead of a ToolCard.

The extractFrontendAction helper unwraps the action from various MCP response formats:

function extractFrontendAction(result) {
  if (!result) return null;
  if (result.__frontendAction) return result.__frontendAction;
  
  // Unwrap MCP wrapper format: result → result.result → content[].text → JSON
  let data = result;
  if (result?.result?.content) data = result.result;
  
  if (data?.content && Array.isArray(data.content)) {
    const textContent = data.content.find(c => c.type === 'text');
    if (textContent?.text) {
      try {
        const parsed = JSON.parse(textContent.text);
        if (parsed?.__frontendAction) return parsed.__frontendAction;
      } catch { /* not JSON */ }
    }
  }
  return null;
}

Frontend Action Types

Action Type Component Description
qrcode QrCodeActionCard Renders any string value as a QR code card
dataView DataViewActionCard Fetches a Business API route and renders a grid or gallery
payment PaymentActionCard “Pay Now” button that opens Stripe checkout modal

QR Code Action (type: "qrcode")

Triggered by the showQrCode MCP tool. Renders a QR code card from any string value.

{
  "__frontendAction": {
    "type": "qrcode",
    "value": "https://example.com/invite/ABC123",
    "title": "Invite Link",
    "subtitle": "Scan to open"
  }
}

Data View Action (type: "dataView")

Triggered by showBusinessApiListInFrontEnd or showBusinessApiGalleryInFrontEnd. Frontend calls the provided Business API route using the user’s bearer token, then renders:

{
  "__frontendAction": {
    "type": "dataView",
    "viewType": "grid",
    "title": "Recent Orders",
    "serviceName": "commerce",
    "apiName": "listOrders",
    "routePath": "/v1/listorders",
    "httpMethod": "GET",
    "queryParams": { "pageNo": 1, "pageRowCount": 10 },
    "columns": [
      { "field": "id", "label": "Order ID" },
      { "field": "orderAmount", "label": "Amount", "format": "currency" }
    ]
  }
}

Payment Action (type: "payment")

Triggered by the initiatePayment MCP tool. Renders a payment card with amount and a “Pay Now” button.

{
  "__frontendAction": {
    "type": "payment",
    "orderId": "uuid",
    "orderType": "order",
    "serviceName": "commerce",
    "amount": 99.99,
    "currency": "USD",
    "description": "Order #abc123"
  }
}

Conversation Management

// List user's conversations
GET /api/chat/conversations

// Get conversation history
GET /api/chat/conversations/:conversationId

// Delete a conversation
DELETE /api/chat/conversations/:conversationId

MCP Tool Discovery & Direct Invocation

The MCP BFF exposes endpoints for discovering and directly calling MCP tools (useful for debugging or building custom UIs).

GET /api/tools — List All Tools

const response = await fetch(`${mcpBffUrl}/api/tools`, { headers });
const { tools, count } = await response.json();
// tools: [{ name, description, inputSchema, service }, ...]

GET /api/tools/service/:serviceName — List Service Tools

const response = await fetch(`${mcpBffUrl}/api/tools/service/commerce`, { headers });
const { tools } = await response.json();

POST /api/tools/call — Call a Tool Directly

const response = await fetch(`${mcpBffUrl}/api/tools/call`, {
  method: 'POST',
  headers,
  body: JSON.stringify({
    toolName: "listProducts",
    args: { page: 1, limit: 10 },
  }),
});
const result = await response.json();

GET /api/tools/status — Connection Status

const status = await fetch(`${mcpBffUrl}/api/tools/status`, { headers });
// Returns health of each MCP service connection

POST /api/tools/refresh — Reconnect Services

await fetch(`${mcpBffUrl}/api/tools/refresh`, { method: 'POST', headers });
// Reconnects to all MCP services and refreshes the tool registry

Elasticsearch API

The MCP BFF provides direct access to Elasticsearch for searching, filtering, and aggregating data across all project indices.

All Elasticsearch endpoints are under /api/elastic.

GET /api/elastic/allIndices — List Project Indices

Returns all Elasticsearch indices belonging to this project (prefixed with auteurlabb_).

const indices = await fetch(`${mcpBffUrl}/api/elastic/allIndices`, { headers });
// ["auteurlabb_products", "auteurlabb_orders", ...]

POST /api/elastic/:indexName/rawsearch — Raw Elasticsearch Query

Execute a raw Elasticsearch query on a specific index.

const response = await fetch(`${mcpBffUrl}/api/elastic/products/rawsearch`, {
  method: 'POST',
  headers,
  body: JSON.stringify({
    query: {
      bool: {
        must: [
          { match: { status: "active" } },
          { range: { price: { gte: 10, lte: 100 } } }
        ]
      }
    },
    size: 20,
    from: 0,
    sort: [{ createdAt: "desc" }]
  }),
});
const { total, hits, aggregations, took } = await response.json();
// hits: [{ _id, _index, _score, _source: { ...document... } }, ...]

Note: The index name is automatically prefixed with auteurlabb_ if not already prefixed.

POST /api/elastic/:indexName/search — Simplified Search

A higher-level search API with built-in support for filters, sorting, and pagination.

const response = await fetch(`${mcpBffUrl}/api/elastic/products/search`, {
  method: 'POST',
  headers,
  body: JSON.stringify({
    search: "wireless headphones",           // Full-text search
    filters: { status: "active" },           // Field filters
    sort: { field: "createdAt", order: "desc" },
    page: 1,
    limit: 25,
  }),
});

POST /api/elastic/:indexName/aggregate — Aggregations

Run aggregation queries for analytics and dashboards.

const response = await fetch(`${mcpBffUrl}/api/elastic/orders/aggregate`, {
  method: 'POST',
  headers,
  body: JSON.stringify({
    aggs: {
      status_counts: { terms: { field: "status.keyword" } },
      total_revenue: { sum: { field: "amount" } },
      monthly_orders: {
        date_histogram: { field: "createdAt", calendar_interval: "month" }
      }
    },
    query: { range: { createdAt: { gte: "now-1y" } } }
  }),
});

GET /api/elastic/:indexName/mapping — Index Mapping

Get the field mapping for an index (useful for building dynamic filter UIs).

const mapping = await fetch(`${mcpBffUrl}/api/elastic/products/mapping`, { headers });

POST /api/elastic/:indexName/ai-search — AI-Assisted Search

Uses the configured AI model to convert a natural-language query into an Elasticsearch query.

const response = await fetch(`${mcpBffUrl}/api/elastic/orders/ai-search`, {
  method: 'POST',
  headers,
  body: JSON.stringify({
    query: "orders over $100 from last month that are still pending",
  }),
});
// Returns: { total, hits, generatedQuery, ... }

Log API

The MCP BFF provides log viewing endpoints for monitoring application behavior.

GET /api/logs — Query Logs

const response = await fetch(`${mcpBffUrl}/api/logs?page=1&limit=50&logType=2&service=commerce&search=payment`, {
  headers,
});

Query Parameters:

GET /api/logs/stream — Real-time Console Stream (SSE)

Streams real-time console output from all services via Server-Sent Events.

const eventSource = new EventSource(`${mcpBffUrl}/api/logs/stream?services=commerce,auth`, {
  headers: { 'Authorization': `Bearer ${accessToken}` },
});

eventSource.addEventListener('log', (event) => {
  const logEntry = JSON.parse(event.data);
  // { service, timestamp, level, message, ... }
});

Available Services

The MCP BFF connects to the following backend services:

Service Description
auth Authentication, user management, sessions
projectPortfolio Handles the lifecycle of film projects and access management, allowing filmmakers & studios to submit, update, publish (public/private), withdraw projects, and manage project access for investors/bookmarks. Enforces admin approval & efficient searching/filtering. Connects projects to user (and optionally studio) ownership.
messagingCenter Facilitates secure messaging between filmmakers, studios, and investors, enabling message threads, moderation, and notifications for industry collaborations.
moderationAdmin Handles approval workflows for studios, investors, and projects; facilitates platform content moderation, user suspensions, and records all related admin actions for audit and compliance.
agentHub AI Agent Hub

Each service exposes MCP tools that the AI can call through the BFF. Use GET /api/tools to discover all available tools at runtime, or GET /api/tools/service/:serviceName to list tools for a specific service.


MCP as Internal API Gateway

The MCP-BFF service can also be used by the frontend as an internal API gateway for tool-based interactions. This is separate from external AI tool connections — it is meant for frontend code that needs to call backend tools programmatically.

Direct Tool Calls (REST)

Use the REST tool invocation endpoints for programmatic access from frontend code:

// List all available tools
const tools = await fetch(`${mcpBffUrl}/api/tools`, { headers });

// Call a specific tool directly
const result = await fetch(`${mcpBffUrl}/api/tools/call`, {
  method: 'POST',
  headers,
  body: JSON.stringify({
    toolName: 'listProducts',
    args: { page: 1, limit: 10 },
  }),
});

AI-Orchestrated Calls (Chat API)

For AI-driven interactions, use the chat streaming API documented above (POST /api/chat/stream). The AI model decides which tools to call based on the user’s message.

Both approaches use the user’s JWT access token for authentication — the MCP-BFF forwards it to the correct backend service.


MCP Connection Info for Profile Page

The user’s profile page should include an informational section explaining how to connect external AI tools (Cursor, Claude Desktop, Lovable, Windsurf, etc.) to this application’s backend via MCP.

What to Display

The MCP-BFF exposes a unified MCP endpoint that aggregates tools from all backend services into a single connection point:

Environment URL
Preview https://auteurlabb.prw.mindbricks.com/mcpbff-api/mcp
Staging https://auteurlabb-stage.mindbricks.co/mcpbff-api/mcp
Production https://auteurlabb.mindbricks.co/mcpbff-api/mcp

For legacy MCP clients that don’t support StreamableHTTP, an SSE fallback is available at the same URL with /sse appended (e.g., .../mcpbff-api/mcp/sse).

Profile Page UI Requirements

Add an “MCP Connection” or “Connect External AI Tools” card/section to the profile page with:

  1. Endpoint URL — Display the MCP endpoint URL for the current environment with a copy-to-clipboard button.

  2. Ready-to-Copy Configs — Show copy-to-clipboard config snippets for popular tools:

    Cursor (.cursor/mcp.json):

    {
      "mcpServers": {
        "auteurlabb": {
          "url": "https://auteurlabb.prw.mindbricks.com/mcpbff-api/mcp",
          "headers": {
            "Authorization": "Bearer your_access_token_here"
          }
        }
      }
    }
    

    Claude Desktop (claude_desktop_config.json):

    {
      "mcpServers": {
        "auteurlabb": {
          "url": "https://auteurlabb.prw.mindbricks.com/mcpbff-api/mcp",
          "headers": {
            "Authorization": "Bearer your_access_token_here"
          }
        }
      }
    }
    
  3. Auth Note — Note that users should replace your_access_token_here with a valid JWT access token from the login API.

  4. OAuth Note — Display a note that OAuth authentication is not currently supported for MCP connections.

  5. Available Tools — Optionally show a summary of available tool categories (e.g., “CRUD operations for all data objects, custom business APIs, file operations”) or link to the tools discovery endpoint (GET /api/tools).


After this prompt, the user may give you new instructions to update the output of this prompt or provide subsequent prompts about the project.


ProjectPortfolio Service

AUTEURLABB

FRONTEND GUIDE FOR AI CODING AGENTS - PART 7 - ProjectPortfolio Service

This document is a part of a REST API guide for the auteurlabb project. It is designed for AI agents that will generate frontend code to consume the project’s backend.

This document provides extensive instruction for the usage of projectPortfolio

Service Access

ProjectPortfolio service management is handled through service specific base urls.

ProjectPortfolio service may be deployed to the preview server, staging server, or production server. Therefore,it has 3 access URLs. The frontend application must support all deployment environments during development, and the user should be able to select the target API server on the login page (already handled in first part.).

For the projectPortfolio service, the base URLs are:

Scope

ProjectPortfolio Service Description

Handles the lifecycle of film projects and access management, allowing filmmakers & studios to submit, update, publish (public/private), withdraw projects, and manage project access for investors/bookmarks. Enforces admin approval & efficient searching/filtering. Connects projects to user (and optionally studio) ownership.

ProjectPortfolio service provides apis and business logic for following data objects in auteurlabb application. Each data object may be either a central domain of the application data structure or a related helper data object for a central concept. Note that data object concept is equal to table concept in the database, in the service database each data object is represented as a db table scheme and the object instances as table rows.

filmProject Data Object: A film project submitted by a filmmaker or studio with all required metadata, visibility, and lifecycle status.

accessGrant Data Object: Access grants to private projects, allowing selected users to view restricted projects (requested/granted/revoked/denied).

projectBookmark Data Object: User bookmarks/follows for projects. Each bookmark is per user+project.

investmentOffer Data Object: Tracks investment offers from investors to film projects. Each offer has an amount, optional message, and status workflow (pending/accepted/rejected/withdrawn).

userFollow Data Object: Tracks user-to-user follow relationships. A follower follows a target user (filmmaker, studio, investor).

ProjectPortfolio Service Frontend Description By The Backend Architect

ProjectPortfolio Service

Use this service to browse, submit, access, and manage film projects. Project listings, details, bookmarks, and access requests are all managed here. Filmmakers/studios can control project visibility. Investors can search, request access, and bookmark. Admins can moderate, approve, and oversee lifecycle transitions. All project API responses may include owner/studio data via selectJoin when needed.

API Structure

Object Structure of a Successful Response

When the service processes requests successfully, it wraps the requested resource(s) within a JSON envelope. This envelope includes the data and essential metadata such as configuration details and pagination information, providing context to the client.

HTTP Status Codes:

Success Response Format:

For successful operations, the response includes a "status": "OK" property, signaling that the request executed successfully. The structure of a successful response is outlined below:

{
  "status":"OK",
  "statusCode": 200,   
  "elapsedMs":126,
  "ssoTime":120,
  "source": "db",
  "cacheKey": "hexCode",
  "userId": "ID",
  "sessionId": "ID",
  "requestId": "ID",
  "dataName":"products",
  "method":"GET",
  "action":"list",
  "appVersion":"Version",
  "rowCount":3,
  "products":[{},{},{}],
  "paging": {
    "pageNumber":1, 
    "pageRowCount":25, 
    "totalRowCount":3,
    "pageCount":1
  },
  "filters": [],
  "uiPermissions": []
}

Additional Data

Each API may include additional data besides the main data object, depending on the business logic of the API. These will be provided in each API’s response signature.

Error Response

If a request encounters an issue—whether due to a logical fault or a technical problem—the service responds with a standardized JSON error structure. The HTTP status code indicates the nature of the error, using commonly recognized codes for clarity:

Each error response is structured to provide meaningful insight into the problem, assisting in efficient diagnosis and resolution.

{
  "result": "ERR",
  "status": 400,
  "message": "errMsg_organizationIdisNotAValidID",
  "errCode": 400,
  "date": "2024-03-19T12:13:54.124Z",
  "detail": "String"
}

FilmProject Data Object

A film project submitted by a filmmaker or studio with all required metadata, visibility, and lifecycle status.

FilmProject Data Object Frontend Description By The Backend Architect

FilmProject Data Object Properties

FilmProject data object has got following properties that are represented as table fields in the database scheme. These properties don’t stand just for data storage, but each may have different settings to manage the business logic.

Property Type IsArray Required Secret Description
title String false Yes No Project title, unique per owner
description Text false Yes No Project description (for details page/fulltext search)
synopsis Text false No No Short synopsis or tagline
budget Double false Yes No Estimated budget (USD)
cast String true No No List of major cast members (names)
genre String true No No Project genres/tags
projectType Enum false Yes No Origin: filmmaker or studio
ownerUserId ID false Yes No User ID of project owner (filmmaker/studio admin)
studioId ID false No No (Optional) User ID of the studio (for studio projects)
isPublic Boolean false Yes No Project public visibility flag
approvalStatus Enum false Yes No Project approval/publication workflow status
mediaUrls String true No No Project demo reel/trailer/cover media URLs
featured Boolean false No No Platform feature flag (for promoted projects)
publishedAt Date false No No Publication date
accessPolicy Enum false Yes No Access policy (open: any authorized user, restricted: need grant)
director String false No No Director of the film project
fundingGoal Double false No No Funding goal amount (USD)

Array Properties

cast genre mediaUrls

Array properties can hold multiple values. Array properties should be respected according to their multiple structure in the frontend in any user input for them. Please use multiple input components for the array proeprties when needed.

Enum Properties

Enum properties are defined with a set of allowed values, ensuring that only valid options can be assigned to them. The enum options value will be stored as strings in the database, but when a data object is created an additional property with the same name plus an idx suffix will be created, which will hold the index of the selected enum option. You can use the {fieldName_idx} property to sort by the enum value or when your enum options represent a hiyerarchy of values. In the frontend input components, enum type properties should only accept values from an option component that lists the enum options.

Relation Properties

ownerUserId studioId

Mindbricks supports relations between data objects, allowing you to define how objects are linked together. The relations may reference to a data object either in this service or in another service. Id the reference is remote, backend handles the relations through service communication or elastic search. These relations should be respected in the frontend so that instaead of showing the related objects id, the frontend should list human readable values from other data objects. If the relation points to another service, frontend should use the referenced service api in case it needs related data. The relation logic is montly handled in backend so the api responses feeds the frontend about the relational data. In mmost cases the api response will provide the relational data as well as the main one.

In frontend, please ensure that,

1- instaead of these relational ids you show the main human readable field of the related target data (like name), 2- if this data object needs a user input of these relational ids, you should provide a combobox with the list of possible records or (a searchbox) to select with the realted target data object main human readable field.

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

Required: Yes

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

Required: No

Filter Properties

title description synopsis budget genre projectType isPublic approvalStatus featured accessPolicy director fundingGoal

Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API’s.

AccessGrant Data Object

Access grants to private projects, allowing selected users to view restricted projects (requested/granted/revoked/denied).

AccessGrant Data Object Frontend Description By The Backend Architect

AccessGrant Data Object Properties

AccessGrant data object has got following properties that are represented as table fields in the database scheme. These properties don’t stand just for data storage, but each may have different settings to manage the business logic.

Property Type IsArray Required Secret Description
projectId ID false Yes No Film project ID for which access is granted/requested
granteeUserId ID false Yes No ID of user being granted/requesting access
grantedByUserId ID false No No Who granted/revoked the access (or null for self-request)
status Enum false Yes No requested (pending); granted (success); revoked; denied
requestMessage Text false No No Message from requester (for context)
dateGranted Date false No No Timestamp when access status last updated

Enum Properties

Enum properties are defined with a set of allowed values, ensuring that only valid options can be assigned to them. The enum options value will be stored as strings in the database, but when a data object is created an additional property with the same name plus an idx suffix will be created, which will hold the index of the selected enum option. You can use the {fieldName_idx} property to sort by the enum value or when your enum options represent a hiyerarchy of values. In the frontend input components, enum type properties should only accept values from an option component that lists the enum options.

Relation Properties

projectId granteeUserId grantedByUserId

Mindbricks supports relations between data objects, allowing you to define how objects are linked together. The relations may reference to a data object either in this service or in another service. Id the reference is remote, backend handles the relations through service communication or elastic search. These relations should be respected in the frontend so that instaead of showing the related objects id, the frontend should list human readable values from other data objects. If the relation points to another service, frontend should use the referenced service api in case it needs related data. The relation logic is montly handled in backend so the api responses feeds the frontend about the relational data. In mmost cases the api response will provide the relational data as well as the main one.

In frontend, please ensure that,

1- instaead of these relational ids you show the main human readable field of the related target data (like name), 2- if this data object needs a user input of these relational ids, you should provide a combobox with the list of possible records or (a searchbox) to select with the realted target data object main human readable field.

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

Required: Yes

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

Required: Yes

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

Required: No

Filter Properties

projectId granteeUserId status

Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API’s.

ProjectBookmark Data Object

User bookmarks/follows for projects. Each bookmark is per user+project.

ProjectBookmark Data Object Frontend Description By The Backend Architect

ProjectBookmark Data Object Properties

ProjectBookmark data object has got following properties that are represented as table fields in the database scheme. These properties don’t stand just for data storage, but each may have different settings to manage the business logic.

Property Type IsArray Required Secret Description
projectId ID false Yes No The project being bookmarked
userId ID false Yes No The user who bookmarked this project
createdAtBookmark Date false No No When bookmark was made

Relation Properties

projectId userId

Mindbricks supports relations between data objects, allowing you to define how objects are linked together. The relations may reference to a data object either in this service or in another service. Id the reference is remote, backend handles the relations through service communication or elastic search. These relations should be respected in the frontend so that instaead of showing the related objects id, the frontend should list human readable values from other data objects. If the relation points to another service, frontend should use the referenced service api in case it needs related data. The relation logic is montly handled in backend so the api responses feeds the frontend about the relational data. In mmost cases the api response will provide the relational data as well as the main one.

In frontend, please ensure that,

1- instaead of these relational ids you show the main human readable field of the related target data (like name), 2- if this data object needs a user input of these relational ids, you should provide a combobox with the list of possible records or (a searchbox) to select with the realted target data object main human readable field.

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

Required: Yes

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

Required: Yes

Filter Properties

projectId userId

Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API’s.

InvestmentOffer Data Object

Tracks investment offers from investors to film projects. Each offer has an amount, optional message, and status workflow (pending/accepted/rejected/withdrawn).

InvestmentOffer Data Object Properties

InvestmentOffer data object has got following properties that are represented as table fields in the database scheme. These properties don’t stand just for data storage, but each may have different settings to manage the business logic.

Property Type IsArray Required Secret Description
projectId ID false Yes No Film project receiving the investment offer
investorUserId ID false Yes No Investor who made the offer
offerAmount Double false Yes No Investment amount in USD
message Text false No No Cover letter or terms from the investor
status Enum false No No Offer lifecycle status
respondedAt Date false No No When the project owner responded
responseNote Text false No No Project owner note on accept/reject

Enum Properties

Enum properties are defined with a set of allowed values, ensuring that only valid options can be assigned to them. The enum options value will be stored as strings in the database, but when a data object is created an additional property with the same name plus an idx suffix will be created, which will hold the index of the selected enum option. You can use the {fieldName_idx} property to sort by the enum value or when your enum options represent a hiyerarchy of values. In the frontend input components, enum type properties should only accept values from an option component that lists the enum options.

Relation Properties

projectId investorUserId

Mindbricks supports relations between data objects, allowing you to define how objects are linked together. The relations may reference to a data object either in this service or in another service. Id the reference is remote, backend handles the relations through service communication or elastic search. These relations should be respected in the frontend so that instaead of showing the related objects id, the frontend should list human readable values from other data objects. If the relation points to another service, frontend should use the referenced service api in case it needs related data. The relation logic is montly handled in backend so the api responses feeds the frontend about the relational data. In mmost cases the api response will provide the relational data as well as the main one.

In frontend, please ensure that,

1- instaead of these relational ids you show the main human readable field of the related target data (like name), 2- if this data object needs a user input of these relational ids, you should provide a combobox with the list of possible records or (a searchbox) to select with the realted target data object main human readable field.

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

Required: Yes

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

Required: Yes

Filter Properties

projectId investorUserId offerAmount status

Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API’s.

UserFollow Data Object

Tracks user-to-user follow relationships. A follower follows a target user (filmmaker, studio, investor).

UserFollow Data Object Properties

UserFollow data object has got following properties that are represented as table fields in the database scheme. These properties don’t stand just for data storage, but each may have different settings to manage the business logic.

Property Type IsArray Required Secret Description
followerUserId ID false Yes No The user who is following
followingUserId ID false Yes No The user being followed
followedAt Date false No No When the follow relationship was created

Relation Properties

followerUserId followingUserId

Mindbricks supports relations between data objects, allowing you to define how objects are linked together. The relations may reference to a data object either in this service or in another service. Id the reference is remote, backend handles the relations through service communication or elastic search. These relations should be respected in the frontend so that instaead of showing the related objects id, the frontend should list human readable values from other data objects. If the relation points to another service, frontend should use the referenced service api in case it needs related data. The relation logic is montly handled in backend so the api responses feeds the frontend about the relational data. In mmost cases the api response will provide the relational data as well as the main one.

In frontend, please ensure that,

1- instaead of these relational ids you show the main human readable field of the related target data (like name), 2- if this data object needs a user input of these relational ids, you should provide a combobox with the list of possible records or (a searchbox) to select with the realted target data object main human readable field.

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

Required: Yes

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

Required: Yes

Filter Properties

followerUserId followingUserId

Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API’s.

Default CRUD APIs

For each data object, the backend architect may designate default APIs for standard operations (create, update, delete, get, list). These are the APIs that frontend CRUD forms and AI agents should use for basic record management. If no default is explicitly set (isDefaultApi), the frontend generator auto-discovers the most general API for each operation.

FilmProject Default APIs

Display Label Property: title — Use this property as the human-readable label when displaying records of this data object (e.g., in dropdowns, references).

Operation API Name Route Explicitly Set
Create createFilmProject /v1/filmprojects Yes
Update updateFilmProject /v1/filmprojects/:filmProjectId Yes
Delete none - Auto
Get getFilmProject /v1/filmprojects/:filmProjectId Yes
List listFilmProjects /v1/filmprojects Yes

AccessGrant Default APIs

Operation API Name Route Explicitly Set
Create createAccessGrant /v1/accessgrants Yes
Update updateAccessGrant /v1/accessgrants/:accessGrantId Yes
Delete none - Auto
Get getAccessGrant /v1/accessgrants/:accessGrantId Yes
List listAccessGrants /v1/accessgrants Yes

ProjectBookmark Default APIs

Operation API Name Route Explicitly Set
Create createBookmark /v1/bookmark Yes
Update none - Auto
Delete deleteBookmark /v1/bookmark/:projectBookmarkId Yes
Get none - Auto
List listBookmarks /v1/bookmarks Yes

InvestmentOffer Default APIs

Operation API Name Route Explicitly Set
Create createInvestmentOffer /v1/investmentoffers Yes
Update respondToInvestmentOffer /v1/respondtoinvestmentoffer/:investmentOfferId Yes
Delete none - Auto
Get none - Auto
List listInvestmentOffers /v1/investmentoffers Yes

UserFollow Default APIs

Operation API Name Route Explicitly Set
Create followUser /v1/followuser Yes
Update none - Auto
Delete unfollowUser /v1/unfollowuser/:userFollowId Yes
Get none - Auto
List listUserFollows /v1/userfollows Yes

When building CRUD forms for a data object, use the default create/update APIs listed above. The form fields should correspond to the API’s body parameters. For relation fields, render a dropdown loaded from the related object’s list API using the display label property.

API Reference

Create Filmproject API

[Default create API] — This is the designated default create API for the filmProject data object. Frontend generators and AI agents should use this API for standard CRUD operations. Submit a new film project (by filmmaker/studio). Sets approvalStatus=pending and assigns ownerUserId from session. Studio projects require studioId.

API Frontend Description By The Backend Architect

Used by filmmakers/studios to submit a new project. Standard create form. Approval workflow starts automatically. Owner assigned from session.

Rest Route

The createFilmProject API REST controller can be triggered via the following route:

/v1/filmprojects

Rest Request Parameters

The createFilmProject api has got 15 regular request parameters

Parameter Type Required Population
title String true request.body?.[“title”]
description Text true request.body?.[“description”]
synopsis Text false request.body?.[“synopsis”]
budget Double true request.body?.[“budget”]
cast String false request.body?.[“cast”]
genre String false request.body?.[“genre”]
projectType Enum true request.body?.[“projectType”]
studioId ID false request.body?.[“studioId”]
isPublic Boolean true request.body?.[“isPublic”]
mediaUrls String false request.body?.[“mediaUrls”]
featured Boolean false request.body?.[“featured”]
publishedAt Date false request.body?.[“publishedAt”]
accessPolicy Enum true request.body?.[“accessPolicy”]
director String false request.body?.[“director”]
fundingGoal Double false request.body?.[“fundingGoal”]
title : Project title, unique per owner
description : Project description (for details page/fulltext search)
synopsis : Short synopsis or tagline
budget : Estimated budget (USD)
cast : List of major cast members (names)
genre : Project genres/tags
projectType : Origin: filmmaker or studio
studioId : (Optional) User ID of the studio (for studio projects)
isPublic : Project public visibility flag
mediaUrls : Project demo reel/trailer/cover media URLs
featured : Platform feature flag (for promoted projects)
publishedAt : Publication date
accessPolicy : Access policy (open: any authorized user, restricted: need grant)
director : Director of the film project
fundingGoal : Funding goal amount (USD)

REST Request To access the api you can use the REST controller with the path POST /v1/filmprojects

  axios({
    method: 'POST',
    url: '/v1/filmprojects',
    data: {
            title:"String",  
            description:"Text",  
            synopsis:"Text",  
            budget:"Double",  
            cast:"String",  
            genre:"String",  
            projectType:"Enum",  
            studioId:"ID",  
            isPublic:"Boolean",  
            mediaUrls:"String",  
            featured:"Boolean",  
            publishedAt:"Date",  
            accessPolicy:"Enum",  
            director:"String",  
            fundingGoal:"Double",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "filmProject",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"filmProject": {
		"id": "ID",
		"title": "String",
		"description": "Text",
		"synopsis": "Text",
		"budget": "Double",
		"cast": "String",
		"genre": "String",
		"projectType": "Enum",
		"projectType_idx": "Integer",
		"ownerUserId": "ID",
		"studioId": "ID",
		"isPublic": "Boolean",
		"approvalStatus": "Enum",
		"approvalStatus_idx": "Integer",
		"mediaUrls": "String",
		"featured": "Boolean",
		"publishedAt": "Date",
		"accessPolicy": "Enum",
		"accessPolicy_idx": "Integer",
		"director": "String",
		"fundingGoal": "Double",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Update Filmproject API

[Default update API] — This is the designated default update API for the filmProject data object. Frontend generators and AI agents should use this API for standard CRUD operations. Update a film project. Only the owner or admin can update. Only admin can set approvalStatus=approved/rejected. Owner can withdraw (approvalStatus=withdrawn).

API Frontend Description By The Backend Architect

For editing project details (including withdrawal). ApprovalStatus can only be changed by admin (other than withdrawn by owner). Owner cannot submit direct publish/approve requests; always wait admin.

Rest Route

The updateFilmProject API REST controller can be triggered via the following route:

/v1/filmprojects/:filmProjectId

Rest Request Parameters

The updateFilmProject api has got 15 regular request parameters

Parameter Type Required Population
filmProjectId ID true request.params?.[“filmProjectId”]
title String false request.body?.[“title”]
description Text false request.body?.[“description”]
synopsis Text false request.body?.[“synopsis”]
budget Double false request.body?.[“budget”]
cast String false request.body?.[“cast”]
genre String false request.body?.[“genre”]
isPublic Boolean false request.body?.[“isPublic”]
approvalStatus Enum true request.body?.[“approvalStatus”]
mediaUrls String false request.body?.[“mediaUrls”]
featured Boolean false request.body?.[“featured”]
publishedAt Date false request.body?.[“publishedAt”]
accessPolicy Enum false request.body?.[“accessPolicy”]
director String false request.body?.[“director”]
fundingGoal Double false request.body?.[“fundingGoal”]
filmProjectId : This id paremeter is used to select the required data object that will be updated
title : Project title, unique per owner
description : Project description (for details page/fulltext search)
synopsis : Short synopsis or tagline
budget : Estimated budget (USD)
cast : List of major cast members (names)
genre : Project genres/tags
isPublic : Project public visibility flag
approvalStatus : Project approval/publication workflow status
mediaUrls : Project demo reel/trailer/cover media URLs
featured : Platform feature flag (for promoted projects)
publishedAt : Publication date
accessPolicy : Access policy (open: any authorized user, restricted: need grant)
director : Director of the film project
fundingGoal : Funding goal amount (USD)

REST Request To access the api you can use the REST controller with the path PATCH /v1/filmprojects/:filmProjectId

  axios({
    method: 'PATCH',
    url: `/v1/filmprojects/${filmProjectId}`,
    data: {
            title:"String",  
            description:"Text",  
            synopsis:"Text",  
            budget:"Double",  
            cast:"String",  
            genre:"String",  
            isPublic:"Boolean",  
            approvalStatus:"Enum",  
            mediaUrls:"String",  
            featured:"Boolean",  
            publishedAt:"Date",  
            accessPolicy:"Enum",  
            director:"String",  
            fundingGoal:"Double",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "filmProject",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"filmProject": {
		"id": "ID",
		"title": "String",
		"description": "Text",
		"synopsis": "Text",
		"budget": "Double",
		"cast": "String",
		"genre": "String",
		"projectType": "Enum",
		"projectType_idx": "Integer",
		"ownerUserId": "ID",
		"studioId": "ID",
		"isPublic": "Boolean",
		"approvalStatus": "Enum",
		"approvalStatus_idx": "Integer",
		"mediaUrls": "String",
		"featured": "Boolean",
		"publishedAt": "Date",
		"accessPolicy": "Enum",
		"accessPolicy_idx": "Integer",
		"director": "String",
		"fundingGoal": "Double",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	},
	"ownerUser": {}
}

Get Filmproject API

[Default get API] — This is the designated default get API for the filmProject data object. Frontend generators and AI agents should use this API for standard CRUD operations. Fetch project details. Accessible by owner, admin, or for public + approved projects. Also for granted investors/users (accessGrant).

API Frontend Description By The Backend Architect

Used to display project details page. Applies access and visibility policy – if project is private, only owner/admin/granted users can see; if public+approved, visible to everyone logged in. User denied access gets 404.

Rest Route

The getFilmProject API REST controller can be triggered via the following route:

/v1/filmprojects/:filmProjectId

Rest Request Parameters

The getFilmProject api has got 1 regular request parameter

Parameter Type Required Population
filmProjectId ID true request.params?.[“filmProjectId”]
filmProjectId : This id paremeter is used to query the required data object.

REST Request To access the api you can use the REST controller with the path GET /v1/filmprojects/:filmProjectId

  axios({
    method: 'GET',
    url: `/v1/filmprojects/${filmProjectId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

This route’s response is constrained to a select list of properties, and therefore does not encompass all attributes of the resource.

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "filmProject",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"filmProject": {
		"ownerUser": {
			"fullname": "String",
			"avatar": "String",
			"roleId": "String"
		},
		"studio": {
			"fullname": "String",
			"avatar": "String",
			"roleId": "String"
		},
		"isActive": true
	}
}

List Filmprojects API

[Default list API] — This is the designated default list API for the filmProject data object. Frontend generators and AI agents should use this API for standard CRUD operations. List projects (public+approved, owned, or where granted). With filters for search. Results by role: owner/all their projects; normal users see only public+approved; investors/studios see owned or accessible, or public+approved. Filters: genre, budget, approvalStatus, isPublic, featured, projectType, title, description (text search).

API Frontend Description By The Backend Architect

Allows all users to search/browse projects. Only public/approved projects are visible to normal users; owners/investors get private projects to which they’re granted. Search by genre, budget, etc. Use for the main project directory.

Rest Route

The listFilmProjects API REST controller can be triggered via the following route:

/v1/filmprojects

Rest Request Parameters The listFilmProjects api has got no request parameters.

REST Request To access the api you can use the REST controller with the path GET /v1/filmprojects

  axios({
    method: 'GET',
    url: '/v1/filmprojects',
    data: {
    
    },
    params: {
    
        }
  });

REST Response

This route’s response is constrained to a select list of properties, and therefore does not encompass all attributes of the resource.

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "filmProjects",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"filmProjects": [
		{
			"ownerUser": [
				{
					"fullname": "String",
					"avatar": "String",
					"roleId": "String"
				},
				{},
				{}
			],
			"isActive": true
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Create Accessgrant API

[Default create API] — This is the designated default create API for the accessGrant data object. Frontend generators and AI agents should use this API for standard CRUD operations. Create a new accessGrant. Used for access requests (user) or direct grant (owner/admin).

API Frontend Description By The Backend Architect

Investors request access to private/restricted projects; project owners or admins grant/revoke access to users. Status flows: requested→granted/denied/revoked. Owner can only grant/revoke their own; admins can manage all.

Rest Route

The createAccessGrant API REST controller can be triggered via the following route:

/v1/accessgrants

Rest Request Parameters

The createAccessGrant api has got 6 regular request parameters

Parameter Type Required Population
projectId ID true request.body?.[“projectId”]
granteeUserId ID true request.body?.[“granteeUserId”]
grantedByUserId ID false request.body?.[“grantedByUserId”]
status Enum true request.body?.[“status”]
requestMessage Text false request.body?.[“requestMessage”]
dateGranted Date false request.body?.[“dateGranted”]
projectId : Film project ID for which access is granted/requested
granteeUserId : ID of user being granted/requesting access
grantedByUserId : Who granted/revoked the access (or null for self-request)
status : requested (pending); granted (success); revoked; denied
requestMessage : Message from requester (for context)
dateGranted : Timestamp when access status last updated

REST Request To access the api you can use the REST controller with the path POST /v1/accessgrants

  axios({
    method: 'POST',
    url: '/v1/accessgrants',
    data: {
            projectId:"ID",  
            granteeUserId:"ID",  
            grantedByUserId:"ID",  
            status:"Enum",  
            requestMessage:"Text",  
            dateGranted:"Date",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "accessGrant",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"accessGrant": {
		"id": "ID",
		"projectId": "ID",
		"granteeUserId": "ID",
		"grantedByUserId": "ID",
		"status": "Enum",
		"status_idx": "Integer",
		"requestMessage": "Text",
		"dateGranted": "Date",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Update Accessgrant API

[Default update API] — This is the designated default update API for the accessGrant data object. Frontend generators and AI agents should use this API for standard CRUD operations. Update status of an access grant. Only admin or project owner can grant, revoke, or deny. User can cancel (delete) their own pending request or see status.

API Frontend Description By The Backend Architect

Used for access management UI. Owners/admins can grant/revoke/deny access grants; requesters can cancel. For status transitions, always log who did it and when. Only valid transitions possible (ex: can’t grant if not owner/admin).

Rest Route

The updateAccessGrant API REST controller can be triggered via the following route:

/v1/accessgrants/:accessGrantId

Rest Request Parameters

The updateAccessGrant api has got 4 regular request parameters

Parameter Type Required Population
accessGrantId ID true request.params?.[“accessGrantId”]
status Enum true request.body?.[“status”]
requestMessage Text false request.body?.[“requestMessage”]
dateGranted Date false request.body?.[“dateGranted”]
accessGrantId : This id paremeter is used to select the required data object that will be updated
status : requested (pending); granted (success); revoked; denied
requestMessage : Message from requester (for context)
dateGranted : Timestamp when access status last updated

REST Request To access the api you can use the REST controller with the path PATCH /v1/accessgrants/:accessGrantId

  axios({
    method: 'PATCH',
    url: `/v1/accessgrants/${accessGrantId}`,
    data: {
            status:"Enum",  
            requestMessage:"Text",  
            dateGranted:"Date",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "accessGrant",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"accessGrant": {
		"id": "ID",
		"projectId": "ID",
		"granteeUserId": "ID",
		"grantedByUserId": "ID",
		"status": "Enum",
		"status_idx": "Integer",
		"requestMessage": "Text",
		"dateGranted": "Date",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Get Accessgrant API

[Default get API] — This is the designated default get API for the accessGrant data object. Frontend generators and AI agents should use this API for standard CRUD operations. Get a single accessGrant record by id. Used for grant management UI.

API Frontend Description By The Backend Architect

Shows a single access grant: who, for what project, current status, request message.

Rest Route

The getAccessGrant API REST controller can be triggered via the following route:

/v1/accessgrants/:accessGrantId

Rest Request Parameters

The getAccessGrant api has got 1 regular request parameter

Parameter Type Required Population
accessGrantId ID true request.params?.[“accessGrantId”]
accessGrantId : This id paremeter is used to query the required data object.

REST Request To access the api you can use the REST controller with the path GET /v1/accessgrants/:accessGrantId

  axios({
    method: 'GET',
    url: `/v1/accessgrants/${accessGrantId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "accessGrant",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"accessGrant": {
		"id": "ID",
		"projectId": "ID",
		"granteeUserId": "ID",
		"grantedByUserId": "ID",
		"status": "Enum",
		"status_idx": "Integer",
		"requestMessage": "Text",
		"dateGranted": "Date",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

List Accessgrants API

[Default list API] — This is the designated default list API for the accessGrant data object. Frontend generators and AI agents should use this API for standard CRUD operations. List all accessGrants for a project (owner/admin) or for a user (user’s own requests).

API Frontend Description By The Backend Architect

Used by project owners/admins to see all access requests; by users to see their own requests & statuses. Investors check their granted projects for dashboard; owners manage through this list.

Rest Route

The listAccessGrants API REST controller can be triggered via the following route:

/v1/accessgrants

Rest Request Parameters

Filter Parameters

The listAccessGrants api supports 3 optional filter parameters for filtering list results:

projectId (ID): Film project ID for which access is granted/requested

granteeUserId (ID): ID of user being granted/requesting access

status (Enum): requested (pending); granted (success); revoked; denied

REST Request To access the api you can use the REST controller with the path GET /v1/accessgrants

  axios({
    method: 'GET',
    url: '/v1/accessgrants',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section above)
        // projectId: '<value>' // Filter by projectId
        // granteeUserId: '<value>' // Filter by granteeUserId
        // status: '<value>' // Filter by status
            }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "accessGrants",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"accessGrants": [
		{
			"id": "ID",
			"projectId": "ID",
			"granteeUserId": "ID",
			"grantedByUserId": "ID",
			"status": "Enum",
			"status_idx": "Integer",
			"requestMessage": "Text",
			"dateGranted": "Date",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID"
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Create Bookmark API

[Default create API] — This is the designated default create API for the projectBookmark data object. Frontend generators and AI agents should use this API for standard CRUD operations. Add a project bookmark (user/project pair, unique).

API Frontend Description By The Backend Architect

Users bookmark projects for easy retrieval. Only one bookmark per (user, project).

Rest Route

The createBookmark API REST controller can be triggered via the following route:

/v1/bookmark

Rest Request Parameters

The createBookmark api has got 1 regular request parameter

Parameter Type Required Population
projectId ID true request.body?.[“projectId”]
projectId : The project being bookmarked

REST Request To access the api you can use the REST controller with the path POST /v1/bookmark

  axios({
    method: 'POST',
    url: '/v1/bookmark',
    data: {
            projectId:"ID",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "projectBookmark",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"projectBookmark": {
		"id": "ID",
		"projectId": "ID",
		"userId": "ID",
		"createdAtBookmark": "Date",
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"isActive": true
	}
}

Delete Bookmark API

[Default delete API] — This is the designated default delete API for the projectBookmark data object. Frontend generators and AI agents should use this API for standard CRUD operations. Remove a project bookmark (user can only delete their own bookmarks).

API Frontend Description By The Backend Architect

Bookmarks are always per-user: can only remove bookmark if you’re the owner.

Rest Route

The deleteBookmark API REST controller can be triggered via the following route:

/v1/bookmark/:projectBookmarkId

Rest Request Parameters

The deleteBookmark api has got 1 regular request parameter

Parameter Type Required Population
projectBookmarkId ID true request.params?.[“projectBookmarkId”]
projectBookmarkId : This id paremeter is used to select the required data object that will be deleted

REST Request To access the api you can use the REST controller with the path DELETE /v1/bookmark/:projectBookmarkId

  axios({
    method: 'DELETE',
    url: `/v1/bookmark/${projectBookmarkId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "projectBookmark",
	"method": "DELETE",
	"action": "delete",
	"appVersion": "Version",
	"rowCount": 1,
	"projectBookmark": {
		"id": "ID",
		"projectId": "ID",
		"userId": "ID",
		"createdAtBookmark": "Date",
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"isActive": false
	}
}

List Bookmarks API

[Default list API] — This is the designated default list API for the projectBookmark data object. Frontend generators and AI agents should use this API for standard CRUD operations. List a user’s own bookmarks. Only accessible for current user. Used for profile/bookmarks view.

API Frontend Description By The Backend Architect

Used for the user’s My Bookmarks page. Always lists only YOUR bookmarks, never others’.

Rest Route

The listBookmarks API REST controller can be triggered via the following route:

/v1/bookmarks

Rest Request Parameters

Filter Parameters

The listBookmarks api supports 2 optional filter parameters for filtering list results:

projectId (ID): The project being bookmarked

userId (ID): The user who bookmarked this project

REST Request To access the api you can use the REST controller with the path GET /v1/bookmarks

  axios({
    method: 'GET',
    url: '/v1/bookmarks',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section above)
        // projectId: '<value>' // Filter by projectId
        // userId: '<value>' // Filter by userId
            }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "projectBookmarks",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"projectBookmarks": [
		{
			"id": "ID",
			"projectId": "ID",
			"userId": "ID",
			"createdAtBookmark": "Date",
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID",
			"isActive": true
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Create Investmentoffer API

[Default create API] — This is the designated default create API for the investmentOffer data object. Frontend generators and AI agents should use this API for standard CRUD operations. Investor sends an investment offer to a film project. Status defaults to pending. Only investors can create offers.

Rest Route

The createInvestmentOffer API REST controller can be triggered via the following route:

/v1/investmentoffers

Rest Request Parameters

The createInvestmentOffer api has got 5 regular request parameters

Parameter Type Required Population
projectId ID true request.body?.[“projectId”]
offerAmount Double true request.body?.[“offerAmount”]
message Text false request.body?.[“message”]
respondedAt Date false request.body?.[“respondedAt”]
responseNote Text false request.body?.[“responseNote”]
projectId : Film project receiving the investment offer
offerAmount : Investment amount in USD
message : Cover letter or terms from the investor
respondedAt : When the project owner responded
responseNote : Project owner note on accept/reject

REST Request To access the api you can use the REST controller with the path POST /v1/investmentoffers

  axios({
    method: 'POST',
    url: '/v1/investmentoffers',
    data: {
            projectId:"ID",  
            offerAmount:"Double",  
            message:"Text",  
            respondedAt:"Date",  
            responseNote:"Text",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "investmentOffer",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"investmentOffer": {
		"id": "ID",
		"projectId": "ID",
		"investorUserId": "ID",
		"offerAmount": "Double",
		"message": "Text",
		"status": "Enum",
		"status_idx": "Integer",
		"respondedAt": "Date",
		"responseNote": "Text",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Respond Toinvestmentoffer API

[Default update API] — This is the designated default update API for the investmentOffer data object. Frontend generators and AI agents should use this API for standard CRUD operations. Project owner accepts or rejects an investment offer. Only the project owner or admin can respond.

Rest Route

The respondToInvestmentOffer API REST controller can be triggered via the following route:

/v1/respondtoinvestmentoffer/:investmentOfferId

Rest Request Parameters

The respondToInvestmentOffer api has got 6 regular request parameters

Parameter Type Required Population
investmentOfferId ID true request.params?.[“investmentOfferId”]
offerAmount Double false request.body?.[“offerAmount”]
message Text false request.body?.[“message”]
status Enum false request.body?.[“status”]
respondedAt Date false request.body?.[“respondedAt”]
responseNote Text false request.body?.[“responseNote”]
investmentOfferId : This id paremeter is used to select the required data object that will be updated
offerAmount : Investment amount in USD
message : Cover letter or terms from the investor
status : Offer lifecycle status
respondedAt : When the project owner responded
responseNote : Project owner note on accept/reject

REST Request To access the api you can use the REST controller with the path PATCH /v1/respondtoinvestmentoffer/:investmentOfferId

  axios({
    method: 'PATCH',
    url: `/v1/respondtoinvestmentoffer/${investmentOfferId}`,
    data: {
            offerAmount:"Double",  
            message:"Text",  
            status:"Enum",  
            respondedAt:"Date",  
            responseNote:"Text",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "investmentOffer",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"investmentOffer": {
		"id": "ID",
		"projectId": "ID",
		"investorUserId": "ID",
		"offerAmount": "Double",
		"message": "Text",
		"status": "Enum",
		"status_idx": "Integer",
		"respondedAt": "Date",
		"responseNote": "Text",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

List Investmentoffers API

[Default list API] — This is the designated default list API for the investmentOffer data object. Frontend generators and AI agents should use this API for standard CRUD operations. List investment offers. Admins see all, investors see their own, filmmakers/studios see offers on their projects.

Rest Route

The listInvestmentOffers API REST controller can be triggered via the following route:

/v1/investmentoffers

Rest Request Parameters

Filter Parameters

The listInvestmentOffers api supports 4 optional filter parameters for filtering list results:

projectId (ID): Film project receiving the investment offer

investorUserId (ID): Investor who made the offer

offerAmount (Double): Investment amount in USD

status (Enum): Offer lifecycle status

REST Request To access the api you can use the REST controller with the path GET /v1/investmentoffers

  axios({
    method: 'GET',
    url: '/v1/investmentoffers',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section above)
        // projectId: '<value>' // Filter by projectId
        // investorUserId: '<value>' // Filter by investorUserId
        // offerAmount: '<value>' // Filter by offerAmount
        // status: '<value>' // Filter by status
            }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "investmentOffers",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"investmentOffers": [
		{
			"id": "ID",
			"projectId": "ID",
			"investorUserId": "ID",
			"offerAmount": "Double",
			"message": "Text",
			"status": "Enum",
			"status_idx": "Integer",
			"respondedAt": "Date",
			"responseNote": "Text",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID"
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Withdraw Investmentoffer API

Investor withdraws their own pending offer. Sets status to withdrawn.

Rest Route

The withdrawInvestmentOffer API REST controller can be triggered via the following route:

/v1/withdrawinvestmentoffer/:investmentOfferId

Rest Request Parameters

The withdrawInvestmentOffer api has got 6 regular request parameters

Parameter Type Required Population
investmentOfferId ID true request.params?.[“investmentOfferId”]
offerAmount Double false request.body?.[“offerAmount”]
message Text false request.body?.[“message”]
status Enum false request.body?.[“status”]
respondedAt Date false request.body?.[“respondedAt”]
responseNote Text false request.body?.[“responseNote”]
investmentOfferId : This id paremeter is used to select the required data object that will be updated
offerAmount : Investment amount in USD
message : Cover letter or terms from the investor
status : Offer lifecycle status
respondedAt : When the project owner responded
responseNote : Project owner note on accept/reject

REST Request To access the api you can use the REST controller with the path PATCH /v1/withdrawinvestmentoffer/:investmentOfferId

  axios({
    method: 'PATCH',
    url: `/v1/withdrawinvestmentoffer/${investmentOfferId}`,
    data: {
            offerAmount:"Double",  
            message:"Text",  
            status:"Enum",  
            respondedAt:"Date",  
            responseNote:"Text",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "investmentOffer",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"investmentOffer": {
		"id": "ID",
		"projectId": "ID",
		"investorUserId": "ID",
		"offerAmount": "Double",
		"message": "Text",
		"status": "Enum",
		"status_idx": "Integer",
		"respondedAt": "Date",
		"responseNote": "Text",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Follow User API

[Default create API] — This is the designated default create API for the userFollow data object. Frontend generators and AI agents should use this API for standard CRUD operations. Follow a user. Creates a follow relationship between the session user and the target user. Duplicate follows are prevented by composite index.

Rest Route

The followUser API REST controller can be triggered via the following route:

/v1/followuser

Rest Request Parameters

The followUser api has got 2 regular request parameters

Parameter Type Required Population
followingUserId ID true request.body?.[“followingUserId”]
followedAt Date false request.body?.[“followedAt”]
followingUserId : The user being followed
followedAt : When the follow relationship was created

REST Request To access the api you can use the REST controller with the path POST /v1/followuser

  axios({
    method: 'POST',
    url: '/v1/followuser',
    data: {
            followingUserId:"ID",  
            followedAt:"Date",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "userFollow",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"userFollow": {
		"id": "ID",
		"followerUserId": "ID",
		"followingUserId": "ID",
		"followedAt": "Date",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Unfollow User API

[Default delete API] — This is the designated default delete API for the userFollow data object. Frontend generators and AI agents should use this API for standard CRUD operations. Unfollow a user. Removes the follow relationship. Only the follower (owner) can unfollow.

Rest Route

The unfollowUser API REST controller can be triggered via the following route:

/v1/unfollowuser/:userFollowId

Rest Request Parameters

The unfollowUser api has got 1 regular request parameter

Parameter Type Required Population
userFollowId ID true request.params?.[“userFollowId”]
userFollowId : This id paremeter is used to select the required data object that will be deleted

REST Request To access the api you can use the REST controller with the path DELETE /v1/unfollowuser/:userFollowId

  axios({
    method: 'DELETE',
    url: `/v1/unfollowuser/${userFollowId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "userFollow",
	"method": "DELETE",
	"action": "delete",
	"appVersion": "Version",
	"rowCount": 1,
	"userFollow": {
		"id": "ID",
		"followerUserId": "ID",
		"followingUserId": "ID",
		"followedAt": "Date",
		"isActive": false,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

List Userfollows API

[Default list API] — This is the designated default list API for the userFollow data object. Frontend generators and AI agents should use this API for standard CRUD operations. List follow relationships. Filter by followerUserId to get who a user follows, or by followingUserId to get a user’s followers.

Rest Route

The listUserFollows API REST controller can be triggered via the following route:

/v1/userfollows

Rest Request Parameters

Filter Parameters

The listUserFollows api supports 2 optional filter parameters for filtering list results:

followerUserId (ID): The user who is following

followingUserId (ID): The user being followed

REST Request To access the api you can use the REST controller with the path GET /v1/userfollows

  axios({
    method: 'GET',
    url: '/v1/userfollows',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section above)
        // followerUserId: '<value>' // Filter by followerUserId
        // followingUserId: '<value>' // Filter by followingUserId
            }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "userFollows",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"userFollows": [
		{
			"id": "ID",
			"followerUserId": "ID",
			"followingUserId": "ID",
			"followedAt": "Date",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID"
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

After this prompt, the user may give you new instructions to update the output of this prompt or provide subsequent prompts about the project.


MessagingCenter Service

AUTEURLABB

FRONTEND GUIDE FOR AI CODING AGENTS - PART 8 - MessagingCenter Service

This document is a part of a REST API guide for the auteurlabb project. It is designed for AI agents that will generate frontend code to consume the project’s backend.

This document provides extensive instruction for the usage of messagingCenter

Service Access

MessagingCenter service management is handled through service specific base urls.

MessagingCenter service may be deployed to the preview server, staging server, or production server. Therefore,it has 3 access URLs. The frontend application must support all deployment environments during development, and the user should be able to select the target API server on the login page (already handled in first part.).

For the messagingCenter service, the base URLs are:

Scope

MessagingCenter Service Description

Facilitates secure messaging between filmmakers, studios, and investors, enabling message threads, moderation, and notifications for industry collaborations.

MessagingCenter service provides apis and business logic for following data objects in auteurlabb application. Each data object may be either a central domain of the application data structure or a related helper data object for a central concept. Note that data object concept is equal to table concept in the database, in the service database each data object is represented as a db table scheme and the object instances as table rows.

messageThread Data Object: A thread (private or group) representing a conversation among platform users, optionally linked to a film project

message Data Object: A message sent in a thread between platform users, with moderation and delivery tracking.

MessagingCenter Service Frontend Description By The Backend Architect

API Structure

Object Structure of a Successful Response

When the service processes requests successfully, it wraps the requested resource(s) within a JSON envelope. This envelope includes the data and essential metadata such as configuration details and pagination information, providing context to the client.

HTTP Status Codes:

Success Response Format:

For successful operations, the response includes a "status": "OK" property, signaling that the request executed successfully. The structure of a successful response is outlined below:

{
  "status":"OK",
  "statusCode": 200,   
  "elapsedMs":126,
  "ssoTime":120,
  "source": "db",
  "cacheKey": "hexCode",
  "userId": "ID",
  "sessionId": "ID",
  "requestId": "ID",
  "dataName":"products",
  "method":"GET",
  "action":"list",
  "appVersion":"Version",
  "rowCount":3,
  "products":[{},{},{}],
  "paging": {
    "pageNumber":1, 
    "pageRowCount":25, 
    "totalRowCount":3,
    "pageCount":1
  },
  "filters": [],
  "uiPermissions": []
}

Additional Data

Each API may include additional data besides the main data object, depending on the business logic of the API. These will be provided in each API’s response signature.

Error Response

If a request encounters an issue—whether due to a logical fault or a technical problem—the service responds with a standardized JSON error structure. The HTTP status code indicates the nature of the error, using commonly recognized codes for clarity:

Each error response is structured to provide meaningful insight into the problem, assisting in efficient diagnosis and resolution.

{
  "result": "ERR",
  "status": 400,
  "message": "errMsg_organizationIdisNotAValidID",
  "errCode": 400,
  "date": "2024-03-19T12:13:54.124Z",
  "detail": "String"
}

MessageThread Data Object

A thread (private or group) representing a conversation among platform users, optionally linked to a film project

MessageThread Data Object Frontend Description By The Backend Architect

Represents the context for a conversation (one-on-one or group) among users. Subject is displayed for group/archived/flagged threads; threads can be listed by participant for chat list UI; relatedProjectId links the thread to a film project for context. Threads can be archived, flagged, or active.

MessageThread Data Object Properties

MessageThread data object has got following properties that are represented as table fields in the database scheme. These properties don’t stand just for data storage, but each may have different settings to manage the business logic.

Property Type IsArray Required Secret Description
participantIds ID true Yes No IDs of all participants in the thread (must be 2+ for group, exactly 2 for 1-1)
subject String false No No Optional subject for the thread, required for group or flagged; for 1-on-1 may be null/empty.
relatedProjectId ID false No No (Optional) The project this thread is about.
isGroup Boolean false Yes No True if thread is a group chat, false if private 1-to-1 message.
createdBy ID false Yes No User who created the thread.
lastMessageAt Date false Yes No Timestamp of the last message in this thread (used for sorting).
threadStatus Enum false Yes No Status of the thread: active, archived, flagged.

Array Properties

participantIds

Array properties can hold multiple values. Array properties should be respected according to their multiple structure in the frontend in any user input for them. Please use multiple input components for the array proeprties when needed.

Enum Properties

Enum properties are defined with a set of allowed values, ensuring that only valid options can be assigned to them. The enum options value will be stored as strings in the database, but when a data object is created an additional property with the same name plus an idx suffix will be created, which will hold the index of the selected enum option. You can use the {fieldName_idx} property to sort by the enum value or when your enum options represent a hiyerarchy of values. In the frontend input components, enum type properties should only accept values from an option component that lists the enum options.

Relation Properties

participantIds relatedProjectId createdBy

Mindbricks supports relations between data objects, allowing you to define how objects are linked together. The relations may reference to a data object either in this service or in another service. Id the reference is remote, backend handles the relations through service communication or elastic search. These relations should be respected in the frontend so that instaead of showing the related objects id, the frontend should list human readable values from other data objects. If the relation points to another service, frontend should use the referenced service api in case it needs related data. The relation logic is montly handled in backend so the api responses feeds the frontend about the relational data. In mmost cases the api response will provide the relational data as well as the main one.

In frontend, please ensure that,

1- instaead of these relational ids you show the main human readable field of the related target data (like name), 2- if this data object needs a user input of these relational ids, you should provide a combobox with the list of possible records or (a searchbox) to select with the realted target data object main human readable field.

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

Required: Yes

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

Required: No

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

Required: Yes

Filter Properties

participantIds relatedProjectId threadStatus

Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API’s.

Message Data Object

A message sent in a thread between platform users, with moderation and delivery tracking.

Message Data Object Frontend Description By The Backend Architect

Represents a participant’s sent message in a conversation. Each message is linked to a thread, contains sender/recipient data, the message content, sent and read dates, and moderation status (normal, flagged, removed). Only the sender can edit (if not flagged/removed and within a grace period), only admin can set moderation actions (for platform safety). Used for chat/message UIs, moderation/inbox displays.

Message Data Object Properties

Message data object has got following properties that are represented as table fields in the database scheme. These properties don’t stand just for data storage, but each may have different settings to manage the business logic.

Property Type IsArray Required Secret Description
threadId ID false Yes No The parent thread of this message.
senderId ID false Yes No User ID of the sender.
content Text false Yes No The actual message content (body).
sentAt Date false Yes No When the message was sent.
readByIds ID true No No User IDs who have read the message (for read receipts).
moderationStatus Enum false Yes No Moderation status: normal (default), flagged (pending review), or removed by admin/moderation.
flaggedReason String false No No Reason for message being flagged (set by admin or reporting workflow).
adminAction String false No No Admin/moderator action/note taken regarding this message (set only by admin).

Array Properties

readByIds

Array properties can hold multiple values. Array properties should be respected according to their multiple structure in the frontend in any user input for them. Please use multiple input components for the array proeprties when needed.

Enum Properties

Enum properties are defined with a set of allowed values, ensuring that only valid options can be assigned to them. The enum options value will be stored as strings in the database, but when a data object is created an additional property with the same name plus an idx suffix will be created, which will hold the index of the selected enum option. You can use the {fieldName_idx} property to sort by the enum value or when your enum options represent a hiyerarchy of values. In the frontend input components, enum type properties should only accept values from an option component that lists the enum options.

Relation Properties

threadId senderId readByIds

Mindbricks supports relations between data objects, allowing you to define how objects are linked together. The relations may reference to a data object either in this service or in another service. Id the reference is remote, backend handles the relations through service communication or elastic search. These relations should be respected in the frontend so that instaead of showing the related objects id, the frontend should list human readable values from other data objects. If the relation points to another service, frontend should use the referenced service api in case it needs related data. The relation logic is montly handled in backend so the api responses feeds the frontend about the relational data. In mmost cases the api response will provide the relational data as well as the main one.

In frontend, please ensure that,

1- instaead of these relational ids you show the main human readable field of the related target data (like name), 2- if this data object needs a user input of these relational ids, you should provide a combobox with the list of possible records or (a searchbox) to select with the realted target data object main human readable field.

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

Required: Yes

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

Required: Yes

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

Required: No

Filter Properties

threadId moderationStatus

Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API’s.

Default CRUD APIs

For each data object, the backend architect may designate default APIs for standard operations (create, update, delete, get, list). These are the APIs that frontend CRUD forms and AI agents should use for basic record management. If no default is explicitly set (isDefaultApi), the frontend generator auto-discovers the most general API for each operation.

MessageThread Default APIs

Operation API Name Route Explicitly Set
Create createMessageThread /v1/messagethreads Yes
Update updateMessageThread /v1/messagethreads/:messageThreadId Yes
Delete none - Auto
Get getMessageThread /v1/messagethreads/:messageThreadId Yes
List listMessageThreads /v1/messagethreads Yes

Message Default APIs

Operation API Name Route Explicitly Set
Create createMessage /v1/messages Yes
Update updateMessage /v1/messages/:messageId Yes
Delete deleteMessage /v1/messages/:messageId Yes
Get getMessage /v1/messages/:messageId Yes
List listMessages /v1/messages Yes

When building CRUD forms for a data object, use the default create/update APIs listed above. The form fields should correspond to the API’s body parameters. For relation fields, render a dropdown loaded from the related object’s list API using the display label property.

API Reference

Create Messagethread API

[Default create API] — This is the designated default create API for the messageThread data object. Frontend generators and AI agents should use this API for standard CRUD operations. Create a new message thread (private or group). Can optionally link to a film project. Enforces participants count and role access.

API Frontend Description By The Backend Architect

For users to start a new conversation (private or group chat) with one or more participants (including themselves); optionally link the thread to a project, set subject (required for group/flagged threads only), subject can be empty for 1-to-1; lastMessageAt auto-set to creation time.

Rest Route

The createMessageThread API REST controller can be triggered via the following route:

/v1/messagethreads

Rest Request Parameters

The createMessageThread api has got 6 regular request parameters

Parameter Type Required Population
participantIds ID true request.body?.[“participantIds”]
subject String false request.body?.[“subject”]
relatedProjectId ID false request.body?.[“relatedProjectId”]
isGroup Boolean true request.body?.[“isGroup”]
lastMessageAt Date true request.body?.[“lastMessageAt”]
threadStatus Enum true request.body?.[“threadStatus”]
participantIds : IDs of all participants in the thread (must be 2+ for group, exactly 2 for 1-1)
subject : Optional subject for the thread, required for group or flagged; for 1-on-1 may be null/empty.
relatedProjectId : (Optional) The project this thread is about.
isGroup : True if thread is a group chat, false if private 1-to-1 message.
lastMessageAt : Timestamp of the last message in this thread (used for sorting).
threadStatus : Status of the thread: active, archived, flagged.

REST Request To access the api you can use the REST controller with the path POST /v1/messagethreads

  axios({
    method: 'POST',
    url: '/v1/messagethreads',
    data: {
            participantIds:"ID",  
            subject:"String",  
            relatedProjectId:"ID",  
            isGroup:"Boolean",  
            lastMessageAt:"Date",  
            threadStatus:"Enum",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "messageThread",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"messageThread": {
		"id": "ID",
		"participantIds": "ID",
		"subject": "String",
		"relatedProjectId": "ID",
		"isGroup": "Boolean",
		"createdBy": "ID",
		"lastMessageAt": "Date",
		"threadStatus": "Enum",
		"threadStatus_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"lastMessage": [
			{
				"senderId": "ID",
				"content": "Text",
				"sentAt": "Date",
				"moderationStatus": "Enum",
				"moderationStatus_idx": "Integer"
			},
			{},
			{}
		],
		"relatedProject": {
			"title": "String",
			"projectType": "Enum",
			"projectType_idx": "Integer",
			"ownerUserId": "ID",
			"isPublic": "Boolean",
			"approvalStatus": "Enum",
			"approvalStatus_idx": "Integer"
		}
	}
}

Get Messagethread API

[Default get API] — This is the designated default get API for the messageThread data object. Frontend generators and AI agents should use this API for standard CRUD operations. Fetch a message thread and last message; only participants or admin may retrieve.

API Frontend Description By The Backend Architect

For thread detail/conversation load: returns thread and its related context (last message, project info). Enforces access: only participants and admins.

Rest Route

The getMessageThread API REST controller can be triggered via the following route:

/v1/messagethreads/:messageThreadId

Rest Request Parameters

The getMessageThread api has got 1 regular request parameter

Parameter Type Required Population
messageThreadId ID true request.params?.[“messageThreadId”]
messageThreadId : This id paremeter is used to query the required data object.

REST Request To access the api you can use the REST controller with the path GET /v1/messagethreads/:messageThreadId

  axios({
    method: 'GET',
    url: `/v1/messagethreads/${messageThreadId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "messageThread",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"messageThread": {
		"id": "ID",
		"participantIds": "ID",
		"subject": "String",
		"relatedProjectId": "ID",
		"isGroup": "Boolean",
		"createdBy": "ID",
		"lastMessageAt": "Date",
		"threadStatus": "Enum",
		"threadStatus_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"lastMessage": [
			{
				"senderId": "ID",
				"content": "Text",
				"sentAt": "Date",
				"moderationStatus": "Enum",
				"moderationStatus_idx": "Integer"
			},
			{},
			{}
		],
		"relatedProject": {
			"title": "String",
			"projectType": "Enum",
			"projectType_idx": "Integer",
			"ownerUserId": "ID",
			"isPublic": "Boolean",
			"approvalStatus": "Enum",
			"approvalStatus_idx": "Integer"
		}
	}
}

List Messagethreads API

[Default list API] — This is the designated default list API for the messageThread data object. Frontend generators and AI agents should use this API for standard CRUD operations. List threads for current user (participantIds contains session userId), or all threads for admin. Filters: by project, thread status, participant, search by subject. Sorted by lastMessageAt desc.

API Frontend Description By The Backend Architect

Returns conversation list for chat inbox. By default lists threads where session user is a participant, with last message for display. Admins can filter/status for moderation, filter by related project for context. Supports pagination.

Rest Route

The listMessageThreads API REST controller can be triggered via the following route:

/v1/messagethreads

Rest Request Parameters

Filter Parameters

The listMessageThreads api supports 4 optional filter parameters for filtering list results:

participantId (ID array): IDs of all participants in the thread (must be 2+ for group, exactly 2 for 1-1)

participantId_op (String): Operator for filtering array property “participantIds”. Use “contains” to check if array contains the value, or “overlap” to check if arrays have common elements.

relatedProjectId (ID): (Optional) The project this thread is about.

threadStatus (Enum): Status of the thread: active, archived, flagged.

REST Request To access the api you can use the REST controller with the path GET /v1/messagethreads

  axios({
    method: 'GET',
    url: '/v1/messagethreads',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section above)
        // participantId: '<value>' // Filter by participantId
        // participantId_op: '<value>' // Filter by participantId_op
        // relatedProjectId: '<value>' // Filter by relatedProjectId
        // threadStatus: '<value>' // Filter by threadStatus
            }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "messageThreads",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"messageThreads": [
		{
			"id": "ID",
			"participantIds": "ID",
			"subject": "String",
			"relatedProjectId": "ID",
			"isGroup": "Boolean",
			"createdBy": "ID",
			"lastMessageAt": "Date",
			"threadStatus": "Enum",
			"threadStatus_idx": "Integer",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID",
			"lastMessage": [
				{
					"senderId": "ID",
					"content": "Text",
					"sentAt": "Date",
					"moderationStatus": "Enum",
					"moderationStatus_idx": "Integer"
				},
				{},
				{}
			],
			"relatedProject": [
				{
					"title": "String",
					"projectType": "Enum",
					"projectType_idx": "Integer",
					"ownerUserId": "ID",
					"isPublic": "Boolean",
					"approvalStatus": "Enum",
					"approvalStatus_idx": "Integer"
				},
				{},
				{}
			]
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Update Messagethread API

[Default update API] — This is the designated default update API for the messageThread data object. Frontend generators and AI agents should use this API for standard CRUD operations. Update thread (subject, status, participants for group). Only thread creator, participants (for subject/archival), or admin can update. Only admin can set status=flagged.

API Frontend Description By The Backend Architect

Allows editing of thread subject, status (archival/flag for moderation), or for admin actions; participants cannot update thread participants unless admin/group owner. All updates are logged for audit. Only admin may set flagged status.

Rest Route

The updateMessageThread API REST controller can be triggered via the following route:

/v1/messagethreads/:messageThreadId

Rest Request Parameters

The updateMessageThread api has got 7 regular request parameters

Parameter Type Required Population
messageThreadId ID true request.params?.[“messageThreadId”]
participantIds ID false request.body?.[“participantIds”]
subject String false request.body?.[“subject”]
relatedProjectId ID false request.body?.[“relatedProjectId”]
isGroup Boolean false request.body?.[“isGroup”]
lastMessageAt Date false request.body?.[“lastMessageAt”]
threadStatus Enum false request.body?.[“threadStatus”]
messageThreadId : This id paremeter is used to select the required data object that will be updated
participantIds : IDs of all participants in the thread (must be 2+ for group, exactly 2 for 1-1)
subject : Optional subject for the thread, required for group or flagged; for 1-on-1 may be null/empty.
relatedProjectId : (Optional) The project this thread is about.
isGroup : True if thread is a group chat, false if private 1-to-1 message.
lastMessageAt : Timestamp of the last message in this thread (used for sorting).
threadStatus : Status of the thread: active, archived, flagged.

REST Request To access the api you can use the REST controller with the path PATCH /v1/messagethreads/:messageThreadId

  axios({
    method: 'PATCH',
    url: `/v1/messagethreads/${messageThreadId}`,
    data: {
            participantIds:"ID",  
            subject:"String",  
            relatedProjectId:"ID",  
            isGroup:"Boolean",  
            lastMessageAt:"Date",  
            threadStatus:"Enum",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "messageThread",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"messageThread": {
		"id": "ID",
		"participantIds": "ID",
		"subject": "String",
		"relatedProjectId": "ID",
		"isGroup": "Boolean",
		"createdBy": "ID",
		"lastMessageAt": "Date",
		"threadStatus": "Enum",
		"threadStatus_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Create Message API

[Default create API] — This is the designated default create API for the message data object. Frontend generators and AI agents should use this API for standard CRUD operations. Send a message (post) in a thread. Only thread participants allowed. Thread lastMessageAt is updated.

API Frontend Description By The Backend Architect

Sends a message in an existing conversation (thread). Access check: only participants may send. Sets senderId, sentAt. Notifies via events. Supports message content, moderation default = normal. Marks thread lastMessageAt for inbox sort.

Rest Route

The createMessage API REST controller can be triggered via the following route:

/v1/messages

Rest Request Parameters

The createMessage api has got 6 regular request parameters

Parameter Type Required Population
threadId ID true request.body?.[“threadId”]
content Text true request.body?.[“content”]
readByIds ID false request.body?.[“readByIds”]
moderationStatus Enum true request.body?.[“moderationStatus”]
flaggedReason String false request.body?.[“flaggedReason”]
adminAction String false request.body?.[“adminAction”]
threadId : The parent thread of this message.
content : The actual message content (body).
readByIds : User IDs who have read the message (for read receipts).
moderationStatus : Moderation status: normal (default), flagged (pending review), or removed by admin/moderation.
flaggedReason : Reason for message being flagged (set by admin or reporting workflow).
adminAction : Admin/moderator action/note taken regarding this message (set only by admin).

REST Request To access the api you can use the REST controller with the path POST /v1/messages

  axios({
    method: 'POST',
    url: '/v1/messages',
    data: {
            threadId:"ID",  
            content:"Text",  
            readByIds:"ID",  
            moderationStatus:"Enum",  
            flaggedReason:"String",  
            adminAction:"String",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "message",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"message": {
		"id": "ID",
		"threadId": "ID",
		"senderId": "ID",
		"content": "Text",
		"sentAt": "Date",
		"readByIds": "ID",
		"moderationStatus": "Enum",
		"moderationStatus_idx": "Integer",
		"flaggedReason": "String",
		"adminAction": "String",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Get Message API

[Default get API] — This is the designated default get API for the message data object. Frontend generators and AI agents should use this API for standard CRUD operations. Fetch a single message, thread participant or admin only.

API Frontend Description By The Backend Architect

Load message (for thread/conversation display or moderation). Only allowed for participant or admin/superAdmin.

Rest Route

The getMessage API REST controller can be triggered via the following route:

/v1/messages/:messageId

Rest Request Parameters

The getMessage api has got 1 regular request parameter

Parameter Type Required Population
messageId ID true request.params?.[“messageId”]
messageId : This id paremeter is used to query the required data object.

REST Request To access the api you can use the REST controller with the path GET /v1/messages/:messageId

  axios({
    method: 'GET',
    url: `/v1/messages/${messageId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "message",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"message": {
		"id": "ID",
		"threadId": "ID",
		"senderId": "ID",
		"content": "Text",
		"sentAt": "Date",
		"readByIds": "ID",
		"moderationStatus": "Enum",
		"moderationStatus_idx": "Integer",
		"flaggedReason": "String",
		"adminAction": "String",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"thread": {
			"participantIds": "ID",
			"subject": "String",
			"relatedProjectId": "ID",
			"threadStatus": "Enum",
			"threadStatus_idx": "Integer"
		}
	}
}

List Messages API

[Default list API] — This is the designated default list API for the message data object. Frontend generators and AI agents should use this API for standard CRUD operations. List messages for a thread (or per filter by participant/project/moderation). Participant or admin only.

API Frontend Description By The Backend Architect

Conversation message list for a given thread, or admin-moderated message audit. Enables filter/sort/paginate (newest last). Only participant of the thread or admin can list.

Rest Route

The listMessages API REST controller can be triggered via the following route:

/v1/messages

Rest Request Parameters

Filter Parameters

The listMessages api supports 2 optional filter parameters for filtering list results:

threadId (ID): The parent thread of this message.

moderationStatus (Enum): Moderation status: normal (default), flagged (pending review), or removed by admin/moderation.

REST Request To access the api you can use the REST controller with the path GET /v1/messages

  axios({
    method: 'GET',
    url: '/v1/messages',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section above)
        // threadId: '<value>' // Filter by threadId
        // moderationStatus: '<value>' // Filter by moderationStatus
            }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "messages",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"messages": [
		{
			"id": "ID",
			"threadId": "ID",
			"senderId": "ID",
			"content": "Text",
			"sentAt": "Date",
			"readByIds": "ID",
			"moderationStatus": "Enum",
			"moderationStatus_idx": "Integer",
			"flaggedReason": "String",
			"adminAction": "String",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID",
			"thread": [
				{
					"participantIds": "ID",
					"subject": "String",
					"relatedProjectId": "ID",
					"threadStatus": "Enum",
					"threadStatus_idx": "Integer"
				},
				{},
				{}
			]
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Update Message API

[Default update API] — This is the designated default update API for the message data object. Frontend generators and AI agents should use this API for standard CRUD operations. Update a message’s content (by sender & only before flagged/removed) or moderation fields (admin only).

API Frontend Description By The Backend Architect

Sender may edit own message content if not yet flagged/removed and within allowed time window (if desired). Only admin may set moderationStatus, flaggedReason, adminAction fields.

Rest Route

The updateMessage API REST controller can be triggered via the following route:

/v1/messages/:messageId

Rest Request Parameters

The updateMessage api has got 6 regular request parameters

Parameter Type Required Population
messageId ID true request.params?.[“messageId”]
content Text false request.body?.[“content”]
readByIds ID false request.body?.[“readByIds”]
moderationStatus Enum false request.body?.[“moderationStatus”]
flaggedReason String false request.body?.[“flaggedReason”]
adminAction String false request.body?.[“adminAction”]
messageId : This id paremeter is used to select the required data object that will be updated
content : The actual message content (body).
readByIds : User IDs who have read the message (for read receipts).
moderationStatus : Moderation status: normal (default), flagged (pending review), or removed by admin/moderation.
flaggedReason : Reason for message being flagged (set by admin or reporting workflow).
adminAction : Admin/moderator action/note taken regarding this message (set only by admin).

REST Request To access the api you can use the REST controller with the path PATCH /v1/messages/:messageId

  axios({
    method: 'PATCH',
    url: `/v1/messages/${messageId}`,
    data: {
            content:"Text",  
            readByIds:"ID",  
            moderationStatus:"Enum",  
            flaggedReason:"String",  
            adminAction:"String",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "message",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"message": {
		"id": "ID",
		"threadId": "ID",
		"senderId": "ID",
		"content": "Text",
		"sentAt": "Date",
		"readByIds": "ID",
		"moderationStatus": "Enum",
		"moderationStatus_idx": "Integer",
		"flaggedReason": "String",
		"adminAction": "String",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Delete Message API

[Default delete API] — This is the designated default delete API for the message data object. Frontend generators and AI agents should use this API for standard CRUD operations. Delete message (by sender - if unflagged, or admin at any time).

API Frontend Description By The Backend Architect

Sender may remove their own unflagged/unmoderated message; admin may remove (hard/soft) any message (for moderation cleanup). All deletes are soft by default (isActive=false).

Rest Route

The deleteMessage API REST controller can be triggered via the following route:

/v1/messages/:messageId

Rest Request Parameters

The deleteMessage api has got 1 regular request parameter

Parameter Type Required Population
messageId ID true request.params?.[“messageId”]
messageId : This id paremeter is used to select the required data object that will be deleted

REST Request To access the api you can use the REST controller with the path DELETE /v1/messages/:messageId

  axios({
    method: 'DELETE',
    url: `/v1/messages/${messageId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "message",
	"method": "DELETE",
	"action": "delete",
	"appVersion": "Version",
	"rowCount": 1,
	"message": {
		"id": "ID",
		"threadId": "ID",
		"senderId": "ID",
		"content": "Text",
		"sentAt": "Date",
		"readByIds": "ID",
		"moderationStatus": "Enum",
		"moderationStatus_idx": "Integer",
		"flaggedReason": "String",
		"adminAction": "String",
		"isActive": false,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

After this prompt, the user may give you new instructions to update the output of this prompt or provide subsequent prompts about the project.


ModerationAdmin Service

AUTEURLABB

FRONTEND GUIDE FOR AI CODING AGENTS - PART 9 - ModerationAdmin Service

This document is a part of a REST API guide for the auteurlabb project. It is designed for AI agents that will generate frontend code to consume the project’s backend.

This document provides extensive instruction for the usage of moderationAdmin

Service Access

ModerationAdmin service management is handled through service specific base urls.

ModerationAdmin service may be deployed to the preview server, staging server, or production server. Therefore,it has 3 access URLs. The frontend application must support all deployment environments during development, and the user should be able to select the target API server on the login page (already handled in first part.).

For the moderationAdmin service, the base URLs are:

Scope

ModerationAdmin Service Description

Handles approval workflows for studios, investors, and projects; facilitates platform content moderation, user suspensions, and records all related admin actions for audit and compliance.

ModerationAdmin service provides apis and business logic for following data objects in auteurlabb application. Each data object may be either a central domain of the application data structure or a related helper data object for a central concept. Note that data object concept is equal to table concept in the database, in the service database each data object is represented as a db table scheme and the object instances as table rows.

approvalRequest Data Object: Tracks approval workflows for studios, investors, and submitted projects. Each request points to a specific entity and is reviewed by admin.

reportLog Data Object: Logs moderation/reporting actions: for project, message, or user. Each report includes status, type, review/action info.

suspensionRecord Data Object: Admin action to suspend or lift suspension on a user. Each record logs a suspension/lift action for audit/compliance.

auditLog Data Object: Generic audit log for all admin/moderation actions across services/objects for compliance and traceability.

ModerationAdmin Service Frontend Description By The Backend Architect

This service is not user-facing and is used strictly for admin and moderation workflows. Typical frontend behaviors involve presenting lists of pending approvals, moderation reports, and audit logs to admins, allowing them to perform workflow actions and review logs. End users can see the status of their own approval requests and reports only. All actions are strictly role-gated. There are no public endpoints.

API Structure

Object Structure of a Successful Response

When the service processes requests successfully, it wraps the requested resource(s) within a JSON envelope. This envelope includes the data and essential metadata such as configuration details and pagination information, providing context to the client.

HTTP Status Codes:

Success Response Format:

For successful operations, the response includes a "status": "OK" property, signaling that the request executed successfully. The structure of a successful response is outlined below:

{
  "status":"OK",
  "statusCode": 200,   
  "elapsedMs":126,
  "ssoTime":120,
  "source": "db",
  "cacheKey": "hexCode",
  "userId": "ID",
  "sessionId": "ID",
  "requestId": "ID",
  "dataName":"products",
  "method":"GET",
  "action":"list",
  "appVersion":"Version",
  "rowCount":3,
  "products":[{},{},{}],
  "paging": {
    "pageNumber":1, 
    "pageRowCount":25, 
    "totalRowCount":3,
    "pageCount":1
  },
  "filters": [],
  "uiPermissions": []
}

Additional Data

Each API may include additional data besides the main data object, depending on the business logic of the API. These will be provided in each API’s response signature.

Error Response

If a request encounters an issue—whether due to a logical fault or a technical problem—the service responds with a standardized JSON error structure. The HTTP status code indicates the nature of the error, using commonly recognized codes for clarity:

Each error response is structured to provide meaningful insight into the problem, assisting in efficient diagnosis and resolution.

{
  "result": "ERR",
  "status": 400,
  "message": "errMsg_organizationIdisNotAValidID",
  "errCode": 400,
  "date": "2024-03-19T12:13:54.124Z",
  "detail": "String"
}

ApprovalRequest Data Object

Tracks approval workflows for studios, investors, and submitted projects. Each request points to a specific entity and is reviewed by admin.

ApprovalRequest Data Object Frontend Description By The Backend Architect

Admins are shown lists of pending, approved, or rejected requests. Only admins can approve/reject; creators can view their own request status but not others. Status and review notes are shown to creators only after decision. All changes are audit-logged.

ApprovalRequest Data Object Properties

ApprovalRequest data object has got following properties that are represented as table fields in the database scheme. These properties don’t stand just for data storage, but each may have different settings to manage the business logic.

Property Type IsArray Required Secret Description
targetType Enum false Yes No Type of entity being approved (studio, investor, project)
targetId ID false Yes No ID of entity being approved (user or project, depending on type)
requestedAt Date false Yes No Request creation time
requestedByUserId ID false Yes No User ID who created the request
status Enum false Yes No Approval status: pending/approved/rejected
reviewedAt Date false No No Date/time request reviewed
reviewedByUserId ID false No No Admin userId who reviewed the request
adminNote String false No No Review note left by admin.

Enum Properties

Enum properties are defined with a set of allowed values, ensuring that only valid options can be assigned to them. The enum options value will be stored as strings in the database, but when a data object is created an additional property with the same name plus an idx suffix will be created, which will hold the index of the selected enum option. You can use the {fieldName_idx} property to sort by the enum value or when your enum options represent a hiyerarchy of values. In the frontend input components, enum type properties should only accept values from an option component that lists the enum options.

Relation Properties

requestedByUserId reviewedByUserId

Mindbricks supports relations between data objects, allowing you to define how objects are linked together. The relations may reference to a data object either in this service or in another service. Id the reference is remote, backend handles the relations through service communication or elastic search. These relations should be respected in the frontend so that instaead of showing the related objects id, the frontend should list human readable values from other data objects. If the relation points to another service, frontend should use the referenced service api in case it needs related data. The relation logic is montly handled in backend so the api responses feeds the frontend about the relational data. In mmost cases the api response will provide the relational data as well as the main one.

In frontend, please ensure that,

1- instaead of these relational ids you show the main human readable field of the related target data (like name), 2- if this data object needs a user input of these relational ids, you should provide a combobox with the list of possible records or (a searchbox) to select with the realted target data object main human readable field.

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

Required: Yes

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

Required: No

Filter Properties

targetType targetId status

Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API’s.

ReportLog Data Object

Logs moderation/reporting actions: for project, message, or user. Each report includes status, type, review/action info.

ReportLog Data Object Frontend Description By The Backend Architect

Admins are shown lists of open/closed/ignored reports and take action by marking as reviewed, adding action notes. Reporting users can see their own report status. All logs reference the original content by type and ID.

ReportLog Data Object Properties

ReportLog data object has got following properties that are represented as table fields in the database scheme. These properties don’t stand just for data storage, but each may have different settings to manage the business logic.

Property Type IsArray Required Secret Description
contentType Enum false Yes No Type of content being reported: project/message/user
contentId ID false Yes No ID of the reported content (project ID, message ID, user ID)
reportType String false Yes No Nature of report (abuse, spam, copyright, etc.)
reportedByUserId ID false Yes No ID of user reporting
reportedAt Date false Yes No Report creation timestamp
reviewStatus Enum false Yes No Open/closed/ignored
reviewAction String false No No Action taken by admin (removed, warned, etc.) or note
actionedByUserId ID false No No Admin making the moderation action
actionedAt Date false No No Time of moderation action

Enum Properties

Enum properties are defined with a set of allowed values, ensuring that only valid options can be assigned to them. The enum options value will be stored as strings in the database, but when a data object is created an additional property with the same name plus an idx suffix will be created, which will hold the index of the selected enum option. You can use the {fieldName_idx} property to sort by the enum value or when your enum options represent a hiyerarchy of values. In the frontend input components, enum type properties should only accept values from an option component that lists the enum options.

Relation Properties

reportedByUserId actionedByUserId

Mindbricks supports relations between data objects, allowing you to define how objects are linked together. The relations may reference to a data object either in this service or in another service. Id the reference is remote, backend handles the relations through service communication or elastic search. These relations should be respected in the frontend so that instaead of showing the related objects id, the frontend should list human readable values from other data objects. If the relation points to another service, frontend should use the referenced service api in case it needs related data. The relation logic is montly handled in backend so the api responses feeds the frontend about the relational data. In mmost cases the api response will provide the relational data as well as the main one.

In frontend, please ensure that,

1- instaead of these relational ids you show the main human readable field of the related target data (like name), 2- if this data object needs a user input of these relational ids, you should provide a combobox with the list of possible records or (a searchbox) to select with the realted target data object main human readable field.

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

Required: Yes

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

Required: No

Filter Properties

contentType contentId reportType reviewStatus

Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API’s.

SuspensionRecord Data Object

Admin action to suspend or lift suspension on a user. Each record logs a suspension/lift action for audit/compliance.

SuspensionRecord Data Object Frontend Description By The Backend Architect

Admins may suspend or reinstate users for violation of policies. Each action is logged; suspension status controls actual access (isActive in core user record). Only admins may create suspension records. All changes update the core auth:user record (isActive).

SuspensionRecord Data Object Properties

SuspensionRecord data object has got following properties that are represented as table fields in the database scheme. These properties don’t stand just for data storage, but each may have different settings to manage the business logic.

Property Type IsArray Required Secret Description
userId ID false Yes No Suspended user id
reason String false Yes No Reason for suspension action
suspendedByUserId ID false Yes No Admin ID who performed the suspension action
suspendedAt Date false Yes No Time of action (suspend/lift)
status Enum false Yes No Current state: active (suspended), lifted (reinstated)

Enum Properties

Enum properties are defined with a set of allowed values, ensuring that only valid options can be assigned to them. The enum options value will be stored as strings in the database, but when a data object is created an additional property with the same name plus an idx suffix will be created, which will hold the index of the selected enum option. You can use the {fieldName_idx} property to sort by the enum value or when your enum options represent a hiyerarchy of values. In the frontend input components, enum type properties should only accept values from an option component that lists the enum options.

Relation Properties

userId suspendedByUserId

Mindbricks supports relations between data objects, allowing you to define how objects are linked together. The relations may reference to a data object either in this service or in another service. Id the reference is remote, backend handles the relations through service communication or elastic search. These relations should be respected in the frontend so that instaead of showing the related objects id, the frontend should list human readable values from other data objects. If the relation points to another service, frontend should use the referenced service api in case it needs related data. The relation logic is montly handled in backend so the api responses feeds the frontend about the relational data. In mmost cases the api response will provide the relational data as well as the main one.

In frontend, please ensure that,

1- instaead of these relational ids you show the main human readable field of the related target data (like name), 2- if this data object needs a user input of these relational ids, you should provide a combobox with the list of possible records or (a searchbox) to select with the realted target data object main human readable field.

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

Required: Yes

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

Required: Yes

AuditLog Data Object

Generic audit log for all admin/moderation actions across services/objects for compliance and traceability.

AuditLog Data Object Frontend Description By The Backend Architect

Admins/reviewers can list or view audit log entries. All log entries are immutable and trace detailed actions for compliance. No updates or deletions allowed.

AuditLog Data Object Properties

AuditLog data object has got following properties that are represented as table fields in the database scheme. These properties don’t stand just for data storage, but each may have different settings to manage the business logic.

Property Type IsArray Required Secret Description
actionType String false Yes No Type of admin action (created, updated, suspended, approved, etc.)
actorUserId ID false Yes No User ID of admin/staff performing the action
targetType String false Yes No Type of object affected by this action (approvalRequest, reportLog, suspensionRecord, etc.)
targetId ID false Yes No ID of the object affected by this action
details Text false No No Freeform details, note, or JSON blob describing action context
actionAt Date false Yes No When the action occurred

Default CRUD APIs

For each data object, the backend architect may designate default APIs for standard operations (create, update, delete, get, list). These are the APIs that frontend CRUD forms and AI agents should use for basic record management. If no default is explicitly set (isDefaultApi), the frontend generator auto-discovers the most general API for each operation.

ApprovalRequest Default APIs

Operation API Name Route Explicitly Set
Create createApprovalRequest /v1/approvalrequests Yes
Update reviewApprovalRequest /v1/reviewapprovalrequest/:approvalRequestId Yes
Delete none - Auto
Get getApprovalRequest /v1/approvalrequests/:approvalRequestId Yes
List listApprovalRequests /v1/approvalrequests Yes

ReportLog Default APIs

Operation API Name Route Explicitly Set
Create createReportLog /v1/reportlogs Yes
Update reviewReportLog /v1/reviewreportlog/:reportLogId Yes
Delete none - Auto
Get getReportLog /v1/reportlogs/:reportLogId Yes
List listReportLogs /v1/reportlogs Yes

SuspensionRecord Default APIs

Operation API Name Route Explicitly Set
Create createSuspensionRecord /v1/suspensionrecords Yes
Update liftSuspensionRecord /v1/liftsuspensionrecord/:suspensionRecordId Yes
Delete none - Auto
Get getSuspensionRecord /v1/suspensionrecords/:suspensionRecordId Yes
List listSuspensionRecords /v1/suspensionrecords Yes

AuditLog Default APIs

Operation API Name Route Explicitly Set
Create createAuditLog /v1/auditlogs Yes
Update none - Auto
Delete none - Auto
Get getAuditLog /v1/auditlogs/:auditLogId Yes
List listAuditLogs /v1/auditlogs Yes

When building CRUD forms for a data object, use the default create/update APIs listed above. The form fields should correspond to the API’s body parameters. For relation fields, render a dropdown loaded from the related object’s list API using the display label property.

API Reference

Create Approvalrequest API

[Default create API] — This is the designated default create API for the approvalRequest data object. Frontend generators and AI agents should use this API for standard CRUD operations. Create a new approval request for studio, investor, or project. Status defaults to pending. Only non-admins can create requests for themselvessss.

Rest Route

The createApprovalRequest API REST controller can be triggered via the following route:

/v1/approvalrequests

Rest Request Parameters

The createApprovalRequest api has got 6 regular request parameters

Parameter Type Required Population
targetType Enum true request.body?.[“targetType”]
targetId ID true request.body?.[“targetId”]
requestedAt Date true request.body?.[“requestedAt”]
reviewedAt Date false request.body?.[“reviewedAt”]
reviewedByUserId ID false request.body?.[“reviewedByUserId”]
adminNote String false request.body?.[“adminNote”]
targetType : Type of entity being approved (studio, investor, project)
targetId : ID of entity being approved (user or project, depending on type)
requestedAt : Request creation time
reviewedAt : Date/time request reviewed
reviewedByUserId : Admin userId who reviewed the request
adminNote : Review note left by admin.

REST Request To access the api you can use the REST controller with the path POST /v1/approvalrequests

  axios({
    method: 'POST',
    url: '/v1/approvalrequests',
    data: {
            targetType:"Enum",  
            targetId:"ID",  
            requestedAt:"Date",  
            reviewedAt:"Date",  
            reviewedByUserId:"ID",  
            adminNote:"String",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "approvalRequest",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"approvalRequest": {
		"id": "ID",
		"targetType": "Enum",
		"targetType_idx": "Integer",
		"targetId": "ID",
		"requestedAt": "Date",
		"requestedByUserId": "ID",
		"status": "Enum",
		"status_idx": "Integer",
		"reviewedAt": "Date",
		"reviewedByUserId": "ID",
		"adminNote": "String",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Review Approvalrequest API

[Default update API] — This is the designated default update API for the approvalRequest data object. Frontend generators and AI agents should use this API for standard CRUD operations. Approve or reject an approval request. Only superAdmin or admin may update status or add review notes.

Rest Route

The reviewApprovalRequest API REST controller can be triggered via the following route:

/v1/reviewapprovalrequest/:approvalRequestId

Rest Request Parameters

The reviewApprovalRequest api has got 5 regular request parameters

Parameter Type Required Population
approvalRequestId ID true request.params?.[“approvalRequestId”]
status Enum true request.body?.[“status”]
reviewedAt Date false request.body?.[“reviewedAt”]
reviewedByUserId ID false request.body?.[“reviewedByUserId”]
adminNote String false request.body?.[“adminNote”]
approvalRequestId : This id paremeter is used to select the required data object that will be updated
status : Approval status: pending/approved/rejected
reviewedAt : Date/time request reviewed
reviewedByUserId : Admin userId who reviewed the request
adminNote : Review note left by admin.

REST Request To access the api you can use the REST controller with the path PATCH /v1/reviewapprovalrequest/:approvalRequestId

  axios({
    method: 'PATCH',
    url: `/v1/reviewapprovalrequest/${approvalRequestId}`,
    data: {
            status:"Enum",  
            reviewedAt:"Date",  
            reviewedByUserId:"ID",  
            adminNote:"String",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "approvalRequest",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"approvalRequest": {
		"id": "ID",
		"targetType": "Enum",
		"targetType_idx": "Integer",
		"targetId": "ID",
		"requestedAt": "Date",
		"requestedByUserId": "ID",
		"status": "Enum",
		"status_idx": "Integer",
		"reviewedAt": "Date",
		"reviewedByUserId": "ID",
		"adminNote": "String",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Get Approvalrequest API

[Default get API] — This is the designated default get API for the approvalRequest data object. Frontend generators and AI agents should use this API for standard CRUD operations. Get a single approvalRequest. Only owner or admin may view.

Rest Route

The getApprovalRequest API REST controller can be triggered via the following route:

/v1/approvalrequests/:approvalRequestId

Rest Request Parameters

The getApprovalRequest api has got 1 regular request parameter

Parameter Type Required Population
approvalRequestId ID true request.params?.[“approvalRequestId”]
approvalRequestId : This id paremeter is used to query the required data object.

REST Request To access the api you can use the REST controller with the path GET /v1/approvalrequests/:approvalRequestId

  axios({
    method: 'GET',
    url: `/v1/approvalrequests/${approvalRequestId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "approvalRequest",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"approvalRequest": {
		"id": "ID",
		"targetType": "Enum",
		"targetType_idx": "Integer",
		"targetId": "ID",
		"requestedAt": "Date",
		"requestedByUserId": "ID",
		"status": "Enum",
		"status_idx": "Integer",
		"reviewedAt": "Date",
		"reviewedByUserId": "ID",
		"adminNote": "String",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"requester": {
			"email": "String",
			"fullname": "String",
			"roleId": "String"
		},
		"reviewer": {
			"email": "String",
			"fullname": "String"
		}
	}
}

List Approvalrequests API

[Default list API] — This is the designated default list API for the approvalRequest data object. Frontend generators and AI agents should use this API for standard CRUD operations. List approval requests. Admins see all, non-admins see only their own.

Rest Route

The listApprovalRequests API REST controller can be triggered via the following route:

/v1/approvalrequests

Rest Request Parameters

Filter Parameters

The listApprovalRequests api supports 3 optional filter parameters for filtering list results:

targetType (Enum): Type of entity being approved (studio, investor, project)

targetId (ID): ID of entity being approved (user or project, depending on type)

status (Enum): Approval status: pending/approved/rejected

REST Request To access the api you can use the REST controller with the path GET /v1/approvalrequests

  axios({
    method: 'GET',
    url: '/v1/approvalrequests',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section above)
        // targetType: '<value>' // Filter by targetType
        // targetId: '<value>' // Filter by targetId
        // status: '<value>' // Filter by status
            }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "approvalRequests",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"approvalRequests": [
		{
			"id": "ID",
			"targetType": "Enum",
			"targetType_idx": "Integer",
			"targetId": "ID",
			"requestedAt": "Date",
			"requestedByUserId": "ID",
			"status": "Enum",
			"status_idx": "Integer",
			"reviewedAt": "Date",
			"reviewedByUserId": "ID",
			"adminNote": "String",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID",
			"requester": [
				{
					"email": "String",
					"fullname": "String",
					"roleId": "String"
				},
				{},
				{}
			],
			"reviewer": [
				{
					"email": "String",
					"fullname": "String"
				},
				{},
				{}
			]
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Create Reportlog API

[Default create API] — This is the designated default create API for the reportLog data object. Frontend generators and AI agents should use this API for standard CRUD operations. Create a content/user/project moderation report

Rest Route

The createReportLog API REST controller can be triggered via the following route:

/v1/reportlogs

Rest Request Parameters

The createReportLog api has got 7 regular request parameters

Parameter Type Required Population
contentType Enum true request.body?.[“contentType”]
contentId ID true request.body?.[“contentId”]
reportType String true request.body?.[“reportType”]
reportedAt Date true request.body?.[“reportedAt”]
reviewAction String false request.body?.[“reviewAction”]
actionedByUserId ID false request.body?.[“actionedByUserId”]
actionedAt Date false request.body?.[“actionedAt”]
contentType : Type of content being reported: project/message/user
contentId : ID of the reported content (project ID, message ID, user ID)
reportType : Nature of report (abuse, spam, copyright, etc.)
reportedAt : Report creation timestamp
reviewAction : Action taken by admin (removed, warned, etc.) or note
actionedByUserId : Admin making the moderation action
actionedAt : Time of moderation action

REST Request To access the api you can use the REST controller with the path POST /v1/reportlogs

  axios({
    method: 'POST',
    url: '/v1/reportlogs',
    data: {
            contentType:"Enum",  
            contentId:"ID",  
            reportType:"String",  
            reportedAt:"Date",  
            reviewAction:"String",  
            actionedByUserId:"ID",  
            actionedAt:"Date",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "reportLog",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"reportLog": {
		"id": "ID",
		"contentType": "Enum",
		"contentType_idx": "Integer",
		"contentId": "ID",
		"reportType": "String",
		"reportedByUserId": "ID",
		"reportedAt": "Date",
		"reviewStatus": "Enum",
		"reviewStatus_idx": "Integer",
		"reviewAction": "String",
		"actionedByUserId": "ID",
		"actionedAt": "Date",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Review Reportlog API

[Default update API] — This is the designated default update API for the reportLog data object. Frontend generators and AI agents should use this API for standard CRUD operations. Admin-only: Close/ignore a report, add review action/note. Only superAdmin/admin allowed.

Rest Route

The reviewReportLog API REST controller can be triggered via the following route:

/v1/reviewreportlog/:reportLogId

Rest Request Parameters

The reviewReportLog api has got 5 regular request parameters

Parameter Type Required Population
reportLogId ID true request.params?.[“reportLogId”]
reviewStatus Enum true request.body?.[“reviewStatus”]
reviewAction String false request.body?.[“reviewAction”]
actionedByUserId ID false request.body?.[“actionedByUserId”]
actionedAt Date false request.body?.[“actionedAt”]
reportLogId : This id paremeter is used to select the required data object that will be updated
reviewStatus : Open/closed/ignored
reviewAction : Action taken by admin (removed, warned, etc.) or note
actionedByUserId : Admin making the moderation action
actionedAt : Time of moderation action

REST Request To access the api you can use the REST controller with the path PATCH /v1/reviewreportlog/:reportLogId

  axios({
    method: 'PATCH',
    url: `/v1/reviewreportlog/${reportLogId}`,
    data: {
            reviewStatus:"Enum",  
            reviewAction:"String",  
            actionedByUserId:"ID",  
            actionedAt:"Date",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "reportLog",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"reportLog": {
		"id": "ID",
		"contentType": "Enum",
		"contentType_idx": "Integer",
		"contentId": "ID",
		"reportType": "String",
		"reportedByUserId": "ID",
		"reportedAt": "Date",
		"reviewStatus": "Enum",
		"reviewStatus_idx": "Integer",
		"reviewAction": "String",
		"actionedByUserId": "ID",
		"actionedAt": "Date",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Get Reportlog API

[Default get API] — This is the designated default get API for the reportLog data object. Frontend generators and AI agents should use this API for standard CRUD operations. Get a single report log. Only admins or reporting user may view.

Rest Route

The getReportLog API REST controller can be triggered via the following route:

/v1/reportlogs/:reportLogId

Rest Request Parameters

The getReportLog api has got 1 regular request parameter

Parameter Type Required Population
reportLogId ID true request.params?.[“reportLogId”]
reportLogId : This id paremeter is used to query the required data object.

REST Request To access the api you can use the REST controller with the path GET /v1/reportlogs/:reportLogId

  axios({
    method: 'GET',
    url: `/v1/reportlogs/${reportLogId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "reportLog",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"reportLog": {
		"id": "ID",
		"contentType": "Enum",
		"contentType_idx": "Integer",
		"contentId": "ID",
		"reportType": "String",
		"reportedByUserId": "ID",
		"reportedAt": "Date",
		"reviewStatus": "Enum",
		"reviewStatus_idx": "Integer",
		"reviewAction": "String",
		"actionedByUserId": "ID",
		"actionedAt": "Date",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"reportedBy": {
			"email": "String",
			"fullname": "String",
			"roleId": "String"
		},
		"actionedBy": {
			"email": "String",
			"fullname": "String"
		}
	}
}

List Reportlogs API

[Default list API] — This is the designated default list API for the reportLog data object. Frontend generators and AI agents should use this API for standard CRUD operations. List moderation reports. Admins see all; other users see only their reports.

Rest Route

The listReportLogs API REST controller can be triggered via the following route:

/v1/reportlogs

Rest Request Parameters

Filter Parameters

The listReportLogs api supports 4 optional filter parameters for filtering list results:

contentType (Enum): Type of content being reported: project/message/user

contentId (ID): ID of the reported content (project ID, message ID, user ID)

reportType (String): Nature of report (abuse, spam, copyright, etc.)

reviewStatus (Enum): Open/closed/ignored

REST Request To access the api you can use the REST controller with the path GET /v1/reportlogs

  axios({
    method: 'GET',
    url: '/v1/reportlogs',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section above)
        // contentType: '<value>' // Filter by contentType
        // contentId: '<value>' // Filter by contentId
        // reportType: '<value>' // Filter by reportType
        // reviewStatus: '<value>' // Filter by reviewStatus
            }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "reportLogs",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"reportLogs": [
		{
			"id": "ID",
			"contentType": "Enum",
			"contentType_idx": "Integer",
			"contentId": "ID",
			"reportType": "String",
			"reportedByUserId": "ID",
			"reportedAt": "Date",
			"reviewStatus": "Enum",
			"reviewStatus_idx": "Integer",
			"reviewAction": "String",
			"actionedByUserId": "ID",
			"actionedAt": "Date",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID",
			"reportedBy": [
				{
					"email": "String",
					"fullname": "String",
					"roleId": "String"
				},
				{},
				{}
			],
			"actionedBy": [
				{
					"email": "String",
					"fullname": "String"
				},
				{},
				{}
			]
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Create Suspensionrecord API

[Default create API] — This is the designated default create API for the suspensionRecord data object. Frontend generators and AI agents should use this API for standard CRUD operations. Admin: suspend a user from the platform. Action triggers update to auth:user isActive = false.

Rest Route

The createSuspensionRecord API REST controller can be triggered via the following route:

/v1/suspensionrecords

Rest Request Parameters

The createSuspensionRecord api has got 4 regular request parameters

Parameter Type Required Population
userId ID true request.body?.[“userId”]
reason String true request.body?.[“reason”]
suspendedByUserId ID true request.body?.[“suspendedByUserId”]
suspendedAt Date true request.body?.[“suspendedAt”]
userId : Suspended user id
reason : Reason for suspension action
suspendedByUserId : Admin ID who performed the suspension action
suspendedAt : Time of action (suspend/lift)

REST Request To access the api you can use the REST controller with the path POST /v1/suspensionrecords

  axios({
    method: 'POST',
    url: '/v1/suspensionrecords',
    data: {
            userId:"ID",  
            reason:"String",  
            suspendedByUserId:"ID",  
            suspendedAt:"Date",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "suspensionRecord",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"suspensionRecord": {
		"id": "ID",
		"userId": "ID",
		"reason": "String",
		"suspendedByUserId": "ID",
		"suspendedAt": "Date",
		"status": "Enum",
		"status_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Lift Suspensionrecord API

[Default update API] — This is the designated default update API for the suspensionRecord data object. Frontend generators and AI agents should use this API for standard CRUD operations. Admin: lift user suspension, set status to lifted & update user isActive=true in auth service.

Rest Route

The liftSuspensionRecord API REST controller can be triggered via the following route:

/v1/liftsuspensionrecord/:suspensionRecordId

Rest Request Parameters

The liftSuspensionRecord api has got 1 regular request parameter

Parameter Type Required Population
suspensionRecordId ID true request.params?.[“suspensionRecordId”]
suspensionRecordId : This id paremeter is used to select the required data object that will be updated

REST Request To access the api you can use the REST controller with the path PATCH /v1/liftsuspensionrecord/:suspensionRecordId

  axios({
    method: 'PATCH',
    url: `/v1/liftsuspensionrecord/${suspensionRecordId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "suspensionRecord",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"suspensionRecord": {
		"id": "ID",
		"userId": "ID",
		"reason": "String",
		"suspendedByUserId": "ID",
		"suspendedAt": "Date",
		"status": "Enum",
		"status_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Get Suspensionrecord API

[Default get API] — This is the designated default get API for the suspensionRecord data object. Frontend generators and AI agents should use this API for standard CRUD operations. Get a suspension record. Only admin/superAdmin or suspended user.

Rest Route

The getSuspensionRecord API REST controller can be triggered via the following route:

/v1/suspensionrecords/:suspensionRecordId

Rest Request Parameters

The getSuspensionRecord api has got 1 regular request parameter

Parameter Type Required Population
suspensionRecordId ID true request.params?.[“suspensionRecordId”]
suspensionRecordId : This id paremeter is used to query the required data object.

REST Request To access the api you can use the REST controller with the path GET /v1/suspensionrecords/:suspensionRecordId

  axios({
    method: 'GET',
    url: `/v1/suspensionrecords/${suspensionRecordId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "suspensionRecord",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"suspensionRecord": {
		"id": "ID",
		"userId": "ID",
		"reason": "String",
		"suspendedByUserId": "ID",
		"suspendedAt": "Date",
		"status": "Enum",
		"status_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"user": {
			"email": "String",
			"fullname": "String",
			"roleId": "String"
		},
		"suspendedByUser": {
			"email": "String",
			"fullname": "String"
		}
	}
}

List Suspensionrecords API

[Default list API] — This is the designated default list API for the suspensionRecord data object. Frontend generators and AI agents should use this API for standard CRUD operations. List suspension records. Admins see all; users see only their own.

Rest Route

The listSuspensionRecords API REST controller can be triggered via the following route:

/v1/suspensionrecords

Rest Request Parameters The listSuspensionRecords api has got no request parameters.

REST Request To access the api you can use the REST controller with the path GET /v1/suspensionrecords

  axios({
    method: 'GET',
    url: '/v1/suspensionrecords',
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "suspensionRecords",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"suspensionRecords": [
		{
			"id": "ID",
			"userId": "ID",
			"reason": "String",
			"suspendedByUserId": "ID",
			"suspendedAt": "Date",
			"status": "Enum",
			"status_idx": "Integer",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID",
			"user": [
				{
					"email": "String",
					"fullname": "String",
					"roleId": "String"
				},
				{},
				{}
			],
			"suspendedByUser": [
				{
					"email": "String",
					"fullname": "String"
				},
				{},
				{}
			]
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Create Auditlog API

[Default create API] — This is the designated default create API for the auditLog data object. Frontend generators and AI agents should use this API for standard CRUD operations. Create audit log entry. Only used by system or admin workflows.

Rest Route

The createAuditLog API REST controller can be triggered via the following route:

/v1/auditlogs

Rest Request Parameters

The createAuditLog api has got 6 regular request parameters

Parameter Type Required Population
actionType String true request.body?.[“actionType”]
actorUserId ID true request.body?.[“actorUserId”]
targetType String true request.body?.[“targetType”]
targetId ID true request.body?.[“targetId”]
details Text false request.body?.[“details”]
actionAt Date true request.body?.[“actionAt”]
actionType : Type of admin action (created, updated, suspended, approved, etc.)
actorUserId : User ID of admin/staff performing the action
targetType : Type of object affected by this action (approvalRequest, reportLog, suspensionRecord, etc.)
targetId : ID of the object affected by this action
details : Freeform details, note, or JSON blob describing action context
actionAt : When the action occurred

REST Request To access the api you can use the REST controller with the path POST /v1/auditlogs

  axios({
    method: 'POST',
    url: '/v1/auditlogs',
    data: {
            actionType:"String",  
            actorUserId:"ID",  
            targetType:"String",  
            targetId:"ID",  
            details:"Text",  
            actionAt:"Date",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "auditLog",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"auditLog": {
		"id": "ID",
		"actionType": "String",
		"actorUserId": "ID",
		"targetType": "String",
		"targetId": "ID",
		"details": "Text",
		"actionAt": "Date",
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"isActive": true
	}
}

Get Auditlog API

[Default get API] — This is the designated default get API for the auditLog data object. Frontend generators and AI agents should use this API for standard CRUD operations. Get a single audit log record. Only superAdmin/admin.

Rest Route

The getAuditLog API REST controller can be triggered via the following route:

/v1/auditlogs/:auditLogId

Rest Request Parameters

The getAuditLog api has got 1 regular request parameter

Parameter Type Required Population
auditLogId ID true request.params?.[“auditLogId”]
auditLogId : This id paremeter is used to query the required data object.

REST Request To access the api you can use the REST controller with the path GET /v1/auditlogs/:auditLogId

  axios({
    method: 'GET',
    url: `/v1/auditlogs/${auditLogId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "auditLog",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"auditLog": {
		"id": "ID",
		"actionType": "String",
		"actorUserId": "ID",
		"targetType": "String",
		"targetId": "ID",
		"details": "Text",
		"actionAt": "Date",
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"isActive": true
	}
}

List Auditlogs API

[Default list API] — This is the designated default list API for the auditLog data object. Frontend generators and AI agents should use this API for standard CRUD operations. List audit log records. Only superAdmin/admin.

Rest Route

The listAuditLogs API REST controller can be triggered via the following route:

/v1/auditlogs

Rest Request Parameters The listAuditLogs api has got no request parameters.

REST Request To access the api you can use the REST controller with the path GET /v1/auditlogs

  axios({
    method: 'GET',
    url: '/v1/auditlogs',
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "auditLogs",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"auditLogs": [
		{
			"id": "ID",
			"actionType": "String",
			"actorUserId": "ID",
			"targetType": "String",
			"targetId": "ID",
			"details": "Text",
			"actionAt": "Date",
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID",
			"isActive": true
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

After this prompt, the user may give you new instructions to update the output of this prompt or provide subsequent prompts about the project.


AgentHub Service

AUTEURLABB

FRONTEND GUIDE FOR AI CODING AGENTS - PART 10 - AgentHub Service

This document is a part of a REST API guide for the auteurlabb project. It is designed for AI agents that will generate frontend code to consume the project’s backend.

This document provides extensive instruction for the usage of agentHub

Service Access

AgentHub service management is handled through service specific base urls.

AgentHub service may be deployed to the preview server, staging server, or production server. Therefore,it has 3 access URLs. The frontend application must support all deployment environments during development, and the user should be able to select the target API server on the login page (already handled in first part.).

For the agentHub service, the base URLs are:

Scope

AgentHub Service Description

AI Agent Hub

AgentHub service provides apis and business logic for following data objects in auteurlabb application. Each data object may be either a central domain of the application data structure or a related helper data object for a central concept. Note that data object concept is equal to table concept in the database, in the service database each data object is represented as a db table scheme and the object instances as table rows.

sys_agentOverride Data Object: Runtime overrides for design-time agents. Null fields use the design default.

sys_agentExecution Data Object: Agent execution log. Records each agent invocation with input, output, and performance metrics.

sys_toolCatalog Data Object: Cached tool catalog discovered from project services. Refreshed periodically.

API Structure

Object Structure of a Successful Response

When the service processes requests successfully, it wraps the requested resource(s) within a JSON envelope. This envelope includes the data and essential metadata such as configuration details and pagination information, providing context to the client.

HTTP Status Codes:

Success Response Format:

For successful operations, the response includes a "status": "OK" property, signaling that the request executed successfully. The structure of a successful response is outlined below:

{
  "status":"OK",
  "statusCode": 200,   
  "elapsedMs":126,
  "ssoTime":120,
  "source": "db",
  "cacheKey": "hexCode",
  "userId": "ID",
  "sessionId": "ID",
  "requestId": "ID",
  "dataName":"products",
  "method":"GET",
  "action":"list",
  "appVersion":"Version",
  "rowCount":3,
  "products":[{},{},{}],
  "paging": {
    "pageNumber":1, 
    "pageRowCount":25, 
    "totalRowCount":3,
    "pageCount":1
  },
  "filters": [],
  "uiPermissions": []
}

Additional Data

Each API may include additional data besides the main data object, depending on the business logic of the API. These will be provided in each API’s response signature.

Error Response

If a request encounters an issue—whether due to a logical fault or a technical problem—the service responds with a standardized JSON error structure. The HTTP status code indicates the nature of the error, using commonly recognized codes for clarity:

Each error response is structured to provide meaningful insight into the problem, assisting in efficient diagnosis and resolution.

{
  "result": "ERR",
  "status": 400,
  "message": "errMsg_organizationIdisNotAValidID",
  "errCode": 400,
  "date": "2024-03-19T12:13:54.124Z",
  "detail": "String"
}

Sys_agentOverride Data Object

Runtime overrides for design-time agents. Null fields use the design default.

Sys_agentOverride Data Object Properties

Sys_agentOverride data object has got following properties that are represented as table fields in the database scheme. These properties don’t stand just for data storage, but each may have different settings to manage the business logic.

Property Type IsArray Required Secret Description
agentName String Yes No Design-time agent name this override applies to.
provider String No No Override AI provider (e.g., openai, anthropic).
model String No No Override model name.
systemPrompt Text No No Override system prompt.
temperature Double No No Override temperature (0-2).
maxTokens Integer No No Override max tokens.
responseFormat String No No Override response format (text/json).
selectedTools Object No No Array of tool names from the catalog that this agent can use.
guardrails Object No No Override guardrails: { maxToolCalls, timeout, maxTokenBudget }.
enabled Boolean Yes No Enable or disable this agent.
updatedBy ID No No User who last updated this override.

Sys_agentExecution Data Object

Agent execution log. Records each agent invocation with input, output, and performance metrics.

Sys_agentExecution Data Object Properties

Sys_agentExecution data object has got following properties that are represented as table fields in the database scheme. These properties don’t stand just for data storage, but each may have different settings to manage the business logic.

Property Type IsArray Required Secret Description
agentName String Yes No Agent that was executed.
agentType Enum Yes No Whether this was a design-time or dynamic agent.
source Enum Yes No How the agent was triggered.
userId ID No No User who triggered the execution.
input Object No No Request input (truncated for large payloads).
output Object No No Response output (truncated for large payloads).
toolCalls Integer No No Number of tool calls made during execution.
tokenUsage Object No No Token usage: { prompt, completion, total }.
durationMs Integer No No Execution time in milliseconds.
status Enum Yes No Execution status.
error Text No No Error message if execution failed.

Enum Properties

Enum properties are defined with a set of allowed values, ensuring that only valid options can be assigned to them. The enum options value will be stored as strings in the database, but when a data object is created an additional property with the same name plus an idx suffix will be created, which will hold the index of the selected enum option. You can use the {fieldName_idx} property to sort by the enum value or when your enum options represent a hiyerarchy of values. In the frontend input components, enum type properties should only accept values from an option component that lists the enum options.

Filter Properties

agentName agentType source userId status

Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API’s.

Sys_toolCatalog Data Object

Cached tool catalog discovered from project services. Refreshed periodically.

Sys_toolCatalog Data Object Properties

Sys_toolCatalog data object has got following properties that are represented as table fields in the database scheme. These properties don’t stand just for data storage, but each may have different settings to manage the business logic.

Property Type IsArray Required Secret Description
toolName String Yes No Full tool name (e.g., service:apiName).
serviceName String Yes No Source service name.
description Text No No Tool description.
parameters Object No No JSON Schema of tool parameters.
lastRefreshed Date No No When this tool was last discovered/refreshed.

Filter Properties

serviceName

Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API’s.

Default CRUD APIs

For each data object, the backend architect may designate default APIs for standard operations (create, update, delete, get, list). These are the APIs that frontend CRUD forms and AI agents should use for basic record management. If no default is explicitly set (isDefaultApi), the frontend generator auto-discovers the most general API for each operation.

Sys_agentOverride Default APIs

Operation API Name Route Explicitly Set
Create createAgentOverride /v1/agentoverride Yes
Update updateAgentOverride /v1/agentoverride/:sys_agentOverrideId Yes
Delete deleteAgentOverride /v1/agentoverride/:sys_agentOverrideId Yes
Get getAgentOverride /v1/agentoverride/:sys_agentOverrideId Yes
List listAgentOverrides /v1/agentoverrides Yes

Sys_agentExecution Default APIs

Operation API Name Route Explicitly Set
Create none - Auto
Update none - Auto
Delete none - Auto
Get getAgentExecution /v1/agentexecution/:sys_agentExecutionId Yes
List listAgentExecutions /v1/agentexecutions Yes

Sys_toolCatalog Default APIs

Operation API Name Route Explicitly Set
Create none - Auto
Update none - Auto
Delete none - Auto
Get getToolCatalogEntry /v1/toolcatalogentry/:sys_toolCatalogId Yes
List listToolCatalog /v1/toolcatalog Yes

When building CRUD forms for a data object, use the default create/update APIs listed above. The form fields should correspond to the API’s body parameters. For relation fields, render a dropdown loaded from the related object’s list API using the display label property.

API Reference

Get Agentoverride API

[Default get API] — This is the designated default get API for the sys_agentOverride data object. Frontend generators and AI agents should use this API for standard CRUD operations.

Rest Route

The getAgentOverride API REST controller can be triggered via the following route:

/v1/agentoverride/:sys_agentOverrideId

Rest Request Parameters

The getAgentOverride api has got 1 regular request parameter

Parameter Type Required Population
sys_agentOverrideId ID true request.params?.[“sys_agentOverrideId”]
sys_agentOverrideId : This id paremeter is used to query the required data object.

REST Request To access the api you can use the REST controller with the path GET /v1/agentoverride/:sys_agentOverrideId

  axios({
    method: 'GET',
    url: `/v1/agentoverride/${sys_agentOverrideId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_agentOverride",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"sys_agentOverride": {
		"id": "ID",
		"agentName": "String",
		"provider": "String",
		"model": "String",
		"systemPrompt": "Text",
		"temperature": "Double",
		"maxTokens": "Integer",
		"responseFormat": "String",
		"selectedTools": "Object",
		"guardrails": "Object",
		"enabled": "Boolean",
		"updatedBy": "ID",
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"isActive": true
	}
}

List Agentoverrides API

[Default list API] — This is the designated default list API for the sys_agentOverride data object. Frontend generators and AI agents should use this API for standard CRUD operations.

Rest Route

The listAgentOverrides API REST controller can be triggered via the following route:

/v1/agentoverrides

Rest Request Parameters The listAgentOverrides api has got no request parameters.

REST Request To access the api you can use the REST controller with the path GET /v1/agentoverrides

  axios({
    method: 'GET',
    url: '/v1/agentoverrides',
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_agentOverrides",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"sys_agentOverrides": [
		{
			"id": "ID",
			"agentName": "String",
			"provider": "String",
			"model": "String",
			"systemPrompt": "Text",
			"temperature": "Double",
			"maxTokens": "Integer",
			"responseFormat": "String",
			"selectedTools": "Object",
			"guardrails": "Object",
			"enabled": "Boolean",
			"updatedBy": "ID",
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID",
			"isActive": true
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Update Agentoverride API

[Default update API] — This is the designated default update API for the sys_agentOverride data object. Frontend generators and AI agents should use this API for standard CRUD operations.

Rest Route

The updateAgentOverride API REST controller can be triggered via the following route:

/v1/agentoverride/:sys_agentOverrideId

Rest Request Parameters

The updateAgentOverride api has got 10 regular request parameters

Parameter Type Required Population
sys_agentOverrideId ID true request.params?.[“sys_agentOverrideId”]
provider String request.body?.[“provider”]
model String request.body?.[“model”]
systemPrompt Text request.body?.[“systemPrompt”]
temperature Double request.body?.[“temperature”]
maxTokens Integer request.body?.[“maxTokens”]
responseFormat String request.body?.[“responseFormat”]
selectedTools Object request.body?.[“selectedTools”]
guardrails Object request.body?.[“guardrails”]
enabled Boolean request.body?.[“enabled”]
sys_agentOverrideId : This id paremeter is used to select the required data object that will be updated
provider : Override AI provider (e.g., openai, anthropic).
model : Override model name.
systemPrompt : Override system prompt.
temperature : Override temperature (0-2).
maxTokens : Override max tokens.
responseFormat : Override response format (text/json).
selectedTools : Array of tool names from the catalog that this agent can use.
guardrails : Override guardrails: { maxToolCalls, timeout, maxTokenBudget }.
enabled : Enable or disable this agent.

REST Request To access the api you can use the REST controller with the path PATCH /v1/agentoverride/:sys_agentOverrideId

  axios({
    method: 'PATCH',
    url: `/v1/agentoverride/${sys_agentOverrideId}`,
    data: {
            provider:"String",  
            model:"String",  
            systemPrompt:"Text",  
            temperature:"Double",  
            maxTokens:"Integer",  
            responseFormat:"String",  
            selectedTools:"Object",  
            guardrails:"Object",  
            enabled:"Boolean",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_agentOverride",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"sys_agentOverride": {
		"id": "ID",
		"agentName": "String",
		"provider": "String",
		"model": "String",
		"systemPrompt": "Text",
		"temperature": "Double",
		"maxTokens": "Integer",
		"responseFormat": "String",
		"selectedTools": "Object",
		"guardrails": "Object",
		"enabled": "Boolean",
		"updatedBy": "ID",
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"isActive": true
	}
}

Create Agentoverride API

[Default create API] — This is the designated default create API for the sys_agentOverride data object. Frontend generators and AI agents should use this API for standard CRUD operations.

Rest Route

The createAgentOverride API REST controller can be triggered via the following route:

/v1/agentoverride

Rest Request Parameters

The createAgentOverride api has got 9 regular request parameters

Parameter Type Required Population
agentName String true request.body?.[“agentName”]
provider String false request.body?.[“provider”]
model String false request.body?.[“model”]
systemPrompt Text false request.body?.[“systemPrompt”]
temperature Double false request.body?.[“temperature”]
maxTokens Integer false request.body?.[“maxTokens”]
responseFormat String false request.body?.[“responseFormat”]
selectedTools Object false request.body?.[“selectedTools”]
guardrails Object false request.body?.[“guardrails”]
agentName : Design-time agent name this override applies to.
provider : Override AI provider (e.g., openai, anthropic).
model : Override model name.
systemPrompt : Override system prompt.
temperature : Override temperature (0-2).
maxTokens : Override max tokens.
responseFormat : Override response format (text/json).
selectedTools : Array of tool names from the catalog that this agent can use.
guardrails : Override guardrails: { maxToolCalls, timeout, maxTokenBudget }.

REST Request To access the api you can use the REST controller with the path POST /v1/agentoverride

  axios({
    method: 'POST',
    url: '/v1/agentoverride',
    data: {
            agentName:"String",  
            provider:"String",  
            model:"String",  
            systemPrompt:"Text",  
            temperature:"Double",  
            maxTokens:"Integer",  
            responseFormat:"String",  
            selectedTools:"Object",  
            guardrails:"Object",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_agentOverride",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"sys_agentOverride": {
		"id": "ID",
		"agentName": "String",
		"provider": "String",
		"model": "String",
		"systemPrompt": "Text",
		"temperature": "Double",
		"maxTokens": "Integer",
		"responseFormat": "String",
		"selectedTools": "Object",
		"guardrails": "Object",
		"enabled": "Boolean",
		"updatedBy": "ID",
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"isActive": true
	}
}

Delete Agentoverride API

[Default delete API] — This is the designated default delete API for the sys_agentOverride data object. Frontend generators and AI agents should use this API for standard CRUD operations.

Rest Route

The deleteAgentOverride API REST controller can be triggered via the following route:

/v1/agentoverride/:sys_agentOverrideId

Rest Request Parameters

The deleteAgentOverride api has got 1 regular request parameter

Parameter Type Required Population
sys_agentOverrideId ID true request.params?.[“sys_agentOverrideId”]
sys_agentOverrideId : This id paremeter is used to select the required data object that will be deleted

REST Request To access the api you can use the REST controller with the path DELETE /v1/agentoverride/:sys_agentOverrideId

  axios({
    method: 'DELETE',
    url: `/v1/agentoverride/${sys_agentOverrideId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_agentOverride",
	"method": "DELETE",
	"action": "delete",
	"appVersion": "Version",
	"rowCount": 1,
	"sys_agentOverride": {
		"id": "ID",
		"agentName": "String",
		"provider": "String",
		"model": "String",
		"systemPrompt": "Text",
		"temperature": "Double",
		"maxTokens": "Integer",
		"responseFormat": "String",
		"selectedTools": "Object",
		"guardrails": "Object",
		"enabled": "Boolean",
		"updatedBy": "ID",
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"isActive": false
	}
}

List Toolcatalog API

[Default list API] — This is the designated default list API for the sys_toolCatalog data object. Frontend generators and AI agents should use this API for standard CRUD operations.

Rest Route

The listToolCatalog API REST controller can be triggered via the following route:

/v1/toolcatalog

Rest Request Parameters

Filter Parameters

The listToolCatalog api supports 1 optional filter parameter for filtering list results:

serviceName (String): Source service name.

REST Request To access the api you can use the REST controller with the path GET /v1/toolcatalog

  axios({
    method: 'GET',
    url: '/v1/toolcatalog',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section above)
        // serviceName: '<value>' // Filter by serviceName
            }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_toolCatalogs",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"sys_toolCatalogs": [
		{
			"id": "ID",
			"toolName": "String",
			"serviceName": "String",
			"description": "Text",
			"parameters": "Object",
			"lastRefreshed": "Date",
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID",
			"isActive": true
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Get Toolcatalogentry API

[Default get API] — This is the designated default get API for the sys_toolCatalog data object. Frontend generators and AI agents should use this API for standard CRUD operations.

Rest Route

The getToolCatalogEntry API REST controller can be triggered via the following route:

/v1/toolcatalogentry/:sys_toolCatalogId

Rest Request Parameters

The getToolCatalogEntry api has got 1 regular request parameter

Parameter Type Required Population
sys_toolCatalogId ID true request.params?.[“sys_toolCatalogId”]
sys_toolCatalogId : This id paremeter is used to query the required data object.

REST Request To access the api you can use the REST controller with the path GET /v1/toolcatalogentry/:sys_toolCatalogId

  axios({
    method: 'GET',
    url: `/v1/toolcatalogentry/${sys_toolCatalogId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_toolCatalog",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"sys_toolCatalog": {
		"id": "ID",
		"toolName": "String",
		"serviceName": "String",
		"description": "Text",
		"parameters": "Object",
		"lastRefreshed": "Date",
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"isActive": true
	}
}

List Agentexecutions API

[Default list API] — This is the designated default list API for the sys_agentExecution data object. Frontend generators and AI agents should use this API for standard CRUD operations.

Rest Route

The listAgentExecutions API REST controller can be triggered via the following route:

/v1/agentexecutions

Rest Request Parameters

Filter Parameters

The listAgentExecutions api supports 5 optional filter parameters for filtering list results:

agentName (String): Agent that was executed.

agentType (Enum): Whether this was a design-time or dynamic agent.

source (Enum): How the agent was triggered.

userId (ID): User who triggered the execution.

status (Enum): Execution status.

REST Request To access the api you can use the REST controller with the path GET /v1/agentexecutions

  axios({
    method: 'GET',
    url: '/v1/agentexecutions',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section above)
        // agentName: '<value>' // Filter by agentName
        // agentType: '<value>' // Filter by agentType
        // source: '<value>' // Filter by source
        // userId: '<value>' // Filter by userId
        // status: '<value>' // Filter by status
            }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_agentExecutions",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"sys_agentExecutions": [
		{
			"id": "ID",
			"agentName": "String",
			"agentType": "Enum",
			"agentType_idx": "Integer",
			"source": "Enum",
			"source_idx": "Integer",
			"userId": "ID",
			"input": "Object",
			"output": "Object",
			"toolCalls": "Integer",
			"tokenUsage": "Object",
			"durationMs": "Integer",
			"status": "Enum",
			"status_idx": "Integer",
			"error": "Text",
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID",
			"isActive": true
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Get Agentexecution API

[Default get API] — This is the designated default get API for the sys_agentExecution data object. Frontend generators and AI agents should use this API for standard CRUD operations.

Rest Route

The getAgentExecution API REST controller can be triggered via the following route:

/v1/agentexecution/:sys_agentExecutionId

Rest Request Parameters

The getAgentExecution api has got 1 regular request parameter

Parameter Type Required Population
sys_agentExecutionId ID true request.params?.[“sys_agentExecutionId”]
sys_agentExecutionId : This id paremeter is used to query the required data object.

REST Request To access the api you can use the REST controller with the path GET /v1/agentexecution/:sys_agentExecutionId

  axios({
    method: 'GET',
    url: `/v1/agentexecution/${sys_agentExecutionId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_agentExecution",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"sys_agentExecution": {
		"id": "ID",
		"agentName": "String",
		"agentType": "Enum",
		"agentType_idx": "Integer",
		"source": "Enum",
		"source_idx": "Integer",
		"userId": "ID",
		"input": "Object",
		"output": "Object",
		"toolCalls": "Integer",
		"tokenUsage": "Object",
		"durationMs": "Integer",
		"status": "Enum",
		"status_idx": "Integer",
		"error": "Text",
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"isActive": true
	}
}

After this prompt, the user may give you new instructions to update the output of this prompt or provide subsequent prompts about the project.


Auth Service

Service Design Specification

Service Design Specification

Athentication documentation -Version:1.0.9

Scope

This document provides a structured architectural overview of the authentication module of the project.The authentication module of the project is used to generate authentication and authorization specific code for all services but a more specific purpose of the module is also to store all required configuration to generate an automatic user service for the project which is named ‘auteurlabb-auth-service’.

So in this document you will find

This document has been automatically generated based on the authetication module definition within Mindbricks, ensuring that the information reflects the source of truth used during code generation and deployment.

The document is intended to serve multiple audiences:

Note for Frontend Developers: While this document is valuable for understanding business logic and data interactions, please refer to the Service API Documentation for endpoint-level specifications and integration details.

Note for Backend Developers: Since the code for this service is automatically generated by Mindbricks, you typically won’t need to implement or modify it manually. However, this document is especially valuable when you’re building other services—whether within Mindbricks or externally—that need to interact with or depend on this service. It provides a clear reference to the service’s data contracts, business rules, and API structure, helping ensure compatibility and correct integration.

This service is accessible via the following environment-specific URLs:

Authentication Essentials

Mindbricks provides a comprehensive authentication module that serves as the foundation for user management and security across all services. This module is designed to be flexible, allowing for the generation of authentication and authorization code tailored to project’s specific needs. Mindbricks supports multiple authentication strategies, for the first validation of the user, the auth service supports the following authentication strategies:

JWT tokens are generated by the auth service and can be used to access protected resources of the service. The JWT token is open and contains the user’s identity and any additional claims required for authorization. The token is signed using a private RSA key, ensuring its integrity and authenticity. Once the JWT token is generated, it can be used to access protected resources of the service.

The JWT token is structured as follows:

{
  "keyId": "716a8738ec3d499f84d58bda6ee772ce",
  "sessionId": "9cf23fa8-07d4-4e7c-80a6-ec6d6ac96bb9",
  "userId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38",
  "sub": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38",
  loginDate: "2023-10-01T12:00:00Z"
}

Key id for a token represents the private-public key pair used to sign the token. To validate the signature of the token, the public key is used. Any service which will use the JWT token can request a publick ket from the auth service using the following endpoint:

GET /publickey?keyId=[keyIdInToken]

Mindbricks generated services manages the key rotation automatically, so the public key is always up to date and valid for the JWT tokens generated by the auth service. If you add any manual service to the project which should validate the JWT token, you can use the public key endpoint to get the public key and validate the JWT token signature.

The JWT token life cycle is configured in the authentication module of the project. This project uses the following configuration for the JWT token: The token is valid for days after it is issued. And the private key used to sign the token is rotated every days.

Note that when a new key is generated to sign the JWT tokens, the old key is still valid for the period of days. So it is recommended to cache the old public keys for the period of days to validate the JWT tokens issued with the old keys.

The Login Definition

The login definition is a crucial part of the authentication module, as it defines how user and tenant model is defined. In this section it is specified how users, user groups, and tenants are defined in the project’s data model. These definitions allow Mindbricks to dynamically extract identity and authorization data from project-specific data objects.

User Settings

Super Admin Identifier: admin@admin.com The login email of the super admin user. This user has full permissions across the project and is not tenant-scoped. When primaryLoginIdentifier is ‘email’ or ‘emailOrMobile’, this should be an email address. When it is ‘mobile’, this should be a mobile number in E.164 format.

Super admin user is created automatically when the project is initialized with a roleId of superAdmin and a userId of f7103b85-fcda-4dec-92c6-c336f71fd3a2. The primary identifier field is populated with superAdminIdentifier and marked as verified. When the secondary identifier field is required (secondaryIdentifierPresence: "required" or dualIdentifierRegistration: "both"), a placeholder value is used ("noreply@system.local" for email, "+10000000000" for mobile) to satisfy the NOT NULL constraint.

Super Admin User Password: Super admin user password is defined in this module as well, but masked in this document. To edit it you can use the User Settings section of Login Definition chapter of the Mindbricks Authentication Module.

Username Type: The type of the username which is stored in the database and written to the session object for information purposes.: -asFullName: The username is stored in one property, fullname, and represents the full name of the user, which is a combination of first name and last name. -asNamePair: The username is stored in two properties, name and surname, which are combined to form the full name of the user.

This project uses the asFullName type, so the user name is stored in one property, fullname, and represents the full name of the user, which is a combination of first name and last name.

User Groups: The project does not support user groups, so the auth service will not create any user group related data objects.

Public User Registration: The project allows public user registration, meaning that users can register themselves without the need for an admin to create an account for them. This is useful for projects that require user self-registration, such as social networks, forums, or any application where users need to create their own accounts. The user registration process is handled by the auth service, which will create a new user data object in the database. The user registration process will create a new user with the userId and roleId set to user, and the user will be able to log in using the username and password they provided during registration. The reigstered user’s roleId will be updated later to any other roleId by the super admin or admin users. If any social login is enabled for the project, the user can also sign up using the social login providers. Note that when users register themselves using socila logi, first all the data that can be provided by the social login provider will written to Redis cache with a key called socialCode, and this code will be returned to the api consumer, which can be used to complete the registration process.

Email Verification Is Not Required For Login: The project does not require email verification for user login, meaning that users can log in without verifying their email address. This is useful for projects that do not require email verification, such as enterprise applications, internal tools, or any application where email verification is not required. The email verification process is not handled by the auth service, and users can log in without verifying their email address. While the email verification is not required, the aut service will still support email verification if it is configured in the verification services. You can prefer email verification at any time before any action or make it optional which means that users can verify their email address if they want to, but it is not required for login. You can check the email verification details in the REST API documentation of the auth service.

Email 2FA Is Not Required For Login: The project does not require email-based two-factor authentication (2FA) for user login, meaning that users can log in using only their username and password without providing a second factor of authentication. This is useful for projects that do not require an additional layer of security for user login, such as enterprise applications, internal tools, or any application where email-based 2FA is not required. While the email 2FA is not required, the auth service will still support email 2FA if it is configured in the verification services. You can prefer email 2FA at any time before any action or make it optional which means that users can provide a second factor of authentication if they want to, but it is not required for login. You can check the email 2FA details in the REST API documentation of the auth service.

User Mobile Is Not Active: The authetication module is not configured to support mobile numbers for users.

User Auto Avatar Script: Mindbricks stores an avatar property inthe user data model automatically. This project supports also automatic avatar generation for users with the following script configuretion. The auth service will generate an avatar for each user when it is not specified in the registration process.

The script is defined in the authentication module and can be edited in the User Settings section of Login Definition chapter of the Mindbricks Authentication Module. The script is executed when a new user is created, and it generates an avatar based on user properties.

`https://gravatar.com/avatar/${LIB.common.md5(this.email ?? 'nullValue')}?s=200&d=identicon`

Tenant Settings

This project is not configured to support multi-tenancy, meaning that users and other data are not scoped to a specific tenant. This allows for a single-tenant data management, where all users and other data are shared across the project.

Verification Services

The project supports various verification services that enhance security and user experience. These services are designed to verify user identity through different channels, such as email and mobile, and can be configured to suit the project’s needs. Please check the auth service API documentation for more details on how to use these services through the REST API.

A verification service is configured with the following settings: -verificationType: The type of verification handling, which can be one of the following: – byCode: The verification is handled by entering a code in the frontend. – byLink: The verification is handled by clicking a link in the frontend, which will automatically verify the user through the auth service. -resendTimeWindow: The time window in seconds during which the user can request a new verification code or link. -expireTimeWindow: The time window in seconds after which the verification code or link will expire and become invalid.

Password Reset By Email

The project supports password reset by email, allowing users to reset their passwords securely through a verification code sent to their registered email address. This service is useful for projects that require users to reset their passwords securely, such as social networks, forums, or any application where password reset is required. The password reset by email process is handled by the auth service, which will send a verification code to the user’s email address after they request a password reset.

{
    verificationType: "byCode",
    resendTimeWindow: 60,
    expireTimeWindow: 86400
}

Password Reset By Mobile

The project supports password reset by mobile, allowing users to reset their passwords securely through a verification code sent to their registered mobile number. This service is useful for projects that require users to reset their passwords securely, such as social networks, forums, or any application where password reset is required. The password reset by mobile process is handled by the auth service, which will send a verification code to the user’s mobile number after they request a password reset.

{
    verificationType: "byCode",
    resendTimeWindow: 60,
    expireTimeWindow: 300
}

Email Verification

The project supports email verification, allowing users to verify their email addresses securely through a verification code sent to their registered email address. This service is useful for projects that require users to verify their email addresses securely, such as social networks, forums, or any application where email verification is required. The email verification process is handled by the auth service, which will send a verification code to the user’s email address after they register or change their email address.

{
    verificationType: "byCode",
    resendTimeWindow: 60,
    expireTimeWindow: 86400
}

Mobile Verification

The project supports mobile verification, allowing users to verify their mobile numbers securely through a verification code sent to their registered mobile number. This service is useful for projects that require users to verify their mobile numbers securely, such as social networks, forums, or any application where mobile verification is required. The mobile verification process is handled by the auth service, which will send a verification code to the user’s mobile number after they register or change their mobile number.

{      
    verificationType: "byCode",
    resendTimeWindow: 60,
    expireTimeWindow: 300
}

Email 2FA

The project supports email-based two-factor authentication (2FA), allowing users to enhance their login security by providing a second factor of authentication, such as a verification code sent to their registered email address. This service is useful for projects that require an additional layer of security for user login, such as social networks, forums, or any application where email-based 2FA is required. The email 2FA process is handled by the auth service, which will send a verification code to the user’s email address after they log in. The user must provide the verification code to complete the login process.

{
    verificationType: "byCode",
    resendTimeWindow: 60,      
    expireTimeWindow: 86400
}

Mobile 2FA

The project supports mobile-based two-factor authentication (2FA), allowing users to enhance their login security by providing a second factor of authentication, such as a verification code sent to their registered mobile number. This service is useful for projects that require an additional layer of security for user login, such as
social networks, forums, or any application where mobile-based 2FA is required. The mobile 2FA process is handled by the auth service, which will send a verification code to the user’s mobile number after they log in. The user must provide the verification code to complete the login process.

{
    verificationType: "byCode",
    resendTimeWindow: 60,
    expireTimeWindow: 300
}       

Access Control

The project supports Role-Based Access Control (RBAC) to manage user roles effectively. RBAC allows for defining roles and limiting resource access with these roles to enable a structured approach to access control.

Role-Based Access Control (RBAC)

RBAC is implemented to manage user roles and their associated permissions. Roles in Mindbricks are defined in design time and transferred to the generated code as hardcoded. Roles are used to group users and assign api access rights to these groups, allowing for efficient management of user access across the project. The roles are defined in the Access Control chapter of authentication module and can be edited in the Role Settings section.

The superAdmin, admin, and user roles are created automatically by the auth service, and they are used to manage user access across the project. The superadmin role has full access to all resources, while the admin role has limited access to resources based on the permissions assigned to it. The user role is the default role for all users, and it has limited access to resources based on the permissions assigned to it.

Along with the default roles, this project also configured to have the following roles: filmmaker studio investor normalUser

The roles object is a hardcoded object in the generated code, and it contains the following roles:

{
  "superAdmin": "'superAdmin'",
  "admin": "'admin'",
  "user": "'user'",
  "filmmaker": "'filmmaker'",
  "studio": "'studio'",
  "investor": "'investor'",
  "normalUser": "'normalUser'"
}

Social Logins (Not Configured)

The project does not support any social logins, meaning that users cannot log in using their social media accounts. If you want to add social logins, you can do so in the Social Logins chapter of Mindbricks Authentication Module.

User Properties

approvalStatus

The project supports above user properties, allowing for the storage of additional user information beyond the default properties. User properties are defined in the User Properties chapter of authentication module and can be edited in the User Properties section. These properties can be used to store additional information about users, such as preferences, settings, or any other custom data that is relevant to the project. User properties are stored in the user data object, and they can be accessed and modified through the auth service API.

To see a detailed configuretion of the user properties, please check the User Data Object docmentation below.

Auth Service Data Objects

The service uses a PostgreSQL database for data storage, with the database name set to auteurlabb-auth-service.

Data deletion is managed using a soft delete strategy. Instead of removing records from the database, they are flagged as inactive by setting the isActive field to false.

Object Name Description Public Access
user A data object that stores the user information and handles login settings. accessPrivate
userAvatarsFile Auto-generated file storage for the userAvatars database bucket. Files are stored as BYTEA in PostgreSQL. accessPublic

user Data Object

Object Overview

Description: A data object that stores the user information and handles login settings.

This object represents a core data structure within the service and acts as the blueprint for database interaction, API generation, and business logic enforcement. It is defined using the ObjectSettings pattern, which governs its behavior, access control, caching strategy, and integration points with other systems such as Stripe and Redis.

Core Configuration

Redis Entity Caching

This data object is configured for Redis entity caching, which improves data retrieval performance by storing frequently accessed data in Redis. Each time a new instance is created, updated or deleted, the cache is updated accordingly. Any get requests by id will first check the cache before querying the database. If you want to use the cache by other select criteria, you can configure any data property as a Redis cluster.

Properties Schema

Property Type Required Description
email String Yes A string value to represent the user's email.
password String Yes A string value to represent the user's password. It will be stored as hashed.
fullname String Yes A string value to represent the fullname of the user
avatar String No The avatar url of the user. A random avatar will be generated if not provided
roleId String Yes A string value to represent the roleId of the user.
emailVerified Boolean Yes A boolean value to represent the email verification status of the user.
approvalStatus Enum No Admin approval status for the user account (pending, approved, rejected).

Default Values

Default values are automatically assigned to properties when a new object is created, if no value is provided in the request body. Since default values are applied on db level, they should be literal values, not expressions.If you want to use expressions, you can use transposed parameters in any business API to set default values dynamically.

Always Create with Default Values

Some of the default values are set to be always used when creating a new object, even if the property value is provided in the request body. It ensures that the property is always initialized with a default value when the object is created.

Constant Properties

email

Constant properties are defined to be immutable after creation, meaning they cannot be updated or changed once set. They are typically used for properties that should remain constant throughout the object’s lifecycle. A property is set to be constant if the Allow Update option is set to false.

Auto Update Properties

fullname avatar approvalStatus

An update crud API created with the option Auto Params enabled will automatically update these properties with the provided values in the request body. If you want to update any property in your own business logic not by user input, you can set the Allow Auto Update option to false. These properties will be added to the update API’s body parameters and can be updated by the user if any value is provided in the request body.

Hashed Properties

password

Hashed properties are stored in the database as a hash value, providing an additional layer of security for sensitive data.

Enum Properties

Enum properties are defined with a set of allowed values, ensuring that only valid options can be assigned to them. The enum options value will be stored as strings in the database, but when a data object is created an addtional property with the same name plus an idx suffix will be created, which will hold the index of the selected enum option. You can use the index property to sort by the enum value or when your enum options represent a sequence of values.

Elastic Search Indexing

email fullname roleId emailVerified approvalStatus

Properties that are indexed in Elastic Search will be searchable via the Elastic Search API. While all properties are stored in the elastic search index of the data object, only those marked for Elastic Search indexing will be available for search queries.

Database Indexing

email

Properties that are indexed in the database will be optimized for query performance, allowing for faster data retrieval. Make a property indexed in the database if you want to use it frequently in query filters or sorting.

Unique Properties

email

Unique properties are enforced to have distinct values across all instances of the data object, preventing duplicate entries. Note that a unique property is automatically indexed in the database so you will not need to set the Indexed in DB option.

Cache Select Properties

email

Cache select properties are used to collect data from Redis entity cache with a different key than the data object id. This allows you to cache data that is not directly related to the data object id, but a frequently used filter.

Secondary Key Properties

email

Secondary key properties are used to create an additional indexed identifiers for the data object, allowing for alternative access patterns. Different than normal indexed properties, secondary keys will act as primary keys and Mindbricks will provide automatic secondary key db utility functions to access the data object by the secondary key.

Filter Properties

email fullname roleId

Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API’s that have “Auto Params” enabled.

userAvatarsFile Data Object

Object Overview

Description: Auto-generated file storage for the userAvatars database bucket. Files are stored as BYTEA in PostgreSQL.

This object represents a core data structure within the service and acts as the blueprint for database interaction, API generation, and business logic enforcement. It is defined using the ObjectSettings pattern, which governs its behavior, access control, caching strategy, and integration points with other systems such as Stripe and Redis.

Core Configuration

Properties Schema

Property Type Required Description
fileName String Yes Original file name as uploaded by the client.
mimeType String Yes MIME type of the uploaded file (e.g., image/png, application/pdf).
fileSize Integer Yes File size in bytes.
accessKey String Yes 12-character random key for shareable access. Auto-generated on upload.
ownerId ID No ID of the user who uploaded the file (from session).
fileData Blob Yes Binary file content. Stored as BYTEA in PostgreSQL or Buffer in MongoDB.
metadata Object No Optional JSON metadata for the file (tags, alt text, etc.).
userId ID No Reference to the owner user record.

Default Values

Default values are automatically assigned to properties when a new object is created, if no value is provided in the request body. Since default values are applied on db level, they should be literal values, not expressions.If you want to use expressions, you can use transposed parameters in any business API to set default values dynamically.

Constant Properties

fileName mimeType fileSize accessKey ownerId fileData userId

Constant properties are defined to be immutable after creation, meaning they cannot be updated or changed once set. They are typically used for properties that should remain constant throughout the object’s lifecycle. A property is set to be constant if the Allow Update option is set to false.

Auto Update Properties

fileName mimeType fileSize accessKey ownerId fileData metadata userId

An update crud API created with the option Auto Params enabled will automatically update these properties with the provided values in the request body. If you want to update any property in your own business logic not by user input, you can set the Allow Auto Update option to false. These properties will be added to the update API’s body parameters and can be updated by the user if any value is provided in the request body.

Elastic Search Indexing

fileName mimeType fileSize ownerId userId

Properties that are indexed in Elastic Search will be searchable via the Elastic Search API. While all properties are stored in the elastic search index of the data object, only those marked for Elastic Search indexing will be available for search queries.

Database Indexing

fileName mimeType accessKey ownerId userId

Properties that are indexed in the database will be optimized for query performance, allowing for faster data retrieval. Make a property indexed in the database if you want to use it frequently in query filters or sorting.

Unique Properties

accessKey

Unique properties are enforced to have distinct values across all instances of the data object, preventing duplicate entries. Note that a unique property is automatically indexed in the database so you will not need to set the Indexed in DB option.

Session Data Properties

ownerId

Session data properties are used to store data that is specific to the user session, allowing for personalized experiences and temporary data storage. If a property is configured as session data, it will be automatically mapped to the related field in the user session during CRUD operations. Note that session data properties can not be mutated by the user, but only by the system.

This property is also used to store the owner of the session data, allowing for ownership checks and access control.

Filter Properties

mimeType ownerId userId

Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API’s that have “Auto Params” enabled.


REST API GUIDE

REST API GUIDE

auteurlabb-auth-service

Version: 1.0.9

Authentication service for the project

Architectural Design Credit and Contact Information

The architectural design of this microservice is credited to . For inquiries, feedback, or further information regarding the architecture, please direct your communication to:

Email:

We encourage open communication and welcome any questions or discussions related to the architectural aspects of this microservice.

Documentation Scope

Welcome to the official documentation for the Auth Service’s REST API. This document is designed to provide a comprehensive guide to interfacing with our Auth Service exclusively through RESTful API endpoints.

Intended Audience

This documentation is intended for developers and integrators who are looking to interact with the Auth Service via HTTP requests for purposes such as creating, updating, deleting and querying Auth objects.

Overview

Within these pages, you will find detailed information on how to effectively utilize the REST API, including authentication methods, request and response formats, endpoint descriptions, and examples of common use cases.

Beyond REST It’s important to note that the Auth Service also supports alternative methods of interaction, such as gRPC and messaging via a Message Broker. These communication methods are beyond the scope of this document. For information regarding these protocols, please refer to their respective documentation.

Authentication And Authorization

To ensure secure access to the Auth service’s protected endpoints, a project-wide access token is required. This token serves as the primary method for authenticating requests to our service. However, it’s important to note that access control varies across different routes:

Protected API: Certain API (routes) require specific authorization levels. Access to these routes is contingent upon the possession of a valid access token that meets the route-specific authorization criteria. Unauthorized requests to these routes will be rejected.

**Public API **: The service also includes public API (routes) that are accessible without authentication. These public endpoints are designed for open access and do not require an access token.

Token Locations

When including your access token in a request, ensure it is placed in one of the following specified locations. The service will sequentially search these locations for the token, utilizing the first one it encounters.

Location Token Name / Param Name
Query access_token
Authorization Header Bearer
Header auteurlabb-access-token
Cookie auteurlabb-access-token

Please ensure the token is correctly placed in one of these locations, using the appropriate label as indicated. The service prioritizes these locations in the order listed, processing the first token it successfully identifies.

Api Definitions

This section outlines the API endpoints available within the Auth service. Each endpoint can receive parameters through various methods, meticulously described in the following definitions. It’s important to understand the flexibility in how parameters can be included in requests to effectively interact with the Auth service.

This service is configured to listen for HTTP requests on port 3011, serving both the main API interface and default administrative endpoints.

The following routes are available by default:

This service is accessible via the following environment-specific URLs:

Parameter Inclusion Methods: Parameters can be incorporated into API requests in several ways, each with its designated location. Understanding these methods is crucial for correctly constructing your requests:

Query Parameters: Included directly in the URL’s query string.

Path Parameters: Embedded within the URL’s path.

Body Parameters: Sent within the JSON body of the request.

Session Parameters: Automatically read from the session object. This method is used for parameters that are intrinsic to the user’s session, such as userId. When using an API that involves session parameters, you can omit these from your request. The service will automatically bind them to the API layer, provided that a session is associated with your request.

Note on Session Parameters: Session parameters represent a unique method of parameter inclusion, relying on the context of the user’s session. A common example of a session parameter is userId, which the service automatically associates with your request when a session exists. This feature ensures seamless integration of user-specific data without manual input for each request.

By adhering to the specified parameter inclusion methods, you can effectively utilize the Auth service’s API endpoints. For detailed information on each endpoint, including required parameters and their accepted locations, refer to the individual API definitions below.

Common Parameters

The Auth service’s business API support several common parameters designed to modify and enhance the behavior of API requests. These parameters are not individually listed in the API route definitions to avoid repetition. Instead, refer to this section to understand how to leverage these common behaviors across different routes. Note that all common parameters should be included in the query part of the URL.

Supported Common Parameters:

By utilizing these common parameters, you can tailor the behavior of API requests to suit your specific requirements, ensuring optimal performance and usability of the Auth service.

Error Response

If a request encounters an issue, whether due to a logical fault or a technical problem, the service responds with a standardized JSON error structure. The HTTP status code within this response indicates the nature of the error, utilizing commonly recognized codes for clarity:

Each error response is structured to provide meaningful insight into the problem, assisting in diagnosing and resolving issues efficiently.

{
  "result": "ERR",
  "status": 400,
  "message": "errMsg_organizationIdisNotAValidID",
  "errCode": 400,
  "date": "2024-03-19T12:13:54.124Z",
  "detail": "String"
}

Object Structure of a Successfull Response

When the Auth service processes requests successfully, it wraps the requested resource(s) within a JSON envelope. This envelope not only contains the data but also includes essential metadata, such as configuration details and pagination information, to enrich the response and provide context to the client.

Key Characteristics of the Response Envelope:

Design Considerations: The structure of a API’s response data is meticulously crafted during the service’s architectural planning. This design ensures that responses adequately reflect the intended data relationships and service logic, providing clients with rich and meaningful information.

Brief Data: Certain API’s return a condensed version of the object data, intentionally selecting only specific fields deemed useful for that request. In such instances, the API documentation will detail the properties included in the response, guiding developers on what to expect.

API Response Structure

The API utilizes a standardized JSON envelope to encapsulate responses. This envelope is designed to consistently deliver both the requested data and essential metadata, ensuring that clients can efficiently interpret and utilize the response.

HTTP Status Codes:

Success Response Format:

For successful operations, the response includes a "status": "OK" property, signaling the successful execution of the request. The structure of a successful response is outlined below:

{
  "status":"OK",
  "statusCode": 200,   
  "elapsedMs":126,
  "ssoTime":120,
  "source": "db",
  "cacheKey": "hexCode",
  "userId": "ID",
  "sessionId": "ID",
  "requestId": "ID",
  "dataName":"products",
  "method":"GET",
  "action":"list",
  "appVersion":"Version",
  "rowCount":3
  "products":[{},{},{}],
  "paging": {
    "pageNumber":1, 
    "pageRowCount":25, 
    "totalRowCount":3,
    "pageCount":1
  },
  "filters": [],
  "uiPermissions": []
}

Handling Errors:

For details on handling error scenarios and understanding the structure of error responses, please refer to the “Error Response” section provided earlier in this documentation. It outlines how error conditions are communicated, including the use of HTTP status codes and standardized JSON structures for error messages.

Resources

Auth service provides the following resources which are stored in its own database as a data object. Note that a resource for an api access is a data object for the service.

User resource

Resource Definition : A data object that stores the user information and handles login settings. User Resource Properties

Name Type Required Default Definition
email String * A string value to represent the user's email.*
password String * A string value to represent the user's password. It will be stored as hashed.*
fullname String A string value to represent the fullname of the user
avatar String The avatar url of the user. A random avatar will be generated if not provided
roleId String A string value to represent the roleId of the user.
emailVerified Boolean A boolean value to represent the email verification status of the user.
approvalStatus Enum Admin approval status for the user account (pending, approved, rejected).

Enum Properties

Enum properties are represented as strings in the database. The values are mapped to their corresponding names in the application layer.

approvalStatus Enum Property

Property Definition : Admin approval status for the user account (pending, approved, rejected).Enum Options

Name Value Index
pending "pending"" 0
approved "approved"" 1
rejected "rejected"" 2

UserAvatarsFile resource

Resource Definition : Auto-generated file storage for the userAvatars database bucket. Files are stored as BYTEA in PostgreSQL. UserAvatarsFile Resource Properties

Name Type Required Default Definition
fileName String Original file name as uploaded by the client.
mimeType String MIME type of the uploaded file (e.g., image/png, application/pdf).
fileSize Integer File size in bytes.
accessKey String 12-character random key for shareable access. Auto-generated on upload.
ownerId ID ID of the user who uploaded the file (from session).
fileData Blob Binary file content. Stored as BYTEA in PostgreSQL or Buffer in MongoDB.
metadata Object Optional JSON metadata for the file (tags, alt text, etc.).
userId ID Reference to the owner user record.

Business Api

Get User API

This api is used by admin roles or the users themselves to get the user profile information.

Rest Route

The getUser API REST controller can be triggered via the following route:

/v1/users/:userId

Rest Request Parameters

The getUser api has got 1 regular request parameter

Parameter Type Required Population
userId ID true request.params?.[“userId”]
userId : This id paremeter is used to query the required data object.

REST Request To access the api you can use the REST controller with the path GET /v1/users/:userId

  axios({
    method: 'GET',
    url: `/v1/users/${userId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "user",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"user": {
		"id": "ID",
		"email": "String",
		"password": "String",
		"fullname": "String",
		"avatar": "String",
		"roleId": "String",
		"emailVerified": "Boolean",
		"approvalStatus": "Enum",
		"approvalStatus_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Update User API

This route is used by admins to update user profiles.

Rest Route

The updateUser API REST controller can be triggered via the following route:

/v1/users/:userId

Rest Request Parameters

The updateUser api has got 4 regular request parameters

Parameter Type Required Population
userId ID true request.params?.[“userId”]
fullname String false request.body?.[“fullname”]
avatar String false request.body?.[“avatar”]
approvalStatus Enum false request.body?.[“approvalStatus”]
userId : This id paremeter is used to select the required data object that will be updated
fullname : A string value to represent the fullname of the user
avatar : The avatar url of the user. A random avatar will be generated if not provided
approvalStatus : Admin approval status for the user account (pending, approved, rejected).

REST Request To access the api you can use the REST controller with the path PATCH /v1/users/:userId

  axios({
    method: 'PATCH',
    url: `/v1/users/${userId}`,
    data: {
            fullname:"String",  
            avatar:"String",  
            approvalStatus:"Enum",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "user",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"user": {
		"id": "ID",
		"email": "String",
		"password": "String",
		"fullname": "String",
		"avatar": "String",
		"roleId": "String",
		"emailVerified": "Boolean",
		"approvalStatus": "Enum",
		"approvalStatus_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Update Profile API

This route is used by users to update their profiles.

Rest Route

The updateProfile API REST controller can be triggered via the following route:

/v1/profile/:userId

Rest Request Parameters

The updateProfile api has got 4 regular request parameters

Parameter Type Required Population
userId ID true request.params?.[“userId”]
fullname String false request.body?.[“fullname”]
avatar String false request.body?.[“avatar”]
approvalStatus Enum false request.body?.[“approvalStatus”]
userId : This id paremeter is used to select the required data object that will be updated
fullname : A string value to represent the fullname of the user
avatar : The avatar url of the user. A random avatar will be generated if not provided
approvalStatus : Admin approval status for the user account (pending, approved, rejected).

REST Request To access the api you can use the REST controller with the path PATCH /v1/profile/:userId

  axios({
    method: 'PATCH',
    url: `/v1/profile/${userId}`,
    data: {
            fullname:"String",  
            avatar:"String",  
            approvalStatus:"Enum",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "user",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"user": {
		"id": "ID",
		"email": "String",
		"password": "String",
		"fullname": "String",
		"avatar": "String",
		"roleId": "String",
		"emailVerified": "Boolean",
		"approvalStatus": "Enum",
		"approvalStatus_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Create User API

This api is used by admin roles to create a new user manually from admin panels

Rest Route

The createUser API REST controller can be triggered via the following route:

/v1/users

Rest Request Parameters

The createUser api has got 4 regular request parameters

Parameter Type Required Population
avatar String false request.body?.[“avatar”]
email String true request.body?.[“email”]
password String true request.body?.[“password”]
fullname String true request.body?.[“fullname”]
avatar : The avatar url of the user. If not sent, a default random one will be generated.
email : A string value to represent the user’s email.
password : A string value to represent the user’s password. It will be stored as hashed.
fullname : A string value to represent the fullname of the user

REST Request To access the api you can use the REST controller with the path POST /v1/users

  axios({
    method: 'POST',
    url: '/v1/users',
    data: {
            avatar:"String",  
            email:"String",  
            password:"String",  
            fullname:"String",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "user",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"user": {
		"id": "ID",
		"email": "String",
		"password": "String",
		"fullname": "String",
		"avatar": "String",
		"roleId": "String",
		"emailVerified": "Boolean",
		"approvalStatus": "Enum",
		"approvalStatus_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Delete User API

This api is used by admins to delete user profiles.

Rest Route

The deleteUser API REST controller can be triggered via the following route:

/v1/users/:userId

Rest Request Parameters

The deleteUser api has got 1 regular request parameter

Parameter Type Required Population
userId ID true request.params?.[“userId”]
userId : This id paremeter is used to select the required data object that will be deleted

REST Request To access the api you can use the REST controller with the path DELETE /v1/users/:userId

  axios({
    method: 'DELETE',
    url: `/v1/users/${userId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "user",
	"method": "DELETE",
	"action": "delete",
	"appVersion": "Version",
	"rowCount": 1,
	"user": {
		"id": "ID",
		"email": "String",
		"password": "String",
		"fullname": "String",
		"avatar": "String",
		"roleId": "String",
		"emailVerified": "Boolean",
		"approvalStatus": "Enum",
		"approvalStatus_idx": "Integer",
		"isActive": false,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Archive Profile API

This api is used by users to archive their profiles.

Rest Route

The archiveProfile API REST controller can be triggered via the following route:

/v1/archiveprofile/:userId

Rest Request Parameters

The archiveProfile api has got 1 regular request parameter

Parameter Type Required Population
userId ID true request.params?.[“userId”]
userId : This id paremeter is used to select the required data object that will be deleted

REST Request To access the api you can use the REST controller with the path DELETE /v1/archiveprofile/:userId

  axios({
    method: 'DELETE',
    url: `/v1/archiveprofile/${userId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "user",
	"method": "DELETE",
	"action": "delete",
	"appVersion": "Version",
	"rowCount": 1,
	"user": {
		"id": "ID",
		"email": "String",
		"password": "String",
		"fullname": "String",
		"avatar": "String",
		"roleId": "String",
		"emailVerified": "Boolean",
		"approvalStatus": "Enum",
		"approvalStatus_idx": "Integer",
		"isActive": false,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

List Users API

The list of users is filtered by the tenantId.

Rest Route

The listUsers API REST controller can be triggered via the following route:

/v1/users

Rest Request Parameters

Filter Parameters

The listUsers api supports 3 optional filter parameters for filtering list results:

email (String): A string value to represent the user’s email.

fullname (String): A string value to represent the fullname of the user

roleId (String): A string value to represent the roleId of the user.

REST Request To access the api you can use the REST controller with the path GET /v1/users

  axios({
    method: 'GET',
    url: '/v1/users',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section above)
        // email: '<value>' // Filter by email
        // fullname: '<value>' // Filter by fullname
        // roleId: '<value>' // Filter by roleId
            }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "users",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"users": [
		{
			"id": "ID",
			"email": "String",
			"password": "String",
			"fullname": "String",
			"avatar": "String",
			"roleId": "String",
			"emailVerified": "Boolean",
			"approvalStatus": "Enum",
			"approvalStatus_idx": "Integer",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID"
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Search Users API

The list of users is filtered by the tenantId.

Rest Route

The searchUsers API REST controller can be triggered via the following route:

/v1/searchusers

Rest Request Parameters

The searchUsers api has got 1 regular request parameter

Parameter Type Required Population
keyword String true request.query?.[“keyword”]
keyword :

Filter Parameters

The searchUsers api supports 1 optional filter parameter for filtering list results:

roleId (String): A string value to represent the roleId of the user.

REST Request To access the api you can use the REST controller with the path GET /v1/searchusers

  axios({
    method: 'GET',
    url: '/v1/searchusers',
    data: {
    
    },
    params: {
             keyword:'"String"',  
    
        // Filter parameters (see Filter Parameters section above)
        // roleId: '<value>' // Filter by roleId
            }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "users",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"users": [
		{
			"id": "ID",
			"email": "String",
			"password": "String",
			"fullname": "String",
			"avatar": "String",
			"roleId": "String",
			"emailVerified": "Boolean",
			"approvalStatus": "Enum",
			"approvalStatus_idx": "Integer",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID"
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Update Userrole API

This route is used by admin roles to update the user role.The default role is user when a user is registered. A user’s role can be updated by superAdmin or admin

Rest Route

The updateUserRole API REST controller can be triggered via the following route:

/v1/userrole/:userId

Rest Request Parameters

The updateUserRole api has got 2 regular request parameters

Parameter Type Required Population
userId ID true request.params?.[“userId”]
roleId String true request.body?.[“roleId”]
userId : This id paremeter is used to select the required data object that will be updated
roleId : The new roleId of the user to be updated

REST Request To access the api you can use the REST controller with the path PATCH /v1/userrole/:userId

  axios({
    method: 'PATCH',
    url: `/v1/userrole/${userId}`,
    data: {
            roleId:"String",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "user",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"user": {
		"id": "ID",
		"email": "String",
		"password": "String",
		"fullname": "String",
		"avatar": "String",
		"roleId": "String",
		"emailVerified": "Boolean",
		"approvalStatus": "Enum",
		"approvalStatus_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Update Userpassword API

This route is used to update the password of users in the profile page by users themselves

Rest Route

The updateUserPassword API REST controller can be triggered via the following route:

/v1/userpassword/:userId

Rest Request Parameters

The updateUserPassword api has got 3 regular request parameters

Parameter Type Required Population
userId ID true request.params?.[“userId”]
oldPassword String true request.body?.[“oldPassword”]
newPassword String true request.body?.[“newPassword”]
userId : This id paremeter is used to select the required data object that will be updated
oldPassword : The old password of the user that will be overridden bu the new one. Send for double check.
newPassword : The new password of the user to be updated

REST Request To access the api you can use the REST controller with the path PATCH /v1/userpassword/:userId

  axios({
    method: 'PATCH',
    url: `/v1/userpassword/${userId}`,
    data: {
            oldPassword:"String",  
            newPassword:"String",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "user",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"user": {
		"id": "ID",
		"email": "String",
		"password": "String",
		"fullname": "String",
		"avatar": "String",
		"roleId": "String",
		"emailVerified": "Boolean",
		"approvalStatus": "Enum",
		"approvalStatus_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Update Userpasswordbyadmin API

This route is used to change any user password by admins only. Superadmin can chnage all passwords, admins can change only nonadmin passwords

Rest Route

The updateUserPasswordByAdmin API REST controller can be triggered via the following route:

/v1/userpasswordbyadmin/:userId

Rest Request Parameters

The updateUserPasswordByAdmin api has got 2 regular request parameters

Parameter Type Required Population
userId ID true request.params?.[“userId”]
password String true request.body?.[“password”]
userId : This id paremeter is used to select the required data object that will be updated
password : The new password of the user to be updated

REST Request To access the api you can use the REST controller with the path PATCH /v1/userpasswordbyadmin/:userId

  axios({
    method: 'PATCH',
    url: `/v1/userpasswordbyadmin/${userId}`,
    data: {
            password:"String",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "user",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"user": {
		"id": "ID",
		"email": "String",
		"password": "String",
		"fullname": "String",
		"avatar": "String",
		"roleId": "String",
		"emailVerified": "Boolean",
		"approvalStatus": "Enum",
		"approvalStatus_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Get Briefuser API

This route is used by public to get simple user profile information.

Rest Route

The getBriefUser API REST controller can be triggered via the following route:

/v1/briefuser/:userId

Rest Request Parameters

The getBriefUser api has got 1 regular request parameter

Parameter Type Required Population
userId ID true request.params?.[“userId”]
userId : This id paremeter is used to query the required data object.

REST Request To access the api you can use the REST controller with the path GET /v1/briefuser/:userId

  axios({
    method: 'GET',
    url: `/v1/briefuser/${userId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

This route’s response is constrained to a select list of properties, and therefore does not encompass all attributes of the resource.

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "user",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"user": {
		"isActive": true
	}
}

Stream Test API

Test API for iterator action streaming via SSE.

Rest Route

The streamTest API REST controller can be triggered via the following route:

/v1/streamtest/:userId

Rest Request Parameters

The streamTest api has got 1 regular request parameter

Parameter Type Required Population
userId ID true request.params?.[“userId”]
userId : This id paremeter is used to query the required data object.

REST Request To access the api you can use the REST controller with the path GET /v1/streamtest/:userId

  axios({
    method: 'GET',
    url: `/v1/streamtest/${userId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "user",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"user": {
		"id": "ID",
		"email": "String",
		"password": "String",
		"fullname": "String",
		"avatar": "String",
		"roleId": "String",
		"emailVerified": "Boolean",
		"approvalStatus": "Enum",
		"approvalStatus_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Register User API

This api is used by public users to register themselves

Rest Route

The registerUser API REST controller can be triggered via the following route:

/v1/registeruser

Rest Request Parameters

The registerUser api has got 4 regular request parameters

Parameter Type Required Population
avatar String false request.body?.[“avatar”]
password String true request.body?.[“password”]
fullname String true request.body?.[“fullname”]
email String true request.body?.[“email”]
avatar : The avatar url of the user. If not sent, a default random one will be generated.
password : The password defined by the the user that is being registered.
fullname : The fullname defined by the the user that is being registered.
email : The email defined by the the user that is being registered.

REST Request To access the api you can use the REST controller with the path POST /v1/registeruser

  axios({
    method: 'POST',
    url: '/v1/registeruser',
    data: {
            avatar:"String",  
            password:"String",  
            fullname:"String",  
            email:"String",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "user",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"user": {
		"id": "ID",
		"email": "String",
		"password": "String",
		"fullname": "String",
		"avatar": "String",
		"roleId": "String",
		"emailVerified": "Boolean",
		"approvalStatus": "Enum",
		"approvalStatus_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Get Useravatarsfile API

[Default get API] — This is the designated default get API for the userAvatarsFile data object. Frontend generators and AI agents should use this API for standard CRUD operations.

Rest Route

The getUserAvatarsFile API REST controller can be triggered via the following route:

/v1/useravatarsfiles/:userAvatarsFileId

Rest Request Parameters

The getUserAvatarsFile api has got 1 regular request parameter

Parameter Type Required Population
userAvatarsFileId ID true request.params?.[“userAvatarsFileId”]
userAvatarsFileId : This id paremeter is used to query the required data object.

REST Request To access the api you can use the REST controller with the path GET /v1/useravatarsfiles/:userAvatarsFileId

  axios({
    method: 'GET',
    url: `/v1/useravatarsfiles/${userAvatarsFileId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "userAvatarsFile",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"userAvatarsFile": {
		"id": "ID",
		"fileName": "String",
		"mimeType": "String",
		"fileSize": "Integer",
		"accessKey": "String",
		"ownerId": "ID",
		"fileData": "Blob",
		"metadata": "Object",
		"userId": "ID",
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"isActive": true
	}
}

List Useravatarsfiles API

[Default list API] — This is the designated default list API for the userAvatarsFile data object. Frontend generators and AI agents should use this API for standard CRUD operations.

Rest Route

The listUserAvatarsFiles API REST controller can be triggered via the following route:

/v1/useravatarsfiles

Rest Request Parameters

Filter Parameters

The listUserAvatarsFiles api supports 3 optional filter parameters for filtering list results:

mimeType (String): MIME type of the uploaded file (e.g., image/png, application/pdf).

ownerId (ID): ID of the user who uploaded the file (from session).

userId (ID): Reference to the owner user record.

REST Request To access the api you can use the REST controller with the path GET /v1/useravatarsfiles

  axios({
    method: 'GET',
    url: '/v1/useravatarsfiles',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section above)
        // mimeType: '<value>' // Filter by mimeType
        // ownerId: '<value>' // Filter by ownerId
        // userId: '<value>' // Filter by userId
            }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "userAvatarsFiles",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"userAvatarsFiles": [
		{
			"id": "ID",
			"fileName": "String",
			"mimeType": "String",
			"fileSize": "Integer",
			"accessKey": "String",
			"ownerId": "ID",
			"fileData": "Blob",
			"metadata": "Object",
			"userId": "ID",
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID",
			"isActive": true
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Delete Useravatarsfile API

[Default delete API] — This is the designated default delete API for the userAvatarsFile data object. Frontend generators and AI agents should use this API for standard CRUD operations.

Rest Route

The deleteUserAvatarsFile API REST controller can be triggered via the following route:

/v1/useravatarsfiles/:userAvatarsFileId

Rest Request Parameters

The deleteUserAvatarsFile api has got 1 regular request parameter

Parameter Type Required Population
userAvatarsFileId ID true request.params?.[“userAvatarsFileId”]
userAvatarsFileId : This id paremeter is used to select the required data object that will be deleted

REST Request To access the api you can use the REST controller with the path DELETE /v1/useravatarsfiles/:userAvatarsFileId

  axios({
    method: 'DELETE',
    url: `/v1/useravatarsfiles/${userAvatarsFileId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "userAvatarsFile",
	"method": "DELETE",
	"action": "delete",
	"appVersion": "Version",
	"rowCount": 1,
	"userAvatarsFile": {
		"id": "ID",
		"fileName": "String",
		"mimeType": "String",
		"fileSize": "Integer",
		"accessKey": "String",
		"ownerId": "ID",
		"fileData": "Blob",
		"metadata": "Object",
		"userId": "ID",
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"isActive": false
	}
}

Authentication Specific Routes

Route: login

Route Definition: Handles the login process by verifying user credentials and generating an authenticated session.

Route Type: login

Access Routes:

Parameters

Parameter Type Required Population
username String Yes request.body.username
password String Yes request.body.password

Notes

// Sample POST /login call
axios.post("/login", {
  username: "user@example.com",
  password: "securePassword"
});

Success Response

Returns the authenticated session object with a status code 200 OK.

A secure HTTP-only cookie and an access token header are included in the response.

{
  "userId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38",
  "email": "user@example.com",
  "fullname": "John Doe",
  ...
}

Error Responses

Route: logout

Route Definition: Logs the user out by terminating the current session and clearing the access token.

Route Type: logout

Access Route: POST /logout

Parameters

This route does not require any parameters in the body or query.

Behavior

// Sample POST /logout call
axios.post("/logout", {}, {
  headers: {
    "Authorization": "Bearer your-jwt-token"
  }
});

Notes

Error Responses 00200 OK:** Always returned, regardless of whether a session existed. Logout is treated as idempotent.

Route: publickey

Route Definition: Returns the public RSA key used to verify JWT access tokens issued by the auth service.

Route Type: publicKeyFetch

Access Route: GET /publickey

Parameters

Parameter Type Required Population
keyId String No request.query.keyId

Behavior

// Sample GET /publickey call
axios.get("/publickey", {
  params: {
    keyId: "currentKeyIdOptional"
  }
});

Success Response Returns the active public key and its associated keyId.

{
    "keyId": "a1b2c3d4",
    "keyData": "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhki...\n-----END PUBLIC KEY-----"
}

Error Responses 404 Not Found: Public key file could not be found on the server.

Token Key Management

Mindbricks uses RSA key pairs to sign and verify JWT access tokens securely.
While the auth service signs each token with a private key, other services within the system — or external clients — need the corresponding public key to verify the authenticity and integrity of received tokens.

The /publickey endpoint allows services and clients to dynamically fetch the currently active public key, ensuring that token verification remains secure even if key rotation is performed.

Note:
The /publickey route is not intended for direct frontend (browser) consumption.
Instead, it is primarily used by trusted backend services, APIs, or middleware systems that need to independently verify access tokens issued by the auth service — without making verification-dependent API calls to the auth service itself.

Accessing the public key is crucial for validating user sessions efficiently and maintaining a decentralized trust model across your platform.

Route: relogin

Route Definition: Performs a silent login by verifying the current access token, refreshing the session, and returning a new access token along with updated user information.

Route Type: sessionRefresh

Access Route: GET /relogin

Parameters

This route does not require any request parameters.

Behavior

// Example call to refresh session
axios.get("/relogin", {
  headers: {
    "Authorization": "Bearer your-jwt-token"
  }
});

Success Response Returns a new session object, refreshed from database data.

{
  "sessionId": "new-session-uuid",
  "userId": "user-uuid",
  "email": "user@example.com",
  "roleId": "admin",
  "accessToken": "new-jwt-token",
  ...
}

Error Responses

{
  "status": "ERR",
  "message": "Cannot relogin"
}

Notes

Tip: This route is ideal when you want to rebuild a user’s session in the frontend without requiring them to manually log in again.

Verification Services — Email Verification

Email verification is a two-step flow that ensures a user’s email address is verified and trusted by the system.

All verification services, including email verification, are located under the /verification-services base path.

When is Email Verification Triggered?

Email Verification Flow

  1. Frontend calls /verification-services/email-verification/start with the user’s email address.
    • Mindbricks checks if the email is already verified.
    • A secret code is generated and stored in the cache linked to the user.
    • The code is sent to the user’s email or returned in the response (only in development environments for easier testing).
  2. User receives the code and enters it into the frontend application.
  3. Frontend calls /verification-services/email-verification/complete with the email and the received secretCode.
    • Mindbricks checks that the code is valid, not expired, and matches.
    • If valid, the user’s emailVerified flag is set to true, and a success response is returned.

API Endpoints

POST /verification-services/email-verification/start

Purpose
Starts the email verification process by generating and sending a secret verification code.

Request Body

Parameter Type Required Description
email String Yes The email address to verify
{
  "email": "user@example.com"
}

Success Response

Secret code details (in development environment). Confirms that the verification step has been started.

{
  "userId": "user-uuid",
  "email": "user@example.com",
  "secretCode": "123456",
  "expireTime": 86400,
  "date": "2024-04-29T10:00:00.000Z"
}

⚠️ In production, the secret code is only sent via email, not exposed in the API response.

Error Responses


POST /verification-services/email-verification/complete

Purpose
Completes the email verification by validating the secret code.

Request Body

Parameter Type Required Description
email String Yes The user email being verified
secretCode String Yes The secret code received via email
{
  "email": "user@example.com",
  "secretCode": "123456"
}

Success Response

Returns confirmation that the email has been verified.

{
  "userId": "user-uuid",
  "email": "user@example.com",
  "isVerified": true
}

Error Responses


Important Behavioral Notes

Resend Throttling

You can only request a new verification code after a cooldown period (resendTimeWindow, e.g., 60 seconds).

Expiration Handling

Verification codes expire after a configured period (expireTimeWindow, e.g., 1 day).

One Code Per Session

Only one active verification session per user is allowed at a time.

💡 Mindbricks automatically manages spam prevention, session caching, expiration, and event broadcasting (start/complete events) for all verification steps.

Verification Services — Mobile Verification

Mobile verification is a two-step flow that ensures a user’s mobile number is verified and trusted by the system.

All verification services, including mobile verification, are located under the /verification-services base path.

When is Mobile Verification Triggered?

Mobile Verification Flow

  1. Frontend calls /verification-services/mobile-verification/start with the user’s email address (used to locate the user).
    • Mindbricks checks if the mobile number is already verified.
    • A secret code is generated and stored in the cache linked to the user.
    • The code is sent to the user’s mobile via SMS or returned in the response (only in development environments for easier testing).
  2. User receives the code and enters it into the frontend application.
  3. Frontend calls /verification-services/mobile-verification/complete with the email and the received secretCode.
    • Mindbricks checks that the code is valid, not expired, and matches.
    • If valid, the user’s mobileVerified flag is set to true, and a success response is returned.

API Endpoints

POST /verification-services/mobile-verification/start

Purpose:
Starts the mobile verification process by generating and sending a secret verification code.

Request Body

Parameter Type Required Description
email String Yes The email address associated with the mobile number to verify
{
  "email": "user@example.com"
}

Success Response
Secret code details (in development environment). Confirms that the verification step has been started.

{
  "userId": "user-uuid",
  "mobile": "+15551234567",
  "secretCode": "123456",
  "expireTime": 86400,
  "date": "2024-04-29T10:00:00.000Z"
}

⚠️ In production, the secret code is only sent via SMS, not exposed in the API response.

Error Responses


POST /verification-services/mobile-verification/complete

Purpose:
Completes the mobile verification by validating the secret code.

Request Body

Parameter Type Required Description
email String Yes The user’s email being verified
secretCode String Yes The secret code received via SMS
{
  "email": "user@example.com",
  "secretCode": "123456"
}

Success Response
Returns confirmation that the mobile number has been verified.

{
  "userId": "user-uuid",
  "mobile": "+15551234567",
  "isVerified": true
}

Error Responses
403 Forbidden:


Important Behavioral Notes

Resend Throttling:
You can only request a new verification code after a cooldown period (resendTimeWindow, e.g., 60 seconds).

Expiration Handling:
Verification codes expire after a configured period (expireTimeWindow, e.g., 1 day).

One Code Per Session:
Only one active verification session per user is allowed at a time.

💡 Mindbricks automatically manages spam prevention, session caching, expiration, and event broadcasting (start/complete events) for all verification steps.

Verification Services — Email 2FA Verification

Email 2FA (Two-Factor Authentication) provides an additional layer of security by requiring users to confirm their identity using a secret code sent to their email address. This process is used in login flows or sensitive actions that need extra verification.

All verification services, including 2FA, are located under the /verification-services base path.

When is Email 2FA Triggered?

Email 2FA Flow

  1. Frontend calls /verification-services/email-2factor-verification/start with the user’s id, session id, client info, and reason.
    • Mindbricks identifies the user and checks if a cooldown period applies.
    • A new secret code is generated and stored, linked to the current session ID.
    • The code is sent via email or returned in development environments.
  2. User receives the code and enters it into the frontend application.
  3. Frontend calls /verification-services/email-2factor-verification/complete with the userId, sessionId, and the secretCode.
    • Mindbricks verifies the code, validates the session, and updates the session to remove the 2FA requirement.

API Endpoints

POST /verification-services/email-2factor-verification/start

Purpose:
Starts the email-based 2FA process by generating and sending a verification code.

Request Body

Parameter Type Required Description
userId String Yes The user’s ID
sessionId String Yes The current session ID
client String No Optional client tag or context
reason String No Optional reason for triggering 2FA
{
  "userId": "user-uuid",
  "sessionId": "session-uuid",
  "client": "login-page",
  "reason": "Login requires email 2FA"
}

Success Response

{
  "sessionId": "session-uuid",
  "userId": "user-uuid",
  "email": "user@example.com",
  "secretCode": "123456",
  "expireTime": 300,
  "date": "2024-04-29T10:00:00.000Z"
}

⚠️ In production, the secretCode is only sent via email, not exposed in the API response.

Error Responses


POST /verification-services/email-2factor-verification/complete

Purpose:
Completes the email 2FA process by validating the secret code and session.

Request Body

Parameter Type Required Description
userId String Yes The user’s ID
sessionId String Yes The session ID the code is tied to
secretCode String Yes The secret code received via email
{
  "userId": "user-uuid",
  "sessionId": "session-uuid",
  "secretCode": "123456"
}

Success Response

Returns an updated session with 2FA disabled:

{
  "sessionId": "session-uuid",
  "userId": "user-uuid",
  "sessionNeedsEmail2FA": false,
  ...
}

Error Responses


Important Behavioral Notes

Verification Services — Mobile 2FA Verification

Mobile 2FA (Two-Factor Authentication) is a security mechanism that adds an extra layer of authentication using a user’s verified mobile number.

All verification services, including mobile 2FA, are accessible under the /verification-services base path.

When is Mobile 2FA Triggered?

Mobile 2FA Verification Flow

  1. Frontend calls /verification-services/mobile-2factor-verification/start with the user’s id, session id, client info, and reason.
    • Mindbricks finds the user by id.
    • Verifies that the user has a verified mobile number.
    • A secret code is generated and cached against the session.
    • The code is sent to the user’s verified mobile number or returned in the response (only in development environments).
  2. User receives the code and enters it in the frontend app.
  3. Frontend calls /verification-services/mobile-2factor-verification/complete with the userId, sessionId, and secretCode.
    • Mindbricks validates the code for expiration and correctness.
    • If valid, the session flag sessionNeedsMobile2FA is cleared.
    • A refreshed session object is returned.

API Endpoints

POST /verification-services/mobile-2factor-verification/start

Purpose:
Initiates mobile-based 2FA by generating and sending a secret code.

Request Body

Parameter Type Required Description
userId String Yes The user’s ID
sessionId String Yes The current session ID
client String No Optional client tag or context
reason String No Optional reason for triggering 2FA
{
  "userId": "user-uuid",
  "sessionId": "session-uuid",
  "client": "login-page",
  "reason": "Login requires mobile 2FA"
}

Success Response
Returns the generated code (only in development), expiration info, and metadata.

{
  "userId": "user-uuid",
  "sessionId": "session-uuid",
  "mobile": "+15551234567",
  "secretCode": "654321",
  "expireTime": 300,
  "date": "2024-04-29T11:00:00.000Z"
}

⚠️ In production environments, the secret code is not included in the response and is instead delivered via SMS.

Error Responses


POST /verification-services/mobile-2factor-verification/complete

Purpose:
Completes mobile 2FA verification by validating the secret code and updating the session.

Request Body

Parameter Type Required Description
userId String Yes ID of the user
sessionId String Yes ID of the session
secretCode String Yes The 6-digit code received via SMS
{
  "userId": "user-uuid",
  "sessionId": "session-uuid",
  "secretCode": "654321"
}

Success Response
Returns the updated session with sessionNeedsMobile2FA: false.

{
  "sessionId": "session-uuid",
  "userId": "user-uuid",
  "sessionNeedsMobile2FA": false,
  "accessToken": "jwt-token",
  "expiresIn": 86400
}

Error Responses


Behavioral Notes

💡 Mindbricks handles session integrity, rate limiting, and secure code delivery to ensure a robust mobile 2FA process.

Verification Services — Password Reset by Email

Password Reset by Email enables a user to securely reset their password using a secret code sent to their registered email address.

All verification services, including password reset by email, are located under the /verification-services base path.

When is Password Reset by Email Triggered?

Password Reset Flow

  1. Frontend calls /verification-services/password-reset-by-email/start with the user’s email.
    • Mindbricks checks if the user exists and if the email is registered.
    • A secret code is generated and stored in the cache linked to the user.
    • The code is sent to the user’s email, or returned in the response (in development environments only for testing).
  2. User receives the code and enters it into the frontend along with the new password.
  3. Frontend calls /verification-services/password-reset-by-email/complete with the email, the secretCode, and the new password.
    • Mindbricks checks that the code is valid, not expired, and matches.
    • If valid, the user’s password is reset, their emailVerified flag is set to true, and a success response is returned.

API Endpoints

POST /verification-services/password-reset-by-email/start

Purpose:
Starts the password reset process by generating and sending a secret verification code.

Request Body

Parameter Type Required Description
email String Yes The email address of the user
{
  "email": "user@example.com"
}

Success Response

Returns secret code details (only in development environment) and confirmation that the verification step has been started.

{
  "userId": "user-uuid",
  "email": "user@example.com",
  "secretCode": "123456", 
  "expireTime": 86400,
  "date": "2024-04-29T10:00:00.000Z"
}

⚠️ In production, the secret code is only sent via email and not exposed in the API response.

Error Responses


POST /verification-services/password-reset-by-email/complete

Purpose:
Completes the password reset process by validating the secret code and updating the user’s password.

Request Body

Parameter Type Required Description
email String Yes The email address of the user
secretCode String Yes The code received via email
password String Yes The new password the user wants to set
{
  "email": "user@example.com",
  "secretCode": "123456",
  "password": "newSecurePassword123"
}

Success Response

{
  "userId": "user-uuid",
  "email": "user@example.com",
  "isVerified": true
}

Error Responses


Important Behavioral Notes

Resend Throttling:

A new verification code can only be requested after a cooldown period (configured via resendTimeWindow, e.g., 60 seconds).

Expiration Handling:

Verification codes automatically expire after a predefined period (expireTimeWindow, e.g., 1 day).

Session & Event Handling:

Mindbricks manages:

Verification Services — Password Reset by Mobile

Password reset by mobile provides users with a secure mechanism to reset their password using a verification code sent via SMS to their registered mobile number.

All verification services, including password reset by mobile, are located under the /verification-services base path.

When is Password Reset by Mobile Triggered?

Password Reset by Mobile Flow

  1. Frontend calls /verification-services/password-reset-by-mobile/start with the user’s mobile number or associated identifier.
    • Mindbricks checks if a user with the given mobile exists.
    • A secret code is generated and stored in the cache for that user.
    • The code is sent to the user’s mobile (or returned in development environments for testing).
  2. User receives the code via SMS and enters it into the frontend app.
  3. Frontend calls /verification-services/password-reset-by-mobile/complete with the user’s email, the secretCode, and the new password.
    • Mindbricks validates the secret code and its expiration.
    • If valid, it updates the user’s password and returns a success response.

API Endpoints

POST /verification-services/password-reset-by-mobile/start

Purpose:
Initiates the mobile-based password reset by sending a verification code to the user’s mobile.

Request Body

Parameter Type Required Description
mobile String Yes The mobile number to verify
{
  "mobile": "+905551234567"
}

Success Response

Returns the verification context (code returned only in development):

{
  "userId": "user-uuid",
  "mobile": "+905551234567",
  "secretCode": "123456", 
  "expireTime": 86400,
  "date": "2024-04-29T10:00:00.000Z"
}

⚠️ In production, the secretCode is not included in the response and is only sent via SMS.

Error Responses


POST /verification-services/password-reset-by-mobile/complete

Purpose:
Finalizes the password reset process by validating the received verification code and updating the user’s password.

Request Body

Parameter Type Required Description
email String Yes The email address of the user
secretCode String Yes The code received via SMS
password String Yes The new password to assign
{
  "email": "user@example.com",
  "secretCode": "123456",
  "password": "NewSecurePassword123!"
}

Success Response

{
  "userId": "user-uuid",
  "mobile": "+905551234567",
  "isVerified": true
}

Important Behavioral Notes

💡 Mindbricks handles spam protection, session caching, and event-based logging (for both start and complete operations) as part of the verification service base class.

Verification Method Types

🧾 For byCode Verifications

This verification type requires the user to manually enter a 6-digit code.

Frontend Action:
Display a secure input page where the user can enter the code they received via email or SMS. After collecting the code and any required metadata (such as userId or sessionId), make a POST request to the corresponding /complete endpoint.


🔗 For byLink Verifications

This verification type uses a clickable link embedded in an email (or SMS message).

Frontend Action:
The link points to a GET page in your frontend that parses userId and code from the query string and sends them to the backend via a POST request to the corresponding /complete endpoint. This enables one-click verification without requiring the user to type in a code.

Common Routes

Route: currentuser

Route Definition: Retrieves the currently authenticated user’s session information.

Route Type: sessionInfo

Access Route: GET /currentuser

Parameters

This route does not require any request parameters.

Behavior

// Sample GET /currentuser call
axios.get("/currentuser", {
  headers: {
    "Authorization": "Bearer your-jwt-token"
  }
});

Success Response Returns the session object, including user-related data and token information.

{
  "sessionId": "9cf23fa8-07d4-4e7c-80a6-ec6d6ac96bb9",
  "userId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38",
  "email": "user@example.com",
  "fullname": "John Doe",
  "roleId": "user",
  "tenantId": "abc123",
  "accessToken": "jwt-token-string",
  ...
}

Error Response 401 Unauthorized: No active session found.

{
  "status": "ERR",
  "message": "No login found"
}

Notes

Route: permissions

*Route Definition*: Retrieves all effective permission records assigned to the currently authenticated user.

*Route Type*: permissionFetch

Access Route: GET /permissions

Parameters

This route does not require any request parameters.

Behavior

// Sample GET /permissions call
axios.get("/permissions", {
  headers: {
    "Authorization": "Bearer your-jwt-token"
  }
});

Success Response

Returns an array of permission objects.

[
  {
    "id": "perm1",
    "permissionName": "adminPanel.access",
    "roleId": "admin",
    "subjectUserId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38",
    "subjectUserGroupId": null,
    "objectId": null,
    "canDo": true,
    "tenantCodename": "store123"
  },
  {
    "id": "perm2",
    "permissionName": "orders.manage",
    "roleId": null,
    "subjectUserId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38",
    "subjectUserGroupId": null,
    "objectId": null,
    "canDo": true,
    "tenantCodename": "store123"
  }
]

Each object reflects a single permission grant, aligned with the givenPermissions model:

Error Responses

{
  "status": "ERR",
  "message": "No login found"
}

Notes

Tip: Applications can cache permission results client-side or server-side, but should occasionally refresh by calling this endpoint, especially after login or permission-changing operations.

Route: permissions/:permissionName

Route Definition: Checks whether the current user has access to a specific permission, and provides a list of scoped object exceptions or inclusions.

Route Type: permissionScopeCheck

Access Route: GET /permissions/:permissionName

Parameters

Parameter Type Required Population
permissionName String Yes request.params.permissionName

Behavior

// Sample GET /permissions/orders.manage
axios.get("/permissions/orders.manage", {
  headers: {
    "Authorization": "Bearer your-jwt-token"
  }
});

Success Response

{
  "canDo": true,
  "exceptions": [
    "a1f2e3d4-xxxx-yyyy-zzzz-object1",
    "b2c3d4e5-xxxx-yyyy-zzzz-object2"
  ]
}

Copyright

All sources, documents and other digital materials are copyright of .

About Us

For more information please visit our website: .

. .


EVENT GUIDE

EVENT GUIDE

auteurlabb-auth-service

Authentication service for the project

Architectural Design Credit and Contact Information

The architectural design of this microservice is credited to . For inquiries, feedback, or further information regarding the architecture, please direct your communication to:

Email:

We encourage open communication and welcome any questions or discussions related to the architectural aspects of this microservice.

Documentation Scope

Welcome to the official documentation for the Auth Service Event descriptions. This guide is dedicated to detailing how to subscribe to and listen for state changes within the Auth Service, offering an exclusive focus on event subscription mechanisms.

Intended Audience

This documentation is aimed at developers and integrators looking to monitor Auth Service state changes. It is especially relevant for those wishing to implement or enhance business logic based on interactions with Auth objects.

Overview

This section provides detailed instructions on monitoring service events, covering payload structures and demonstrating typical use cases through examples.

Authentication and Authorization

Access to the Auth service’s events is facilitated through the project’s Kafka server, which is not accessible to the public. Subscription to a Kafka topic requires being on the same network and possessing valid Kafka user credentials. This document presupposes that readers have existing access to the Kafka server.

Additionally, the service offers a public subscription option via REST for real-time data management in frontend applications, secured through REST API authentication and authorization mechanisms. To subscribe to service events via the REST API, please consult the Realtime REST API Guide.

Database Events

Database events are triggered at the database layer, automatically and atomically, in response to any modifications at the data level. These events serve to notify subscribers about the creation, update, or deletion of objects within the database, distinct from any overarching business logic.

Listening to database events is particularly beneficial for those focused on tracking changes at the database level. A typical use case for subscribing to database events is to replicate the data store of one service within another service’s scope, ensuring data consistency and syncronization across services.

For example, while a business operation such as “approve membership” might generate a high-level business event like membership-approved, the underlying database changes could involve multiple state updates to different entities. These might be published as separate events, such as dbevent-member-updated and dbevent-user-updated, reflecting the granular changes at the database level.

Such detailed eventing provides a robust foundation for building responsive, data-driven applications, enabling fine-grained observability and reaction to the dynamics of the data landscape. It also facilitates the architectural pattern of event sourcing, where state changes are captured as a sequence of events, allowing for high-fidelity data replication and history replay for analytical or auditing purposes.

DbEvent user-created

Event topic: auteurlabb-auth-service-dbevent-user-created

This event is triggered upon the creation of a user data object in the database. The event payload encompasses the newly created data, encapsulated within the root of the paylod.

Event payload:

{"id":"ID","email":"String","password":"String","fullname":"String","avatar":"String","roleId":"String","emailVerified":"Boolean","approvalStatus":"Enum","approvalStatus_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

DbEvent user-updated

Event topic: auteurlabb-auth-service-dbevent-user-updated

Activation of this event follows the update of a user data object. The payload contains the updated information under the user attribute, along with the original data prior to update, labeled as old_user and also you can find the old and new versions of updated-only portion of the data…

Event payload:

{
old_user:{"id":"ID","email":"String","password":"String","fullname":"String","avatar":"String","roleId":"String","emailVerified":"Boolean","approvalStatus":"Enum","approvalStatus_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},
user:{"id":"ID","email":"String","password":"String","fullname":"String","avatar":"String","roleId":"String","emailVerified":"Boolean","approvalStatus":"Enum","approvalStatus_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},
oldDataValues,
newDataValues
}

DbEvent user-deleted

Event topic: auteurlabb-auth-service-dbevent-user-deleted

This event announces the deletion of a user data object, covering both hard deletions (permanent removal) and soft deletions (where the isActive attribute is set to false). Regardless of the deletion type, the event payload will present the data as it was immediately before deletion, highlighting an isActive status of false for soft deletions.

Event payload:

{"id":"ID","email":"String","password":"String","fullname":"String","avatar":"String","roleId":"String","emailVerified":"Boolean","approvalStatus":"Enum","approvalStatus_idx":"Integer","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

DbEvent userAvatarsFile-created

Event topic: auteurlabb-auth-service-dbevent-useravatarsfile-created

This event is triggered upon the creation of a userAvatarsFile data object in the database. The event payload encompasses the newly created data, encapsulated within the root of the paylod.

Event payload:

{"id":"ID","fileName":"String","mimeType":"String","fileSize":"Integer","accessKey":"String","ownerId":"ID","fileData":"Blob","metadata":"Object","userId":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

DbEvent userAvatarsFile-updated

Event topic: auteurlabb-auth-service-dbevent-useravatarsfile-updated

Activation of this event follows the update of a userAvatarsFile data object. The payload contains the updated information under the userAvatarsFile attribute, along with the original data prior to update, labeled as old_userAvatarsFile and also you can find the old and new versions of updated-only portion of the data…

Event payload:

{
old_userAvatarsFile:{"id":"ID","fileName":"String","mimeType":"String","fileSize":"Integer","accessKey":"String","ownerId":"ID","fileData":"Blob","metadata":"Object","userId":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},
userAvatarsFile:{"id":"ID","fileName":"String","mimeType":"String","fileSize":"Integer","accessKey":"String","ownerId":"ID","fileData":"Blob","metadata":"Object","userId":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},
oldDataValues,
newDataValues
}

DbEvent userAvatarsFile-deleted

Event topic: auteurlabb-auth-service-dbevent-useravatarsfile-deleted

This event announces the deletion of a userAvatarsFile data object, covering both hard deletions (permanent removal) and soft deletions (where the isActive attribute is set to false). Regardless of the deletion type, the event payload will present the data as it was immediately before deletion, highlighting an isActive status of false for soft deletions.

Event payload:

{"id":"ID","fileName":"String","mimeType":"String","fileSize":"Integer","accessKey":"String","ownerId":"ID","fileData":"Blob","metadata":"Object","userId":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":false}

ElasticSearch Index Events

Within the Auth service, most data objects are mirrored in ElasticSearch indices, ensuring these indices remain syncronized with their database counterparts through creation, updates, and deletions. These indices serve dual purposes: they act as a data source for external services and furnish aggregated data tailored to enhance frontend user experiences. Consequently, an ElasticSearch index might encapsulate data in its original form or aggregate additional information from other data objects.

These aggregations can include both one-to-one and one-to-many relationships not only with database objects within the same service but also across different services. This capability allows developers to access comprehensive, aggregated data efficiently. By subscribing to ElasticSearch index events, developers are notified when an index is updated and can directly obtain the aggregated entity within the event payload, bypassing the need for separate ElasticSearch queries.

It’s noteworthy that some services may augment another service’s index by appending to the entity’s extends object. In such scenarios, an *-extended event will contain only the newly added data. Should you require the complete dataset, you would need to retrieve the full ElasticSearch index entity using the provided ID.

This approach to indexing and event handling facilitates a modular, interconnected architecture where services can seamlessly integrate and react to changes, enriching the overall data ecosystem and enabling more dynamic, responsive applications.

Index Event user-created

Event topic: elastic-index-auteurlabb_user-created

Event payload:

{"id":"ID","email":"String","password":"String","fullname":"String","avatar":"String","roleId":"String","emailVerified":"Boolean","approvalStatus":"Enum","approvalStatus_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event user-updated

Event topic: elastic-index-auteurlabb_user-created

Event payload:

{"id":"ID","email":"String","password":"String","fullname":"String","avatar":"String","roleId":"String","emailVerified":"Boolean","approvalStatus":"Enum","approvalStatus_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event user-deleted

Event topic: elastic-index-auteurlabb_user-deleted

Event payload:

{"id":"ID","email":"String","password":"String","fullname":"String","avatar":"String","roleId":"String","emailVerified":"Boolean","approvalStatus":"Enum","approvalStatus_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event user-extended

Event topic: elastic-index-auteurlabb_user-extended

Event payload:

{
  id: id,
  extends: {
    [extendName]: "Object",
    [extendName + "_count"]: "Number",
  },
}

Route Events

Route events are emitted following the successful execution of a route. While most routes perform CRUD (Create, Read, Update, Delete) operations on data objects, resulting in route events that closely resemble database events, there are distinctions worth noting. A single route execution might trigger multiple CRUD actions and ElasticSearch indexing operations. However, for those primarily concerned with the overarching business logic and its outcomes, listening to the consolidated route event, published once at the conclusion of the route’s execution, is more pertinent.

Moreover, routes often deliver aggregated data beyond the primary database object, catering to specific client needs. For instance, creating a data object via a route might not only return the entity’s data but also route-specific metrics, such as the executing user’s permissions related to the entity. Alternatively, a route might automatically generate default child entities following the creation of a parent object. Consequently, the route event encapsulates a unified dataset encompassing both the parent and its children, in contrast to individual events triggered for each entity created. Therefore, subscribing to route events can offer a richer, more contextually relevant set of information aligned with business logic.

The payload of a route event mirrors the REST response JSON of the route, providing a direct and comprehensive reflection of the data and metadata communicated to the client. This ensures that subscribers to route events receive a payload that encapsulates both the primary data involved and any additional information deemed significant at the business level, facilitating a deeper understanding and integration of the service’s functional outcomes.

Route Event user-retrived

Event topic : auteurlabb-auth-service-user-retrived

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the user data object itself.

The following JSON included in the payload illustrates the fullest representation of the user object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"user","method":"GET","action":"get","appVersion":"Version","rowCount":1,"user":{"id":"ID","email":"String","password":"String","fullname":"String","avatar":"String","roleId":"String","emailVerified":"Boolean","approvalStatus":"Enum","approvalStatus_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event user-updated

Event topic : auteurlabb-auth-service-user-updated

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the user data object itself.

The following JSON included in the payload illustrates the fullest representation of the user object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"user","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"user":{"id":"ID","email":"String","password":"String","fullname":"String","avatar":"String","roleId":"String","emailVerified":"Boolean","approvalStatus":"Enum","approvalStatus_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event profile-updated

Event topic : auteurlabb-auth-service-profile-updated

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the user data object itself.

The following JSON included in the payload illustrates the fullest representation of the user object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"user","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"user":{"id":"ID","email":"String","password":"String","fullname":"String","avatar":"String","roleId":"String","emailVerified":"Boolean","approvalStatus":"Enum","approvalStatus_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event user-created

Event topic : auteurlabb-auth-service-user-created

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the user data object itself.

The following JSON included in the payload illustrates the fullest representation of the user object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"user","method":"POST","action":"create","appVersion":"Version","rowCount":1,"user":{"id":"ID","email":"String","password":"String","fullname":"String","avatar":"String","roleId":"String","emailVerified":"Boolean","approvalStatus":"Enum","approvalStatus_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event user-deleted

Event topic : auteurlabb-auth-service-user-deleted

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the user data object itself.

The following JSON included in the payload illustrates the fullest representation of the user object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"user","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"user":{"id":"ID","email":"String","password":"String","fullname":"String","avatar":"String","roleId":"String","emailVerified":"Boolean","approvalStatus":"Enum","approvalStatus_idx":"Integer","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event profile-archived

Event topic : auteurlabb-auth-service-profile-archived

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the user data object itself.

The following JSON included in the payload illustrates the fullest representation of the user object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"user","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"user":{"id":"ID","email":"String","password":"String","fullname":"String","avatar":"String","roleId":"String","emailVerified":"Boolean","approvalStatus":"Enum","approvalStatus_idx":"Integer","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event users-listed

Event topic : auteurlabb-auth-service-users-listed

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the users data object itself.

The following JSON included in the payload illustrates the fullest representation of the users object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"users","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","users":[{"id":"ID","email":"String","password":"String","fullname":"String","avatar":"String","roleId":"String","emailVerified":"Boolean","approvalStatus":"Enum","approvalStatus_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]}

Route Event users-searched

Event topic : auteurlabb-auth-service-users-searched

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the users data object itself.

The following JSON included in the payload illustrates the fullest representation of the users object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"users","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","users":[{"id":"ID","email":"String","password":"String","fullname":"String","avatar":"String","roleId":"String","emailVerified":"Boolean","approvalStatus":"Enum","approvalStatus_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]}

Route Event userrole-updated

Event topic : auteurlabb-auth-service-userrole-updated

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the user data object itself.

The following JSON included in the payload illustrates the fullest representation of the user object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"user","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"user":{"id":"ID","email":"String","password":"String","fullname":"String","avatar":"String","roleId":"String","emailVerified":"Boolean","approvalStatus":"Enum","approvalStatus_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event userpassword-updated

Event topic : auteurlabb-auth-service-userpassword-updated

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the user data object itself.

The following JSON included in the payload illustrates the fullest representation of the user object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"user","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"user":{"id":"ID","email":"String","password":"String","fullname":"String","avatar":"String","roleId":"String","emailVerified":"Boolean","approvalStatus":"Enum","approvalStatus_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event userpasswordbyadmin-updated

Event topic : auteurlabb-auth-service-userpasswordbyadmin-updated

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the user data object itself.

The following JSON included in the payload illustrates the fullest representation of the user object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"user","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"user":{"id":"ID","email":"String","password":"String","fullname":"String","avatar":"String","roleId":"String","emailVerified":"Boolean","approvalStatus":"Enum","approvalStatus_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event briefuser-retrived

Event topic : auteurlabb-auth-service-briefuser-retrived

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the user data object itself.

The following JSON included in the payload illustrates the fullest representation of the user object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"user","method":"GET","action":"get","appVersion":"Version","rowCount":1,"user":{"isActive":true}}

Route Event user-registered

Event topic : auteurlabb-auth-service-user-registered

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the user data object itself.

The following JSON included in the payload illustrates the fullest representation of the user object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"user","method":"POST","action":"create","appVersion":"Version","rowCount":1,"user":{"id":"ID","email":"String","password":"String","fullname":"String","avatar":"String","roleId":"String","emailVerified":"Boolean","approvalStatus":"Enum","approvalStatus_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event useravatarsfile-retrived

Event topic : auteurlabb-auth-service-useravatarsfile-retrived

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the userAvatarsFile data object itself.

The following JSON included in the payload illustrates the fullest representation of the userAvatarsFile object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"userAvatarsFile","method":"GET","action":"get","appVersion":"Version","rowCount":1,"userAvatarsFile":{"id":"ID","fileName":"String","mimeType":"String","fileSize":"Integer","accessKey":"String","ownerId":"ID","fileData":"Blob","metadata":"Object","userId":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true}}

Route Event useravatarsfiles-listed

Event topic : auteurlabb-auth-service-useravatarsfiles-listed

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the userAvatarsFiles data object itself.

The following JSON included in the payload illustrates the fullest representation of the userAvatarsFiles object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"userAvatarsFiles","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","userAvatarsFiles":[{"id":"ID","fileName":"String","mimeType":"String","fileSize":"Integer","accessKey":"String","ownerId":"ID","fileData":"Blob","metadata":"Object","userId":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]}

Route Event useravatarsfile-deleted

Event topic : auteurlabb-auth-service-useravatarsfile-deleted

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the userAvatarsFile data object itself.

The following JSON included in the payload illustrates the fullest representation of the userAvatarsFile object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"userAvatarsFile","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"userAvatarsFile":{"id":"ID","fileName":"String","mimeType":"String","fileSize":"Integer","accessKey":"String","ownerId":"ID","fileData":"Blob","metadata":"Object","userId":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":false}}

Index Event useravatarsfile-created

Event topic: elastic-index-auteurlabb_useravatarsfile-created

Event payload:

{"id":"ID","fileName":"String","mimeType":"String","fileSize":"Integer","accessKey":"String","ownerId":"ID","fileData":"Blob","metadata":"Object","userId":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event useravatarsfile-updated

Event topic: elastic-index-auteurlabb_useravatarsfile-created

Event payload:

{"id":"ID","fileName":"String","mimeType":"String","fileSize":"Integer","accessKey":"String","ownerId":"ID","fileData":"Blob","metadata":"Object","userId":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event useravatarsfile-deleted

Event topic: elastic-index-auteurlabb_useravatarsfile-deleted

Event payload:

{"id":"ID","fileName":"String","mimeType":"String","fileSize":"Integer","accessKey":"String","ownerId":"ID","fileData":"Blob","metadata":"Object","userId":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event useravatarsfile-extended

Event topic: elastic-index-auteurlabb_useravatarsfile-extended

Event payload:

{
  id: id,
  extends: {
    [extendName]: "Object",
    [extendName + "_count"]: "Number",
  },
}

Route Events

Route events are emitted following the successful execution of a route. While most routes perform CRUD (Create, Read, Update, Delete) operations on data objects, resulting in route events that closely resemble database events, there are distinctions worth noting. A single route execution might trigger multiple CRUD actions and ElasticSearch indexing operations. However, for those primarily concerned with the overarching business logic and its outcomes, listening to the consolidated route event, published once at the conclusion of the route’s execution, is more pertinent.

Moreover, routes often deliver aggregated data beyond the primary database object, catering to specific client needs. For instance, creating a data object via a route might not only return the entity’s data but also route-specific metrics, such as the executing user’s permissions related to the entity. Alternatively, a route might automatically generate default child entities following the creation of a parent object. Consequently, the route event encapsulates a unified dataset encompassing both the parent and its children, in contrast to individual events triggered for each entity created. Therefore, subscribing to route events can offer a richer, more contextually relevant set of information aligned with business logic.

The payload of a route event mirrors the REST response JSON of the route, providing a direct and comprehensive reflection of the data and metadata communicated to the client. This ensures that subscribers to route events receive a payload that encapsulates both the primary data involved and any additional information deemed significant at the business level, facilitating a deeper understanding and integration of the service’s functional outcomes.

Route Event user-retrived

Event topic : auteurlabb-auth-service-user-retrived

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the user data object itself.

The following JSON included in the payload illustrates the fullest representation of the user object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"user","method":"GET","action":"get","appVersion":"Version","rowCount":1,"user":{"id":"ID","email":"String","password":"String","fullname":"String","avatar":"String","roleId":"String","emailVerified":"Boolean","approvalStatus":"Enum","approvalStatus_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event user-updated

Event topic : auteurlabb-auth-service-user-updated

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the user data object itself.

The following JSON included in the payload illustrates the fullest representation of the user object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"user","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"user":{"id":"ID","email":"String","password":"String","fullname":"String","avatar":"String","roleId":"String","emailVerified":"Boolean","approvalStatus":"Enum","approvalStatus_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event profile-updated

Event topic : auteurlabb-auth-service-profile-updated

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the user data object itself.

The following JSON included in the payload illustrates the fullest representation of the user object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"user","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"user":{"id":"ID","email":"String","password":"String","fullname":"String","avatar":"String","roleId":"String","emailVerified":"Boolean","approvalStatus":"Enum","approvalStatus_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event user-created

Event topic : auteurlabb-auth-service-user-created

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the user data object itself.

The following JSON included in the payload illustrates the fullest representation of the user object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"user","method":"POST","action":"create","appVersion":"Version","rowCount":1,"user":{"id":"ID","email":"String","password":"String","fullname":"String","avatar":"String","roleId":"String","emailVerified":"Boolean","approvalStatus":"Enum","approvalStatus_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event user-deleted

Event topic : auteurlabb-auth-service-user-deleted

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the user data object itself.

The following JSON included in the payload illustrates the fullest representation of the user object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"user","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"user":{"id":"ID","email":"String","password":"String","fullname":"String","avatar":"String","roleId":"String","emailVerified":"Boolean","approvalStatus":"Enum","approvalStatus_idx":"Integer","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event profile-archived

Event topic : auteurlabb-auth-service-profile-archived

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the user data object itself.

The following JSON included in the payload illustrates the fullest representation of the user object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"user","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"user":{"id":"ID","email":"String","password":"String","fullname":"String","avatar":"String","roleId":"String","emailVerified":"Boolean","approvalStatus":"Enum","approvalStatus_idx":"Integer","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event users-listed

Event topic : auteurlabb-auth-service-users-listed

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the users data object itself.

The following JSON included in the payload illustrates the fullest representation of the users object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"users","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","users":[{"id":"ID","email":"String","password":"String","fullname":"String","avatar":"String","roleId":"String","emailVerified":"Boolean","approvalStatus":"Enum","approvalStatus_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]}

Route Event users-searched

Event topic : auteurlabb-auth-service-users-searched

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the users data object itself.

The following JSON included in the payload illustrates the fullest representation of the users object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"users","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","users":[{"id":"ID","email":"String","password":"String","fullname":"String","avatar":"String","roleId":"String","emailVerified":"Boolean","approvalStatus":"Enum","approvalStatus_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]}

Route Event userrole-updated

Event topic : auteurlabb-auth-service-userrole-updated

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the user data object itself.

The following JSON included in the payload illustrates the fullest representation of the user object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"user","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"user":{"id":"ID","email":"String","password":"String","fullname":"String","avatar":"String","roleId":"String","emailVerified":"Boolean","approvalStatus":"Enum","approvalStatus_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event userpassword-updated

Event topic : auteurlabb-auth-service-userpassword-updated

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the user data object itself.

The following JSON included in the payload illustrates the fullest representation of the user object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"user","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"user":{"id":"ID","email":"String","password":"String","fullname":"String","avatar":"String","roleId":"String","emailVerified":"Boolean","approvalStatus":"Enum","approvalStatus_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event userpasswordbyadmin-updated

Event topic : auteurlabb-auth-service-userpasswordbyadmin-updated

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the user data object itself.

The following JSON included in the payload illustrates the fullest representation of the user object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"user","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"user":{"id":"ID","email":"String","password":"String","fullname":"String","avatar":"String","roleId":"String","emailVerified":"Boolean","approvalStatus":"Enum","approvalStatus_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event briefuser-retrived

Event topic : auteurlabb-auth-service-briefuser-retrived

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the user data object itself.

The following JSON included in the payload illustrates the fullest representation of the user object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"user","method":"GET","action":"get","appVersion":"Version","rowCount":1,"user":{"isActive":true}}

Route Event user-registered

Event topic : auteurlabb-auth-service-user-registered

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the user data object itself.

The following JSON included in the payload illustrates the fullest representation of the user object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"user","method":"POST","action":"create","appVersion":"Version","rowCount":1,"user":{"id":"ID","email":"String","password":"String","fullname":"String","avatar":"String","roleId":"String","emailVerified":"Boolean","approvalStatus":"Enum","approvalStatus_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event useravatarsfile-retrived

Event topic : auteurlabb-auth-service-useravatarsfile-retrived

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the userAvatarsFile data object itself.

The following JSON included in the payload illustrates the fullest representation of the userAvatarsFile object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"userAvatarsFile","method":"GET","action":"get","appVersion":"Version","rowCount":1,"userAvatarsFile":{"id":"ID","fileName":"String","mimeType":"String","fileSize":"Integer","accessKey":"String","ownerId":"ID","fileData":"Blob","metadata":"Object","userId":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true}}

Route Event useravatarsfiles-listed

Event topic : auteurlabb-auth-service-useravatarsfiles-listed

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the userAvatarsFiles data object itself.

The following JSON included in the payload illustrates the fullest representation of the userAvatarsFiles object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"userAvatarsFiles","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","userAvatarsFiles":[{"id":"ID","fileName":"String","mimeType":"String","fileSize":"Integer","accessKey":"String","ownerId":"ID","fileData":"Blob","metadata":"Object","userId":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]}

Route Event useravatarsfile-deleted

Event topic : auteurlabb-auth-service-useravatarsfile-deleted

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the userAvatarsFile data object itself.

The following JSON included in the payload illustrates the fullest representation of the userAvatarsFile object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"userAvatarsFile","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"userAvatarsFile":{"id":"ID","fileName":"String","mimeType":"String","fileSize":"Integer","accessKey":"String","ownerId":"ID","fileData":"Blob","metadata":"Object","userId":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":false}}

Copyright

All sources, documents and other digital materials are copyright of .

About Us

For more information please visit our website: .

. .


Data Objects

Service Design Specification - Object Design for user

Service Design Specification - Object Design for user

auteurlabb-auth-service documentation

Document Overview

This document outlines the object design for the user model in our application. It includes details about the model’s attributes, relationships, and any specific validation or business logic that applies.

user Data Object

Object Overview

Description: A data object that stores the user information and handles login settings.

This object represents a core data structure within the service and acts as the blueprint for database interaction, API generation, and business logic enforcement. It is defined using the ObjectSettings pattern, which governs its behavior, access control, caching strategy, and integration points with other systems such as Stripe and Redis.

Core Configuration

Redis Entity Caching

This data object is configured for Redis entity caching, which improves data retrieval performance by storing frequently accessed data in Redis. Each time a new instance is created, updated or deleted, the cache is updated accordingly. Any get requests by id will first check the cache before querying the database. If you want to use the cache by other select criteria, you can configure any data property as a Redis cluster.

Properties Schema

Property Type Required Description
email String Yes A string value to represent the user's email.
password String Yes A string value to represent the user's password. It will be stored as hashed.
fullname String Yes A string value to represent the fullname of the user
avatar String No The avatar url of the user. A random avatar will be generated if not provided
roleId String Yes A string value to represent the roleId of the user.
emailVerified Boolean Yes A boolean value to represent the email verification status of the user.
approvalStatus Enum No Admin approval status for the user account (pending, approved, rejected).

Default Values

Default values are automatically assigned to properties when a new object is created, if no value is provided in the request body. Since default values are applied on db level, they should be literal values, not expressions.If you want to use expressions, you can use transposed parameters in any business API to set default values dynamically.

Always Create with Default Values

Some of the default values are set to be always used when creating a new object, even if the property value is provided in the request body. It ensures that the property is always initialized with a default value when the object is created.

Constant Properties

email

Constant properties are defined to be immutable after creation, meaning they cannot be updated or changed once set. They are typically used for properties that should remain constant throughout the object’s lifecycle. A property is set to be constant if the Allow Update option is set to false.

Auto Update Properties

fullname avatar approvalStatus

An update crud API created with the option Auto Params enabled will automatically update these properties with the provided values in the request body. If you want to update any property in your own business logic not by user input, you can set the Allow Auto Update option to false. These properties will be added to the update API’s body parameters and can be updated by the user if any value is provided in the request body.

Hashed Properties

password

Hashed properties are stored in the database as a hash value, providing an additional layer of security for sensitive data.

Enum Properties

Enum properties are defined with a set of allowed values, ensuring that only valid options can be assigned to them. The enum options value will be stored as strings in the database, but when a data object is created an addtional property with the same name plus an idx suffix will be created, which will hold the index of the selected enum option. You can use the index property to sort by the enum value or when your enum options represent a sequence of values.

Elastic Search Indexing

email fullname roleId emailVerified approvalStatus

Properties that are indexed in Elastic Search will be searchable via the Elastic Search API. While all properties are stored in the elastic search index of the data object, only those marked for Elastic Search indexing will be available for search queries.

Database Indexing

email

Properties that are indexed in the database will be optimized for query performance, allowing for faster data retrieval. Make a property indexed in the database if you want to use it frequently in query filters or sorting.

Unique Properties

email

Unique properties are enforced to have distinct values across all instances of the data object, preventing duplicate entries. Note that a unique property is automatically indexed in the database so you will not need to set the Indexed in DB option.

Cache Select Properties

email

Cache select properties are used to collect data from Redis entity cache with a different key than the data object id. This allows you to cache data that is not directly related to the data object id, but a frequently used filter.

Secondary Key Properties

email

Secondary key properties are used to create an additional indexed identifiers for the data object, allowing for alternative access patterns. Different than normal indexed properties, secondary keys will act as primary keys and Mindbricks will provide automatic secondary key db utility functions to access the data object by the secondary key.

Filter Properties

email fullname roleId

Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API’s that have “Auto Params” enabled.


Service Design Specification - Object Design for userAvatarsFile

Service Design Specification - Object Design for userAvatarsFile

auteurlabb-auth-service documentation

Document Overview

This document outlines the object design for the userAvatarsFile model in our application. It includes details about the model’s attributes, relationships, and any specific validation or business logic that applies.

userAvatarsFile Data Object

Object Overview

Description: Auto-generated file storage for the userAvatars database bucket. Files are stored as BYTEA in PostgreSQL.

This object represents a core data structure within the service and acts as the blueprint for database interaction, API generation, and business logic enforcement. It is defined using the ObjectSettings pattern, which governs its behavior, access control, caching strategy, and integration points with other systems such as Stripe and Redis.

Core Configuration

Properties Schema

Property Type Required Description
fileName String Yes Original file name as uploaded by the client.
mimeType String Yes MIME type of the uploaded file (e.g., image/png, application/pdf).
fileSize Integer Yes File size in bytes.
accessKey String Yes 12-character random key for shareable access. Auto-generated on upload.
ownerId ID No ID of the user who uploaded the file (from session).
fileData Blob Yes Binary file content. Stored as BYTEA in PostgreSQL or Buffer in MongoDB.
metadata Object No Optional JSON metadata for the file (tags, alt text, etc.).
userId ID No Reference to the owner user record.

Default Values

Default values are automatically assigned to properties when a new object is created, if no value is provided in the request body. Since default values are applied on db level, they should be literal values, not expressions.If you want to use expressions, you can use transposed parameters in any business API to set default values dynamically.

Constant Properties

fileName mimeType fileSize accessKey ownerId fileData userId

Constant properties are defined to be immutable after creation, meaning they cannot be updated or changed once set. They are typically used for properties that should remain constant throughout the object’s lifecycle. A property is set to be constant if the Allow Update option is set to false.

Auto Update Properties

fileName mimeType fileSize accessKey ownerId fileData metadata userId

An update crud API created with the option Auto Params enabled will automatically update these properties with the provided values in the request body. If you want to update any property in your own business logic not by user input, you can set the Allow Auto Update option to false. These properties will be added to the update API’s body parameters and can be updated by the user if any value is provided in the request body.

Elastic Search Indexing

fileName mimeType fileSize ownerId userId

Properties that are indexed in Elastic Search will be searchable via the Elastic Search API. While all properties are stored in the elastic search index of the data object, only those marked for Elastic Search indexing will be available for search queries.

Database Indexing

fileName mimeType accessKey ownerId userId

Properties that are indexed in the database will be optimized for query performance, allowing for faster data retrieval. Make a property indexed in the database if you want to use it frequently in query filters or sorting.

Unique Properties

accessKey

Unique properties are enforced to have distinct values across all instances of the data object, preventing duplicate entries. Note that a unique property is automatically indexed in the database so you will not need to set the Indexed in DB option.

Session Data Properties

ownerId

Session data properties are used to store data that is specific to the user session, allowing for personalized experiences and temporary data storage. If a property is configured as session data, it will be automatically mapped to the related field in the user session during CRUD operations. Note that session data properties can not be mutated by the user, but only by the system.

This property is also used to store the owner of the session data, allowing for ownership checks and access control.

Filter Properties

mimeType ownerId userId

Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API’s that have “Auto Params” enabled.


Business APIs

Business API Design Specification - Get User

Business API Design Specification - Get User

A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic.

While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized.

This document provides an in-depth explanation of the architectural design of the getUser Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side.

Main Data Object and CRUD Operation

The getUser Business API is designed to handle a get operation on the User data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

This api is used by admin roles or the users themselves to get the user profile information.

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The getUser Business API includes a REST controller that can be triggered via the following route:

/v1/users/:userId

By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the Parameters section.

gRPC Controller

The getUser Business API includes a gRPC controller that can be triggered via the following function:

getUser()

By calling this gRPC endpoint using a gRPC client, you can execute the Business API. Note that all parameters must be provided as function arguments, regardless of their HTTP location configuration, which is relevant only for the REST controller.

MCP Tool

REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This getUser Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The getUser Business API has 1 parameter that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client.

Business API parameters can be:

Regular Parameters

Name Type Required Default Location Data Path
userId ID Yes - urlpath userId
Description: This id paremeter is used to query the required data object.

Parameter Transformations

Some parameters are post-processed using transform scripts after being read from the request but before validation or workflow execution. Only parameters with a transform script are listed below.

No parameters are transformed in this API.

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the getUser Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Select Clause

Specifies which fields will be selected from the main data object during a get or list operation. Leave blank to select all properties. This applies only to get and list type APIs.",

``

Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({$and:[{id:this.userId},{isActive:true}]}), {"path":"services[0].businessLogic[0].whereClause.fullWhereClause"})

Get Options

Use these options to set get specific settings.

setAsRead: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed.

No setAsread field-value pair is configured.

Business Logic Workflow

[1] Step : startBusinessApi

Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Extracts parameters from request and Redis, applies defaults, and writes them to context.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Executes parameter transformation scripts, applies type coercion, merges derived values, and reshapes inputs for downstream milestones.


[4] Step : checkParameters

Validates required and custom parameters, enforcing business-specific rules and constraints.


[5] Step : checkBasicAuth

Performs login, role, and permission checks, and applies dynamic object-level access rules.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildWhereClause

Builds the WHERE clause for fetching the object and applies additional scoped filters if configured.

You can use the following settings to change some behavior of this step. whereClause

[7] Step : mainGetOperation

Executes the database fetch, retrieves the object, and stores it in context for enrichment or further checks.

You can use the following settings to change some behavior of this step. selectClause, getOptions

[8] Action : emitUserLoaded

Action Type: EmitSseEventAction

class Api {
  async emitUserLoaded() {
    const eventData = runMScript(
      () => ({
        userId: this.user?.id,
        fullname: this.user?.fullname,
        email: this.user?.email,
      }),
      {
        path: "services[0].businessLogic[0].actions.emitSseEventActions[0].data",
      },
    );
    await this.emitProgress(
      "userLoaded",
      typeof eventData === "string" ? eventData : "",
      typeof eventData === "object" ? eventData : {},
    );
  }
}

[9] Action : simulateEnrichment

Action Type: FunctionCallAction

class Api {
  async simulateEnrichment() {
    try {
      return await runMScript(
        () => (async () => await new Promise((r) => setTimeout(r, 50)))(),
        {
          path: "services[0].businessLogic[0].actions.functionCallActions[0].callScript",
        },
      );
    } catch (err) {
      console.error("Error in FunctionCallAction simulateEnrichment:", err);
      throw err;
    }
  }
}

[10] Step : checkInstance

Performs instance-level validations, such as ownership, existence, or access conditions.


[11] Step : buildOutput

Assembles the response from the object, applies masking, formatting, and injects additional metadata if needed.


[12] Step : sendResponse

Delivers the response to the controller for client delivery.


[13] Step : raiseApiEvent

Triggers optional API-level events after workflow completion, sending messages to integrations like Kafka if configured.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The getUser api has got 1 regular client parameter

Parameter Type Required Population
userId ID true request.params?.[“userId”]

REST Request

To access the api you can use the REST controller with the path GET /v1/users/:userId

  axios({
    method: 'GET',
    url: `/v1/users/${userId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the user object in the respones. However, some properties may be omitted based on the object’s internal logic.

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "user",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"user": {
		"id": "ID",
		"email": "String",
		"password": "String",
		"fullname": "String",
		"avatar": "String",
		"roleId": "String",
		"emailVerified": "Boolean",
		"approvalStatus": "Enum",
		"approvalStatus_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Business API Design Specification - Update User

Business API Design Specification - Update User

A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic.

While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized.

This document provides an in-depth explanation of the architectural design of the updateUser Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side.

Main Data Object and CRUD Operation

The updateUser Business API is designed to handle a update operation on the User data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

This route is used by admins to update user profiles.

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The updateUser Business API includes a REST controller that can be triggered via the following route:

/v1/users/:userId

By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the Parameters section.

gRPC Controller

The updateUser Business API includes a gRPC controller that can be triggered via the following function:

updateUser()

By calling this gRPC endpoint using a gRPC client, you can execute the Business API. Note that all parameters must be provided as function arguments, regardless of their HTTP location configuration, which is relevant only for the REST controller.

MCP Tool

REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This updateUser Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The updateUser Business API has 4 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client.

Business API parameters can be:

Regular Parameters

Name Type Required Default Location Data Path
userId ID Yes - urlpath userId
Description: This id paremeter is used to select the required data object that will be updated
fullname String No - body fullname
Description: A string value to represent the fullname of the user
avatar String No - body avatar
Description: The avatar url of the user. A random avatar will be generated if not provided
approvalStatus Enum No - body approvalStatus
Description: Admin approval status for the user account (pending, approved, rejected).

Parameter Transformations

Some parameters are post-processed using transform scripts after being read from the request but before validation or workflow execution. Only parameters with a transform script are listed below.

No parameters are transformed in this API.

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the updateUser Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({$and:[{id:this.userId},{isActive:true}]}), {"path":"services[0].businessLogic[1].whereClause.fullWhereClause"})

Data Clause

Defines custom field-value assignments used to modify or augment the default payload for create and update operations. These settings override values derived from the session or parameters if explicitly provided.", Note that a default data clause is always prepared by Mindbricks using data property settings, however any property in the data clause can be override by Data Clause Settings.

An update data clause populates all update-allowed properties of a data object, however the null properties (that are not provided by client) are ignored in db layer.

Custom Data Clause Override No custom data clause override configured

Actual Data Clause

The business api will use the following data clause. Note that any calculated value will be added to the data clause in the api manager.

{
  fullname: this.fullname,
  avatar: this.avatar,
  approvalStatus: this.approvalStatus,
}

Business Logic Workflow

[1] Step : startBusinessApi

Manager initializes context, prepares request and session objects, and sets up internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Manager reads parameters from the request or Redis, applies defaults, and writes them into context for downstream milestones.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Manager executes parameter transform scripts and derives any helper values or reshaped payloads into the context.


[4] Step : checkParameters

Manager validates required parameters, checks ID formats (UUID/ObjectId), and ensures all preconditions for update are met.


[5] Step : checkBasicAuth

Manager performs login verification, role, and permission checks, enforcing tenant and access rules before update.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildWhereClause

Manager constructs the WHERE clause used to identify the record to update, applying ownership and parent checks if necessary.

You can use the following settings to change some behavior of this step. whereClause

[7] Step : fetchInstance

Manager fetches the existing record from the database and writes it to the context for validation or enrichment.


[8] Action : setRolesOrder

Action Type: CreateObjectAction

Sets the hiyerarchy of the roles to check user permissions on other users

class Api {
  async setRolesOrder() {
    // Construct base object
    const obj = {};

    // Merge dynamic object
    Object.assign(
      obj,
      runMScript(
        () => ({
          superAdmin: 20,
          saasAdmin: 19,
          admin: 18,
          tenantOwner: 17,
          tenantAdmin: 16,
          saasUser: 15,
          tenantUser: 14,
          user: 13,
        }),
        {
          path: "services[0].businessLogic[1].actions.createObjectActions[0].mergeObject",
        },
      ),
    );

    return obj;
  }
}

[9] Action : protectHigherRole

Action Type: ValidationAction

Prevents the update of a higher or equal user role if not themselves

class Api {
  async protectHigherRole() {
    const isValid = runMScript(
      () =>
        (this._r[this.session.roleId] ?? 0) > (this._r[this.user.roleId] ?? 0),
      {
        path: "services[0].businessLogic[1].actions.validationActions[0].validationScript",
      },
    );

    if (!isValid) {
      throw new BadRequestError("AHigherUserRoleCantBeChanged");
    }
    return isValid;
  }
}

[10] Step : checkInstance

Manager performs instance-level validations, including ownership, existence, lock status, or other pre-update checks.


[11] Step : buildDataClause

Manager prepares the data clause for the update, applying transformations or enhancements before persisting.

You can use the following settings to change some behavior of this step. dataClause

[12] Step : mainUpdateOperation

Manager executes the update operation with the WHERE and data clauses. Database-level events are raised if configured.


[13] Step : buildOutput

Manager assembles the response object from the update result, masking fields or injecting additional metadata.


[14] Step : sendResponse

Manager sends the response back to the controller for delivery to the client.


[15] Step : raiseApiEvent

Manager triggers API-level events, sending relevant messages to Kafka or other integrations if configured.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The updateUser api has got 4 regular client parameters

Parameter Type Required Population
userId ID true request.params?.[“userId”]
fullname String false request.body?.[“fullname”]
avatar String false request.body?.[“avatar”]
approvalStatus Enum false request.body?.[“approvalStatus”]

REST Request

To access the api you can use the REST controller with the path PATCH /v1/users/:userId

  axios({
    method: 'PATCH',
    url: `/v1/users/${userId}`,
    data: {
            fullname:"String",  
            avatar:"String",  
            approvalStatus:"Enum",  
    
    },
    params: {
    
        }
  });

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the user object in the respones. However, some properties may be omitted based on the object’s internal logic.

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "user",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"user": {
		"id": "ID",
		"email": "String",
		"password": "String",
		"fullname": "String",
		"avatar": "String",
		"roleId": "String",
		"emailVerified": "Boolean",
		"approvalStatus": "Enum",
		"approvalStatus_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Business API Design Specification - Update Profile

Business API Design Specification - Update Profile

A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic.

While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized.

This document provides an in-depth explanation of the architectural design of the updateProfile Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side.

Main Data Object and CRUD Operation

The updateProfile Business API is designed to handle a update operation on the User data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

This route is used by users to update their profiles.

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The updateProfile Business API includes a REST controller that can be triggered via the following route:

/v1/profile/:userId

By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the Parameters section.

gRPC Controller

The updateProfile Business API includes a gRPC controller that can be triggered via the following function:

updateProfile()

By calling this gRPC endpoint using a gRPC client, you can execute the Business API. Note that all parameters must be provided as function arguments, regardless of their HTTP location configuration, which is relevant only for the REST controller.

MCP Tool

REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This updateProfile Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The updateProfile Business API has 4 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client.

Business API parameters can be:

Regular Parameters

Name Type Required Default Location Data Path
userId ID Yes - urlpath userId
Description: This id paremeter is used to select the required data object that will be updated
fullname String No - body fullname
Description: A string value to represent the fullname of the user
avatar String No - body avatar
Description: The avatar url of the user. A random avatar will be generated if not provided
approvalStatus Enum No - body approvalStatus
Description: Admin approval status for the user account (pending, approved, rejected).

Parameter Transformations

Some parameters are post-processed using transform scripts after being read from the request but before validation or workflow execution. Only parameters with a transform script are listed below.

No parameters are transformed in this API.

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the updateProfile Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({$and:[{id:this.userId},{isActive:true}]}), {"path":"services[0].businessLogic[2].whereClause.fullWhereClause"})

Data Clause

Defines custom field-value assignments used to modify or augment the default payload for create and update operations. These settings override values derived from the session or parameters if explicitly provided.", Note that a default data clause is always prepared by Mindbricks using data property settings, however any property in the data clause can be override by Data Clause Settings.

An update data clause populates all update-allowed properties of a data object, however the null properties (that are not provided by client) are ignored in db layer.

Custom Data Clause Override No custom data clause override configured

Actual Data Clause

The business api will use the following data clause. Note that any calculated value will be added to the data clause in the api manager.

{
  fullname: this.fullname,
  avatar: this.avatar,
  approvalStatus: this.approvalStatus,
}

Business Logic Workflow

[1] Step : startBusinessApi

Manager initializes context, prepares request and session objects, and sets up internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Manager reads parameters from the request or Redis, applies defaults, and writes them into context for downstream milestones.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Manager executes parameter transform scripts and derives any helper values or reshaped payloads into the context.


[4] Step : checkParameters

Manager validates required parameters, checks ID formats (UUID/ObjectId), and ensures all preconditions for update are met.


[5] Step : checkBasicAuth

Manager performs login verification, role, and permission checks, enforcing tenant and access rules before update.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildWhereClause

Manager constructs the WHERE clause used to identify the record to update, applying ownership and parent checks if necessary.

You can use the following settings to change some behavior of this step. whereClause

[7] Step : fetchInstance

Manager fetches the existing record from the database and writes it to the context for validation or enrichment.


[8] Step : checkInstance

Manager performs instance-level validations, including ownership, existence, lock status, or other pre-update checks.


[9] Step : buildDataClause

Manager prepares the data clause for the update, applying transformations or enhancements before persisting.

You can use the following settings to change some behavior of this step. dataClause

[10] Step : mainUpdateOperation

Manager executes the update operation with the WHERE and data clauses. Database-level events are raised if configured.


[11] Step : buildOutput

Manager assembles the response object from the update result, masking fields or injecting additional metadata.


[12] Step : sendResponse

Manager sends the response back to the controller for delivery to the client.


[13] Step : raiseApiEvent

Manager triggers API-level events, sending relevant messages to Kafka or other integrations if configured.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The updateProfile api has got 4 regular client parameters

Parameter Type Required Population
userId ID true request.params?.[“userId”]
fullname String false request.body?.[“fullname”]
avatar String false request.body?.[“avatar”]
approvalStatus Enum false request.body?.[“approvalStatus”]

REST Request

To access the api you can use the REST controller with the path PATCH /v1/profile/:userId

  axios({
    method: 'PATCH',
    url: `/v1/profile/${userId}`,
    data: {
            fullname:"String",  
            avatar:"String",  
            approvalStatus:"Enum",  
    
    },
    params: {
    
        }
  });

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the user object in the respones. However, some properties may be omitted based on the object’s internal logic.

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "user",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"user": {
		"id": "ID",
		"email": "String",
		"password": "String",
		"fullname": "String",
		"avatar": "String",
		"roleId": "String",
		"emailVerified": "Boolean",
		"approvalStatus": "Enum",
		"approvalStatus_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Business API Design Specification - Create User

Business API Design Specification - Create User

A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic.

While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized.

This document provides an in-depth explanation of the architectural design of the createUser Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side.

Main Data Object and CRUD Operation

The createUser Business API is designed to handle a create operation on the User data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

This api is used by admin roles to create a new user manually from admin panels

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The createUser Business API includes a REST controller that can be triggered via the following route:

/v1/users

By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the Parameters section.

gRPC Controller

The createUser Business API includes a gRPC controller that can be triggered via the following function:

createUser()

By calling this gRPC endpoint using a gRPC client, you can execute the Business API. Note that all parameters must be provided as function arguments, regardless of their HTTP location configuration, which is relevant only for the REST controller.

MCP Tool

REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This createUser Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The createUser Business API has 5 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client.

Business API parameters can be:

Regular Parameters

Name Type Required Default Location Data Path
userId ID No - body userId
Description: This id paremeter is used to create the data object with a given specific id. Leave null for automatic id.
avatar String No - body avatar
Description: The avatar url of the user. If not sent, a default random one will be generated.
email String Yes - body email
Description: A string value to represent the user’s email.
password String Yes - body password
Description: A string value to represent the user’s password. It will be stored as hashed.
fullname String Yes - body fullname
Description: A string value to represent the fullname of the user

Parameter Transformations

Some parameters are post-processed using transform scripts after being read from the request but before validation or workflow execution. Only parameters with a transform script are listed below.

this.avatar = 
  runMScript(() => (this.avatar ? `https://gravatar.com/avatar/${LIB.common.md5(this.email ?? 'nullValue')}?s=200&d=identicon` : null), {"path":"services[0].businessLogic[3].customParameters[0].transform"})

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the createUser Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Data Clause

Defines custom field-value assignments used to modify or augment the default payload for create and update operations. These settings override values derived from the session or parameters if explicitly provided.", Note that a default data clause is always prepared by Mindbricks using data property settings, however any property in the data clause can be override by Data Clause Settings.

Custom Data Clause Override No custom data clause override configured

Actual Data Clause

The business api will use the following data clause. Note that any calculated value will be added to the data clause in the api manager.

{
  id: this.userId,
  email: this.email,
  password: this.hashString(this.password),
  fullname: this.fullname,
  avatar: this.avatar,
  isActive: true,
  _archivedAt: null,
}

Business Logic Workflow

[1] Step : startBusinessApi

Manager initializes context, populates session and request objects, prepares internal structures for parameter handling and workflow execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Manager reads input parameters, normalizes missing values, applies default type casting, and stores them in the API context.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Manager transforms parameters, computes derived values, flattens or remaps arrays/objects, and adjusts formats for downstream processing.


[4] Step : checkParameters

Manager executes built-in validations: required field checks, type enforcement, and basic business rules. Prevents operation if validation fails.


[5] Action : validateEmail

Action Type: ValidationAction

Validates that the provided email address has a valid format

class Api {
  async validateEmail() {
    const isValid = runMScript(
      () => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(this.email),
      {
        path: "services[0].businessLogic[3].actions.validationActions[0].validationScript",
      },
    );

    if (!isValid) {
      throw new BadRequestError("InvalidEmailFormat");
    }
    return isValid;
  }
}

[6] Action : fetchArchivedUser

Action Type: FetchObjectAction

Check and get if any deleted user exists with the same identifier

class Api {
  async fetchArchivedUser() {
    // Fetch Object on childObject user

    const userQuery = runMScript(
      () => ({
        $and: [
          { email: this.email, isActive: false },
          {
            _archivedAt: {
              $gte: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000),
            },
          },
        ],
      }),
      {
        path: "services[0].businessLogic[3].actions.fetchObjectActions[0].whereClause",
      },
    );

    const { convertUserQueryToSequelizeQuery } = require("common");
    const scriptQuery = convertUserQueryToSequelizeQuery(userQuery);

    // get object from db
    const data = await getUserByQuery(scriptQuery);

    return data
      ? {
          id: data["id"],
        }
      : null;
  }
}

[7] Action : checkArchivedUser

Action Type: ValidationAction

Prevents re-register of a user when their profile is still in 30days archive

class Api {
  async checkArchivedUser() {
    const isError = runMScript(() => this.archivedUser?.email != null, {
      path: "services[0].businessLogic[3].actions.validationActions[1].validationScript",
    });

    if (isError) {
      throw new BadRequestError("ThisProfileIsArchivedPleaseLoginToRestore");
    }
    return isError;
  }
}

[8] Step : checkBasicAuth

Manager performs authentication and authorization checks: verifies session, user roles, permissions, and tenant restrictions.

You can use the following settings to change some behavior of this step. authOptions

[9] Step : buildDataClause

Manager constructs the final data object for creation, fills auto-generated fields (IDs, timestamps, owner fields), and ensures schema consistency.

You can use the following settings to change some behavior of this step. dataClause

[10] Step : mainCreateOperation

Manager executes the database insert operation, updates indexes/caches, and triggers internal post-processing like linked default records.


[11] Step : buildOutput

Manager shapes the response: masks sensitive fields, resolves linked references, and formats output according to API contract.


[12] Action : writeVerificationNeedsToResponse

Action Type: AddToResponseAction

Set if email or mobile verification needed

class Api {
  async writeVerificationNeedsToResponse() {
    try {
      this.output["emailVerificationNeeded"] = runMScript(() => false, {
        path: "services[0].businessLogic[3].actions.addToResponseActions[0].context[0].contextValue",
      });

      this.output["mobileVerificationNeeded"] = runMScript(() => false, {
        path: "services[0].businessLogic[3].actions.addToResponseActions[0].context[1].contextValue",
      });

      return true;
    } catch (error) {
      console.error("AddToResponseAction error:", error);
      throw error;
    }
  }
}

[13] Step : sendResponse

Manager sends the response to the client and finalizes internal tasks like flushing logs or updating session state.


[14] Step : raiseApiEvent

Manager triggers API-level events (Kafka, WebSocket, async workflows) as the final internal step.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The createUser api has got 4 regular client parameters

Parameter Type Required Population
avatar String false request.body?.[“avatar”]
email String true request.body?.[“email”]
password String true request.body?.[“password”]
fullname String true request.body?.[“fullname”]

REST Request

To access the api you can use the REST controller with the path POST /v1/users

  axios({
    method: 'POST',
    url: '/v1/users',
    data: {
            avatar:"String",  
            email:"String",  
            password:"String",  
            fullname:"String",  
    
    },
    params: {
    
        }
  });

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the user object in the respones. However, some properties may be omitted based on the object’s internal logic.

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "user",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"user": {
		"id": "ID",
		"email": "String",
		"password": "String",
		"fullname": "String",
		"avatar": "String",
		"roleId": "String",
		"emailVerified": "Boolean",
		"approvalStatus": "Enum",
		"approvalStatus_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Business API Design Specification - Delete User

Business API Design Specification - Delete User

A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic.

While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized.

This document provides an in-depth explanation of the architectural design of the deleteUser Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side.

Main Data Object and CRUD Operation

The deleteUser Business API is designed to handle a delete operation on the User data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

This api is used by admins to delete user profiles.

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The deleteUser Business API includes a REST controller that can be triggered via the following route:

/v1/users/:userId

By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the Parameters section.

gRPC Controller

The deleteUser Business API includes a gRPC controller that can be triggered via the following function:

deleteUser()

By calling this gRPC endpoint using a gRPC client, you can execute the Business API. Note that all parameters must be provided as function arguments, regardless of their HTTP location configuration, which is relevant only for the REST controller.

MCP Tool

REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This deleteUser Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The deleteUser Business API has 1 parameter that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client.

Business API parameters can be:

Regular Parameters

Name Type Required Default Location Data Path
userId ID Yes - urlpath userId
Description: This id paremeter is used to select the required data object that will be deleted

Parameter Transformations

Some parameters are post-processed using transform scripts after being read from the request but before validation or workflow execution. Only parameters with a transform script are listed below.

No parameters are transformed in this API.

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the deleteUser Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({$and:[{id:this.userId},{isActive:true}]}), {"path":"services[0].businessLogic[4].whereClause.fullWhereClause"})

Delete Options

Use these options to set delete specific settings.

useSoftDelete: If true, the record will be marked as deleted (isActive: false) instead of removed. The implementation depends on the data object’s soft delete configuration.

Business Logic Workflow

[1] Step : startBusinessApi

Manager initializes context, prepares request/session objects, and sets up internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Manager reads and normalizes parameters, applies defaults, and stores them in the context for downstream steps.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Manager executes parameter transform scripts, computes derived values, and remaps objects or arrays as needed for later processing.


[4] Step : checkParameters

Manager runs built-in validations including required field checks, type enforcement, and deletion preconditions. Stops execution if validation fails.


[5] Step : checkBasicAuth

Manager validates session, user roles, permissions, and tenant-specific access rules to enforce basic auth restrictions.

You can use the following settings to change some behavior of this step. authOptions

[6] Action : setRolesOrder

Action Type: CreateObjectAction

Sets the hiyerarchy of the roles to check user permissions on other users

class Api {
  async setRolesOrder() {
    // Construct base object
    const obj = {};

    // Merge dynamic object
    Object.assign(
      obj,
      runMScript(
        () => ({
          superAdmin: 20,
          saasAdmin: 19,
          admin: 18,
          tenantOwner: 17,
          tenantAdmin: 16,
          saasUser: 15,
          tenantUser: 0,
          user: 0,
        }),
        {
          path: "services[0].businessLogic[4].actions.createObjectActions[0].mergeObject",
        },
      ),
    );

    return obj;
  }
}

[7] Action : protectSuperAdmin

Action Type: ValidationAction

Prevents deletion of the SuperAdmin account. This safeguard ensures that the SuperAdmin userId cannot be removed under any circumstances.

class Api {
  async protectSuperAdmin() {
    const isError = runMScript(() => this.userId == this.auth?.superAdminId, {
      path: "services[0].businessLogic[4].actions.validationActions[0].validationScript",
    });

    if (isError) {
      throw new BadRequestError("SuperAdminCantBeDeleted");
    }
    return isError;
  }
}

[8] Step : buildWhereClause

Manager generates the query conditions, applies ownership and parent checks, and ensures the clause is correct for the delete operation.

You can use the following settings to change some behavior of this step. whereClause

[9] Step : fetchInstance

Manager fetches the target record, applies filters from WHERE clause, and writes the instance to the context for further checks.


[10] Step : checkInstance

Manager performs object-level validations such as lock status, soft-delete eligibility, and multi-step approval enforcement.


[11] Action : protectHigherRole

Action Type: ValidationAction

Prevents the delete of a higher or equal user role

class Api {
  async protectHigherRole() {
    const isValid = runMScript(
      () =>
        (this._r[this.session?.roleId] ?? 0) >
        (this._r[this.user?.roleId] ?? 0),
      {
        path: "services[0].businessLogic[4].actions.validationActions[1].validationScript",
      },
    );

    if (!isValid) {
      throw new BadRequestError("AHigherOrEqualUserRoleCantBeDeleted");
    }
    return isValid;
  }
}

[12] Step : mainDeleteOperation

Manager executes the delete query, updates related indexes/caches, and handles soft/hard delete logic according to configuration.

You can use the following settings to change some behavior of this step. deleteOptions

[13] Action : deleteUserSessions

Action Type: FunctionCallAction

Makes a call to this.auth to delete the sessions of the deleted user.

class Api {
  async deleteUserSessions() {
    try {
      return await runMScript(
        () =>
          (async () =>
            await (async (userId) => {
              await this.auth.deleteUserSessions(userId);
            })(this.userId))(),
        {
          path: "services[0].businessLogic[4].actions.functionCallActions[0].callScript",
        },
      );
    } catch (err) {
      console.error("Error in FunctionCallAction deleteUserSessions:", err);
      throw err;
    }
  }
}

[14] Step : buildOutput

Manager shapes the response payload, masks sensitive fields, and formats related cleanup results for output.


[15] Step : sendResponse

Manager delivers the response to the client and finalizes any temporary internal structures.


[16] Step : raiseApiEvent

Manager triggers asynchronous API events, notifies queues or streams, and performs final cleanup for the workflow.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The deleteUser api has got 1 regular client parameter

Parameter Type Required Population
userId ID true request.params?.[“userId”]

REST Request

To access the api you can use the REST controller with the path DELETE /v1/users/:userId

  axios({
    method: 'DELETE',
    url: `/v1/users/${userId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the user object in the respones. However, some properties may be omitted based on the object’s internal logic.

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "user",
	"method": "DELETE",
	"action": "delete",
	"appVersion": "Version",
	"rowCount": 1,
	"user": {
		"id": "ID",
		"email": "String",
		"password": "String",
		"fullname": "String",
		"avatar": "String",
		"roleId": "String",
		"emailVerified": "Boolean",
		"approvalStatus": "Enum",
		"approvalStatus_idx": "Integer",
		"isActive": false,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Business API Design Specification - Archive Profile

Business API Design Specification - Archive Profile

A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic.

While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized.

This document provides an in-depth explanation of the architectural design of the archiveProfile Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side.

Main Data Object and CRUD Operation

The archiveProfile Business API is designed to handle a delete operation on the User data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

This api is used by users to archive their profiles.

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The archiveProfile Business API includes a REST controller that can be triggered via the following route:

/v1/archiveprofile/:userId

By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the Parameters section.

gRPC Controller

The archiveProfile Business API includes a gRPC controller that can be triggered via the following function:

archiveProfile()

By calling this gRPC endpoint using a gRPC client, you can execute the Business API. Note that all parameters must be provided as function arguments, regardless of their HTTP location configuration, which is relevant only for the REST controller.

MCP Tool

REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This archiveProfile Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The archiveProfile Business API has 1 parameter that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client.

Business API parameters can be:

Regular Parameters

Name Type Required Default Location Data Path
userId ID Yes - urlpath userId
Description: This id paremeter is used to select the required data object that will be deleted

Parameter Transformations

Some parameters are post-processed using transform scripts after being read from the request but before validation or workflow execution. Only parameters with a transform script are listed below.

No parameters are transformed in this API.

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the archiveProfile Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({$and:[{id:this.userId},{isActive:true}]}), {"path":"services[0].businessLogic[5].whereClause.fullWhereClause"})

Delete Options

Use these options to set delete specific settings.

useSoftDelete: If true, the record will be marked as deleted (isActive: false) instead of removed. The implementation depends on the data object’s soft delete configuration.

Business Logic Workflow

[1] Step : startBusinessApi

Manager initializes context, prepares request/session objects, and sets up internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Manager reads and normalizes parameters, applies defaults, and stores them in the context for downstream steps.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Manager executes parameter transform scripts, computes derived values, and remaps objects or arrays as needed for later processing.


[4] Step : checkParameters

Manager runs built-in validations including required field checks, type enforcement, and deletion preconditions. Stops execution if validation fails.


[5] Step : checkBasicAuth

Manager validates session, user roles, permissions, and tenant-specific access rules to enforce basic auth restrictions.

You can use the following settings to change some behavior of this step. authOptions

[6] Action : protectSuperAdmin

Action Type: ValidationAction

Prevents deletion of the SuperAdmin account. This safeguard ensures that the SuperAdmin userId cannot be removed under any circumstances.

class Api {
  async protectSuperAdmin() {
    const isError = runMScript(() => this.userId == this.auth?.superAdminId, {
      path: "services[0].businessLogic[5].actions.validationActions[0].validationScript",
    });

    if (isError) {
      throw new BadRequestError("SuperAdminCantBeDeleted");
    }
    return isError;
  }
}

[7] Step : buildWhereClause

Manager generates the query conditions, applies ownership and parent checks, and ensures the clause is correct for the delete operation.

You can use the following settings to change some behavior of this step. whereClause

[8] Step : fetchInstance

Manager fetches the target record, applies filters from WHERE clause, and writes the instance to the context for further checks.


[9] Step : checkInstance

Manager performs object-level validations such as lock status, soft-delete eligibility, and multi-step approval enforcement.


[10] Step : mainDeleteOperation

Manager executes the delete query, updates related indexes/caches, and handles soft/hard delete logic according to configuration.

You can use the following settings to change some behavior of this step. deleteOptions

[11] Action : deleteUserSessions

Action Type: FunctionCallAction

Makes a call to this.auth to delete the sessions of the deleted user.

class Api {
  async deleteUserSessions() {
    try {
      return await runMScript(
        () =>
          (async () =>
            await (async (userId) => {
              await this.auth.deleteUserSessions(userId);
            })(this.userId))(),
        {
          path: "services[0].businessLogic[5].actions.functionCallActions[0].callScript",
        },
      );
    } catch (err) {
      console.error("Error in FunctionCallAction deleteUserSessions:", err);
      throw err;
    }
  }
}

[12] Step : buildOutput

Manager shapes the response payload, masks sensitive fields, and formats related cleanup results for output.


[13] Step : sendResponse

Manager delivers the response to the client and finalizes any temporary internal structures.


[14] Step : raiseApiEvent

Manager triggers asynchronous API events, notifies queues or streams, and performs final cleanup for the workflow.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The archiveProfile api has got 1 regular client parameter

Parameter Type Required Population
userId ID true request.params?.[“userId”]

REST Request

To access the api you can use the REST controller with the path DELETE /v1/archiveprofile/:userId

  axios({
    method: 'DELETE',
    url: `/v1/archiveprofile/${userId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the user object in the respones. However, some properties may be omitted based on the object’s internal logic.

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "user",
	"method": "DELETE",
	"action": "delete",
	"appVersion": "Version",
	"rowCount": 1,
	"user": {
		"id": "ID",
		"email": "String",
		"password": "String",
		"fullname": "String",
		"avatar": "String",
		"roleId": "String",
		"emailVerified": "Boolean",
		"approvalStatus": "Enum",
		"approvalStatus_idx": "Integer",
		"isActive": false,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Business API Design Specification - List Users

Business API Design Specification - List Users

A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic.

While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized.

This document provides an in-depth explanation of the architectural design of the listUsers Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side.

Main Data Object and CRUD Operation

The listUsers Business API is designed to handle a list operation on the User data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

The list of users is filtered by the tenantId.

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The listUsers Business API includes a REST controller that can be triggered via the following route:

/v1/users

By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the Parameters section.

gRPC Controller

The listUsers Business API includes a gRPC controller that can be triggered via the following function:

listUsers()

By calling this gRPC endpoint using a gRPC client, you can execute the Business API. Note that all parameters must be provided as function arguments, regardless of their HTTP location configuration, which is relevant only for the REST controller.

MCP Tool

REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This listUsers Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The listUsers Business API has 3 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client.

Business API parameters can be:

Filter Parameters

The listUsers api supports 3 optional filter parameters for filtering list results using URL query parameters. These parameters are only available for list type APIs.

email Filter

Type: String
Description: A string value to represent the user’s email.
Location: Query Parameter

Usage:

Non-Array Property (Case-Insensitive Partial Matching):

Examples:

// Find records with "john" in the field (case-insensitive partial match)
GET /v1/users?email=john
// Matches: "John", "Johnny", "johnson", "McJohn", etc.

// Find records with multiple values (use multiple parameters)
GET /v1/users?email=laptop&email=phone&email=tablet
// Matches records containing "laptop", "phone", or "tablet" anywhere in the field

// Find records without this field
GET /v1/users?email=null

fullname Filter

Type: String
Description: A string value to represent the fullname of the user
Location: Query Parameter

Usage:

Non-Array Property (Case-Insensitive Partial Matching):

Examples:

// Find records with "john" in the field (case-insensitive partial match)
GET /v1/users?fullname=john
// Matches: "John", "Johnny", "johnson", "McJohn", etc.

// Find records with multiple values (use multiple parameters)
GET /v1/users?fullname=laptop&fullname=phone&fullname=tablet
// Matches records containing "laptop", "phone", or "tablet" anywhere in the field

// Find records without this field
GET /v1/users?fullname=null

roleId Filter

Type: String
Description: A string value to represent the roleId of the user.
Location: Query Parameter

Usage:

Non-Array Property (Case-Insensitive Partial Matching):

Examples:

// Find records with "john" in the field (case-insensitive partial match)
GET /v1/users?roleId=john
// Matches: "John", "Johnny", "johnson", "McJohn", etc.

// Find records with multiple values (use multiple parameters)
GET /v1/users?roleId=laptop&roleId=phone&roleId=tablet
// Matches records containing "laptop", "phone", or "tablet" anywhere in the field

// Find records without this field
GET /v1/users?roleId=null

Parameter Transformations

Some parameters are post-processed using transform scripts after being read from the request but before validation or workflow execution. Only parameters with a transform script are listed below.

No parameters are transformed in this API.

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the listUsers Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Select Clause

Specifies which fields will be selected from the main data object during a get or list operation. Leave blank to select all properties. This applies only to get and list type APIs.",

``

Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({isActive:true}), {"path":"services[0].businessLogic[6].whereClause.fullWhereClause"})

List Options

Defines list-specific options including filtering logic, default sorting, and result customization for APIs that return multiple records.

List Sort By Sort order definitions for the result set. Multiple fields can be provided with direction (asc/desc).

[ id asc ]

List Group By Grouping definitions for the result set. This is typically used for visual or report-based grouping.

The list is not grouped.

setAsRead: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed.

No setAsread field-value pair is configured.

Permission Filter Optional filter that applies permission constraints dynamically based on session or object roles. So that the list items are filtered by the user’s OBAC or ABAC permissions.

Permission filter is not active at the moment. Follow Mindbricks updates to be able to use it.

Pagination Options

Contains settings to configure pagination behavior for list APIs. Includes options like page size, offset, cursor support, and total count inclusion.

Business Logic Workflow

[1] Step : startBusinessApi

Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Reads request and Redis parameters, applies defaults, and writes them to context for downstream processing.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Transforms and normalizes parameters, derives dependent values, and reshapes inputs for the main list query.


[4] Step : checkParameters

Executes validation logic on required and custom parameters, enforcing business rules and cross-field consistency.


[5] Step : checkBasicAuth

Performs role-based access checks and applies dynamic membership or session-based restrictions.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildWhereClause

Constructs the main query WHERE clause and applies optional filters or scoped access controls.

You can use the following settings to change some behavior of this step. whereClause

[7] Step : mainListOperation

Executes the paginated database query, retrieves the list, and stores results in context for enrichment.

You can use the following settings to change some behavior of this step. selectClause, listOptions, paginationOptions

[8] Step : buildOutput

Assembles the list response, sanitizes sensitive fields, applies transformations, and injects extra context if needed.


[9] Step : sendResponse

Sends the paginated list to the client through the controller.


[10] Step : raiseApiEvent

Triggers optional post-workflow events, such as Kafka messages, logs, or system notifications.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The listUsers api has 3 filter parameters available for filtering list results. See the Filter Parameters section above for detailed usage examples.

Filter Parameter Type Array Property Description
email String No A string value to represent the user’s email.
fullname String No A string value to represent the fullname of the user
roleId String No A string value to represent the roleId of the user.

REST Request

To access the api you can use the REST controller with the path GET /v1/users

  axios({
    method: 'GET',
    url: '/v1/users',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section for usage examples)
        // email: '<value>' // Filter by email
        // fullname: '<value>' // Filter by fullname
        // roleId: '<value>' // Filter by roleId
            }
  });

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the users object in the respones. However, some properties may be omitted based on the object’s internal logic.

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "users",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"users": [
		{
			"id": "ID",
			"email": "String",
			"password": "String",
			"fullname": "String",
			"avatar": "String",
			"roleId": "String",
			"emailVerified": "Boolean",
			"approvalStatus": "Enum",
			"approvalStatus_idx": "Integer",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID"
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Business API Design Specification - Search Users

Business API Design Specification - Search Users

A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic.

While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized.

This document provides an in-depth explanation of the architectural design of the searchUsers Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side.

Main Data Object and CRUD Operation

The searchUsers Business API is designed to handle a list operation on the User data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

The list of users is filtered by the tenantId.

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The searchUsers Business API includes a REST controller that can be triggered via the following route:

/v1/searchusers

By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the Parameters section.

gRPC Controller

The searchUsers Business API includes a gRPC controller that can be triggered via the following function:

searchUsers()

By calling this gRPC endpoint using a gRPC client, you can execute the Business API. Note that all parameters must be provided as function arguments, regardless of their HTTP location configuration, which is relevant only for the REST controller.

MCP Tool

REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This searchUsers Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The searchUsers Business API has 2 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client.

Business API parameters can be:

Regular Parameters

Name Type Required Default Location Data Path
keyword String Yes - query keyword
Description: -

Filter Parameters

The searchUsers api supports 1 optional filter parameter for filtering list results using URL query parameters. These parameters are only available for list type APIs.

roleId Filter

Type: String
Description: A string value to represent the roleId of the user.
Location: Query Parameter

Usage:

Non-Array Property (Case-Insensitive Partial Matching):

Examples:

// Find records with "john" in the field (case-insensitive partial match)
GET /v1/searchusers?roleId=john
// Matches: "John", "Johnny", "johnson", "McJohn", etc.

// Find records with multiple values (use multiple parameters)
GET /v1/searchusers?roleId=laptop&roleId=phone&roleId=tablet
// Matches records containing "laptop", "phone", or "tablet" anywhere in the field

// Find records without this field
GET /v1/searchusers?roleId=null

Parameter Transformations

Some parameters are post-processed using transform scripts after being read from the request but before validation or workflow execution. Only parameters with a transform script are listed below.

No parameters are transformed in this API.

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the searchUsers Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Select Clause

Specifies which fields will be selected from the main data object during a get or list operation. Leave blank to select all properties. This applies only to get and list type APIs.",

``

Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({isActive:true}), {"path":"services[0].businessLogic[7].whereClause.fullWhereClause"})

List Options

Defines list-specific options including filtering logic, default sorting, and result customization for APIs that return multiple records.

List Sort By Sort order definitions for the result set. Multiple fields can be provided with direction (asc/desc).

[ id asc ]

List Group By Grouping definitions for the result set. This is typically used for visual or report-based grouping.

The list is not grouped.

setAsRead: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed.

No setAsread field-value pair is configured.

Permission Filter Optional filter that applies permission constraints dynamically based on session or object roles. So that the list items are filtered by the user’s OBAC or ABAC permissions.

Permission filter is not active at the moment. Follow Mindbricks updates to be able to use it.

Pagination Options

Contains settings to configure pagination behavior for list APIs. Includes options like page size, offset, cursor support, and total count inclusion.

Business Logic Workflow

[1] Step : startBusinessApi

Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Reads request and Redis parameters, applies defaults, and writes them to context for downstream processing.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Transforms and normalizes parameters, derives dependent values, and reshapes inputs for the main list query.


[4] Step : checkParameters

Executes validation logic on required and custom parameters, enforcing business rules and cross-field consistency.


[5] Step : checkBasicAuth

Performs role-based access checks and applies dynamic membership or session-based restrictions.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildWhereClause

Constructs the main query WHERE clause and applies optional filters or scoped access controls.

You can use the following settings to change some behavior of this step. whereClause

[7] Step : mainListOperation

Executes the paginated database query, retrieves the list, and stores results in context for enrichment.

You can use the following settings to change some behavior of this step. selectClause, listOptions, paginationOptions

[8] Step : buildOutput

Assembles the list response, sanitizes sensitive fields, applies transformations, and injects extra context if needed.


[9] Step : sendResponse

Sends the paginated list to the client through the controller.


[10] Step : raiseApiEvent

Triggers optional post-workflow events, such as Kafka messages, logs, or system notifications.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The searchUsers api has got 1 regular client parameter

Parameter Type Required Population
keyword String true request.query?.[“keyword”]

The searchUsers api has 1 filter parameter available for filtering list results. See the Filter Parameters section above for detailed usage examples.

Filter Parameter Type Array Property Description
roleId String No A string value to represent the roleId of the user.

REST Request

To access the api you can use the REST controller with the path GET /v1/searchusers

  axios({
    method: 'GET',
    url: '/v1/searchusers',
    data: {
    
    },
    params: {
             keyword:'"String"',  
    
        // Filter parameters (see Filter Parameters section for usage examples)
        // roleId: '<value>' // Filter by roleId
            }
  });

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the users object in the respones. However, some properties may be omitted based on the object’s internal logic.

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "users",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"users": [
		{
			"id": "ID",
			"email": "String",
			"password": "String",
			"fullname": "String",
			"avatar": "String",
			"roleId": "String",
			"emailVerified": "Boolean",
			"approvalStatus": "Enum",
			"approvalStatus_idx": "Integer",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID"
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Business API Design Specification - Update Userrole

Business API Design Specification - Update Userrole

A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic.

While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized.

This document provides an in-depth explanation of the architectural design of the updateUserRole Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side.

Main Data Object and CRUD Operation

The updateUserRole Business API is designed to handle a update operation on the User data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

This route is used by admin roles to update the user role.The default role is user when a user is registered. A user’s role can be updated by superAdmin or admin

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The updateUserRole Business API includes a REST controller that can be triggered via the following route:

/v1/userrole/:userId

By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the Parameters section.

gRPC Controller

The updateUserRole Business API includes a gRPC controller that can be triggered via the following function:

updateUserRole()

By calling this gRPC endpoint using a gRPC client, you can execute the Business API. Note that all parameters must be provided as function arguments, regardless of their HTTP location configuration, which is relevant only for the REST controller.

MCP Tool

REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This updateUserRole Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The updateUserRole Business API has 2 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client.

Business API parameters can be:

Regular Parameters

Name Type Required Default Location Data Path
userId ID Yes - urlpath userId
Description: This id paremeter is used to select the required data object that will be updated
roleId String Yes - body roleId
Description: The new roleId of the user to be updated

Parameter Transformations

Some parameters are post-processed using transform scripts after being read from the request but before validation or workflow execution. Only parameters with a transform script are listed below.

No parameters are transformed in this API.

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the updateUserRole Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({$and:[{id:this.userId},{isActive:true}]}), {"path":"services[0].businessLogic[8].whereClause.fullWhereClause"})

Data Clause

Defines custom field-value assignments used to modify or augment the default payload for create and update operations. These settings override values derived from the session or parameters if explicitly provided.", Note that a default data clause is always prepared by Mindbricks using data property settings, however any property in the data clause can be override by Data Clause Settings.

An update data clause populates all update-allowed properties of a data object, however the null properties (that are not provided by client) are ignored in db layer.

Custom Data Clause Override

{
    roleId: runMScript(() => (this.roleId), {"path":"services[0].businessLogic[8].dataClause.customData[0].value"}),
   
}

Actual Data Clause

The business api will use the following data clause. Note that any calculated value will be added to the data clause in the api manager.

{
  // roleId parameter is closed to update by client request 
  // include it in data clause unless you are sure 
  roleId: runMScript(() => (this.roleId), {"path":"services[0].businessLogic[8].dataClause.customData[0].value"}),
}

Business Logic Workflow

[1] Step : startBusinessApi

Manager initializes context, prepares request and session objects, and sets up internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Manager reads parameters from the request or Redis, applies defaults, and writes them into context for downstream milestones.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Manager executes parameter transform scripts and derives any helper values or reshaped payloads into the context.


[4] Step : checkParameters

Manager validates required parameters, checks ID formats (UUID/ObjectId), and ensures all preconditions for update are met.


[5] Step : checkBasicAuth

Manager performs login verification, role, and permission checks, enforcing tenant and access rules before update.

You can use the following settings to change some behavior of this step. authOptions

[6] Action : setRolesOrder

Action Type: CreateObjectAction

Sets the hiyerarchy of the roles to check user permissions on other users

class Api {
  async setRolesOrder() {
    // Construct base object
    const obj = {};

    // Merge dynamic object
    Object.assign(
      obj,
      runMScript(
        () => ({
          superAdmin: 20,
          saasAdmin: 19,
          admin: 18,
          tenantOwner: 17,
          tenantAdmin: 16,
          saasUser: 15,
          tenantUser: 0,
          user: 0,
        }),
        {
          path: "services[0].businessLogic[8].actions.createObjectActions[0].mergeObject",
        },
      ),
    );

    return obj;
  }
}

[7] Action : preventHigherRoleSet

Action Type: ValidationAction

Prevents to set a user’s role as higher than or equal to the setter role

class Api {
  async preventHigherRoleSet() {
    const isValid = runMScript(
      () => (this._r[this.session.roleId] ?? 0) > (this._r[this.roleId] ?? 0),
      {
        path: "services[0].businessLogic[8].actions.validationActions[0].validationScript",
      },
    );

    if (!isValid) {
      throw new BadRequestError("AHigherRoleCantBeAssigned");
    }
    return isValid;
  }
}

[8] Step : buildWhereClause

Manager constructs the WHERE clause used to identify the record to update, applying ownership and parent checks if necessary.

You can use the following settings to change some behavior of this step. whereClause

[9] Step : fetchInstance

Manager fetches the existing record from the database and writes it to the context for validation or enrichment.


[10] Action : protectHigherRole

Action Type: ValidationAction

Prevents the update of a higher or equal user role

class Api {
  async protectHigherRole() {
    const isValid = runMScript(
      () =>
        (this._r[this.session.roleId] ?? 0) > (this._r[this.user.roleId] ?? 0),
      {
        path: "services[0].businessLogic[8].actions.validationActions[1].validationScript",
      },
    );

    if (!isValid) {
      throw new BadRequestError("AHigherUserRoleCantBeChanged");
    }
    return isValid;
  }
}

[11] Step : checkInstance

Manager performs instance-level validations, including ownership, existence, lock status, or other pre-update checks.


[12] Step : buildDataClause

Manager prepares the data clause for the update, applying transformations or enhancements before persisting.

You can use the following settings to change some behavior of this step. dataClause

[13] Step : mainUpdateOperation

Manager executes the update operation with the WHERE and data clauses. Database-level events are raised if configured.


[14] Step : buildOutput

Manager assembles the response object from the update result, masking fields or injecting additional metadata.


[15] Step : sendResponse

Manager sends the response back to the controller for delivery to the client.


[16] Step : raiseApiEvent

Manager triggers API-level events, sending relevant messages to Kafka or other integrations if configured.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The updateUserRole api has got 2 regular client parameters

Parameter Type Required Population
userId ID true request.params?.[“userId”]
roleId String true request.body?.[“roleId”]

REST Request

To access the api you can use the REST controller with the path PATCH /v1/userrole/:userId

  axios({
    method: 'PATCH',
    url: `/v1/userrole/${userId}`,
    data: {
            roleId:"String",  
    
    },
    params: {
    
        }
  });

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the user object in the respones. However, some properties may be omitted based on the object’s internal logic.

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "user",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"user": {
		"id": "ID",
		"email": "String",
		"password": "String",
		"fullname": "String",
		"avatar": "String",
		"roleId": "String",
		"emailVerified": "Boolean",
		"approvalStatus": "Enum",
		"approvalStatus_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Business API Design Specification - Update Userpassword

Business API Design Specification - Update Userpassword

A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic.

While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized.

This document provides an in-depth explanation of the architectural design of the updateUserPassword Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side.

Main Data Object and CRUD Operation

The updateUserPassword Business API is designed to handle a update operation on the User data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

This route is used to update the password of users in the profile page by users themselves

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The updateUserPassword Business API includes a REST controller that can be triggered via the following route:

/v1/userpassword/:userId

By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the Parameters section.

gRPC Controller

The updateUserPassword Business API includes a gRPC controller that can be triggered via the following function:

updateUserPassword()

By calling this gRPC endpoint using a gRPC client, you can execute the Business API. Note that all parameters must be provided as function arguments, regardless of their HTTP location configuration, which is relevant only for the REST controller.

MCP Tool

REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This updateUserPassword Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The updateUserPassword Business API has 3 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client.

Business API parameters can be:

Regular Parameters

Name Type Required Default Location Data Path
userId ID Yes - urlpath userId
Description: This id paremeter is used to select the required data object that will be updated
oldPassword String Yes - body oldPassword
Description: The old password of the user that will be overridden bu the new one. Send for double check.
newPassword String Yes - body newPassword
Description: The new password of the user to be updated

Parameter Transformations

Some parameters are post-processed using transform scripts after being read from the request but before validation or workflow execution. Only parameters with a transform script are listed below.

this.newPassword = 
  runMScript(() => (this.newPassword ? this.hashString(this.newPassword) : null), {"path":"services[0].businessLogic[9].customParameters[1].transform"})

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the updateUserPassword Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({$and:[{id:this.userId},{isActive:true}]}), {"path":"services[0].businessLogic[9].whereClause.fullWhereClause"})

Data Clause

Defines custom field-value assignments used to modify or augment the default payload for create and update operations. These settings override values derived from the session or parameters if explicitly provided.", Note that a default data clause is always prepared by Mindbricks using data property settings, however any property in the data clause can be override by Data Clause Settings.

An update data clause populates all update-allowed properties of a data object, however the null properties (that are not provided by client) are ignored in db layer.

Custom Data Clause Override

{
    password: runMScript(() => (this.newPassword), {"path":"services[0].businessLogic[9].dataClause.customData[0].value"}),
   
}

Actual Data Clause

The business api will use the following data clause. Note that any calculated value will be added to the data clause in the api manager.

{
  // password parameter is closed to update by client request 
  // include it in data clause unless you are sure 
  password: runMScript(() => (this.newPassword), {"path":"services[0].businessLogic[9].dataClause.customData[0].value"}),
}

Business Logic Workflow

[1] Step : startBusinessApi

Manager initializes context, prepares request and session objects, and sets up internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Manager reads parameters from the request or Redis, applies defaults, and writes them into context for downstream milestones.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Manager executes parameter transform scripts and derives any helper values or reshaped payloads into the context.


[4] Step : checkParameters

Manager validates required parameters, checks ID formats (UUID/ObjectId), and ensures all preconditions for update are met.


[5] Step : checkBasicAuth

Manager performs login verification, role, and permission checks, enforcing tenant and access rules before update.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildWhereClause

Manager constructs the WHERE clause used to identify the record to update, applying ownership and parent checks if necessary.

You can use the following settings to change some behavior of this step. whereClause

[7] Step : fetchInstance

Manager fetches the existing record from the database and writes it to the context for validation or enrichment.


[8] Step : checkInstance

Manager performs instance-level validations, including ownership, existence, lock status, or other pre-update checks.


[9] Action : checkOldPassword

Action Type: ValidationAction

Check if the current password mathces the old password. It is done after the instance is fetched.

class Api {
  async checkOldPassword() {
    if (this.checkAbsolute()) return true;

    const isValid = runMScript(
      () => this.hashCompare(this.oldPassword, this.user.password),
      {
        path: "services[0].businessLogic[9].actions.validationActions[0].validationScript",
      },
    );

    if (!isValid) {
      throw new ForbiddenError("TheOldPasswordDoesNotMatch");
    }
    return isValid;
  }
}

[10] Step : buildDataClause

Manager prepares the data clause for the update, applying transformations or enhancements before persisting.

You can use the following settings to change some behavior of this step. dataClause

[11] Step : mainUpdateOperation

Manager executes the update operation with the WHERE and data clauses. Database-level events are raised if configured.


[12] Step : buildOutput

Manager assembles the response object from the update result, masking fields or injecting additional metadata.


[13] Step : sendResponse

Manager sends the response back to the controller for delivery to the client.


[14] Step : raiseApiEvent

Manager triggers API-level events, sending relevant messages to Kafka or other integrations if configured.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The updateUserPassword api has got 3 regular client parameters

Parameter Type Required Population
userId ID true request.params?.[“userId”]
oldPassword String true request.body?.[“oldPassword”]
newPassword String true request.body?.[“newPassword”]

REST Request

To access the api you can use the REST controller with the path PATCH /v1/userpassword/:userId

  axios({
    method: 'PATCH',
    url: `/v1/userpassword/${userId}`,
    data: {
            oldPassword:"String",  
            newPassword:"String",  
    
    },
    params: {
    
        }
  });

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the user object in the respones. However, some properties may be omitted based on the object’s internal logic.

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "user",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"user": {
		"id": "ID",
		"email": "String",
		"password": "String",
		"fullname": "String",
		"avatar": "String",
		"roleId": "String",
		"emailVerified": "Boolean",
		"approvalStatus": "Enum",
		"approvalStatus_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Business API Design Specification - Update Userpasswordbyadmin

Business API Design Specification - Update Userpasswordbyadmin

A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic.

While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized.

This document provides an in-depth explanation of the architectural design of the updateUserPasswordByAdmin Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side.

Main Data Object and CRUD Operation

The updateUserPasswordByAdmin Business API is designed to handle a update operation on the User data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

This route is used to change any user password by admins only. Superadmin can chnage all passwords, admins can change only nonadmin passwords

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The updateUserPasswordByAdmin Business API includes a REST controller that can be triggered via the following route:

/v1/userpasswordbyadmin/:userId

By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the Parameters section.

gRPC Controller

The updateUserPasswordByAdmin Business API includes a gRPC controller that can be triggered via the following function:

updateUserPasswordByAdmin()

By calling this gRPC endpoint using a gRPC client, you can execute the Business API. Note that all parameters must be provided as function arguments, regardless of their HTTP location configuration, which is relevant only for the REST controller.

MCP Tool

REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This updateUserPasswordByAdmin Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The updateUserPasswordByAdmin Business API has 2 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client.

Business API parameters can be:

Regular Parameters

Name Type Required Default Location Data Path
userId ID Yes - urlpath userId
Description: This id paremeter is used to select the required data object that will be updated
password String Yes - body password
Description: The new password of the user to be updated

Parameter Transformations

Some parameters are post-processed using transform scripts after being read from the request but before validation or workflow execution. Only parameters with a transform script are listed below.

this.password = 
  runMScript(() => (this.password ? this.hashString(this.password) : null), {"path":"services[0].businessLogic[10].customParameters[0].transform"})

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the updateUserPasswordByAdmin Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({$and:[{id:this.userId},{isActive:true}]}), {"path":"services[0].businessLogic[10].whereClause.fullWhereClause"})

Data Clause

Defines custom field-value assignments used to modify or augment the default payload for create and update operations. These settings override values derived from the session or parameters if explicitly provided.", Note that a default data clause is always prepared by Mindbricks using data property settings, however any property in the data clause can be override by Data Clause Settings.

An update data clause populates all update-allowed properties of a data object, however the null properties (that are not provided by client) are ignored in db layer.

Custom Data Clause Override

{
    password: runMScript(() => (this.password), {"path":"services[0].businessLogic[10].dataClause.customData[0].value"}),
   
}

Actual Data Clause

The business api will use the following data clause. Note that any calculated value will be added to the data clause in the api manager.

{
  // password parameter is closed to update by client request 
  // include it in data clause unless you are sure 
  password: runMScript(() => (this.password), {"path":"services[0].businessLogic[10].dataClause.customData[0].value"}),
}

Business Logic Workflow

[1] Step : startBusinessApi

Manager initializes context, prepares request and session objects, and sets up internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Manager reads parameters from the request or Redis, applies defaults, and writes them into context for downstream milestones.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Manager executes parameter transform scripts and derives any helper values or reshaped payloads into the context.


[4] Step : checkParameters

Manager validates required parameters, checks ID formats (UUID/ObjectId), and ensures all preconditions for update are met.


[5] Step : checkBasicAuth

Manager performs login verification, role, and permission checks, enforcing tenant and access rules before update.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildWhereClause

Manager constructs the WHERE clause used to identify the record to update, applying ownership and parent checks if necessary.

You can use the following settings to change some behavior of this step. whereClause

[7] Step : fetchInstance

Manager fetches the existing record from the database and writes it to the context for validation or enrichment.


[8] Step : checkInstance

Manager performs instance-level validations, including ownership, existence, lock status, or other pre-update checks.


[9] Action : setRolesOrder

Action Type: CreateObjectAction

Sets the hiyerarchy of the roles to check user permissions on other users

class Api {
  async setRolesOrder() {
    // Construct base object
    const obj = {};

    // Merge dynamic object
    Object.assign(
      obj,
      runMScript(
        () => ({
          superAdmin: 20,
          saasAdmin: 19,
          admin: 18,
          tenantOwner: 17,
          tenantAdmin: 16,
          saasUser: 15,
          tenantUser: 14,
          user: 13,
        }),
        {
          path: "services[0].businessLogic[10].actions.createObjectActions[0].mergeObject",
        },
      ),
    );

    return obj;
  }
}

[10] Action : protectHigherRole

Action Type: ValidationAction

Prevents the update of a higher or equal user role

class Api {
  async protectHigherRole() {
    const isValid = runMScript(
      () =>
        (this._r[this.session.roleId] ?? 0) > (this._r[this.user.roleId] ?? 0),
      {
        path: "services[0].businessLogic[10].actions.validationActions[0].validationScript",
      },
    );

    if (!isValid) {
      throw new BadRequestError("AHigherUserCantBeUpdated");
    }
    return isValid;
  }
}

[11] Step : buildDataClause

Manager prepares the data clause for the update, applying transformations or enhancements before persisting.

You can use the following settings to change some behavior of this step. dataClause

[12] Step : mainUpdateOperation

Manager executes the update operation with the WHERE and data clauses. Database-level events are raised if configured.


[13] Step : buildOutput

Manager assembles the response object from the update result, masking fields or injecting additional metadata.


[14] Step : sendResponse

Manager sends the response back to the controller for delivery to the client.


[15] Step : raiseApiEvent

Manager triggers API-level events, sending relevant messages to Kafka or other integrations if configured.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The updateUserPasswordByAdmin api has got 2 regular client parameters

Parameter Type Required Population
userId ID true request.params?.[“userId”]
password String true request.body?.[“password”]

REST Request

To access the api you can use the REST controller with the path PATCH /v1/userpasswordbyadmin/:userId

  axios({
    method: 'PATCH',
    url: `/v1/userpasswordbyadmin/${userId}`,
    data: {
            password:"String",  
    
    },
    params: {
    
        }
  });

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the user object in the respones. However, some properties may be omitted based on the object’s internal logic.

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "user",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"user": {
		"id": "ID",
		"email": "String",
		"password": "String",
		"fullname": "String",
		"avatar": "String",
		"roleId": "String",
		"emailVerified": "Boolean",
		"approvalStatus": "Enum",
		"approvalStatus_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Business API Design Specification - Get Briefuser

Business API Design Specification - Get Briefuser

A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic.

While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized.

This document provides an in-depth explanation of the architectural design of the getBriefUser Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side.

Main Data Object and CRUD Operation

The getBriefUser Business API is designed to handle a get operation on the User data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

This route is used by public to get simple user profile information.

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The getBriefUser Business API includes a REST controller that can be triggered via the following route:

/v1/briefuser/:userId

By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the Parameters section.

gRPC Controller

The getBriefUser Business API includes a gRPC controller that can be triggered via the following function:

getBriefUser()

By calling this gRPC endpoint using a gRPC client, you can execute the Business API. Note that all parameters must be provided as function arguments, regardless of their HTTP location configuration, which is relevant only for the REST controller.

MCP Tool

REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This getBriefUser Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The getBriefUser Business API has 1 parameter that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client.

Business API parameters can be:

Regular Parameters

Name Type Required Default Location Data Path
userId ID Yes - urlpath userId
Description: This id paremeter is used to query the required data object.

Parameter Transformations

Some parameters are post-processed using transform scripts after being read from the request but before validation or workflow execution. Only parameters with a transform script are listed below.

No parameters are transformed in this API.

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the getBriefUser Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API is public and can be accessed without login (loginRequired = false).


Ownership Checks


Role and Permission Settings


Select Clause

Specifies which fields will be selected from the main data object during a get or list operation. Leave blank to select all properties. This applies only to get and list type APIs.",

id,fullname,avatar

Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({$and:[{id:this.userId},{isActive:true}]}), {"path":"services[0].businessLogic[11].whereClause.fullWhereClause"})

Get Options

Use these options to set get specific settings.

setAsRead: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed.

No setAsread field-value pair is configured.

Business Logic Workflow

[1] Step : startBusinessApi

Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Extracts parameters from request and Redis, applies defaults, and writes them to context.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Executes parameter transformation scripts, applies type coercion, merges derived values, and reshapes inputs for downstream milestones.


[4] Step : checkParameters

Validates required and custom parameters, enforcing business-specific rules and constraints.


[5] Step : checkBasicAuth

Performs login, role, and permission checks, and applies dynamic object-level access rules.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildWhereClause

Builds the WHERE clause for fetching the object and applies additional scoped filters if configured.

You can use the following settings to change some behavior of this step. whereClause

[7] Step : mainGetOperation

Executes the database fetch, retrieves the object, and stores it in context for enrichment or further checks.

You can use the following settings to change some behavior of this step. selectClause, getOptions

[8] Step : checkInstance

Performs instance-level validations, such as ownership, existence, or access conditions.


[9] Step : buildOutput

Assembles the response from the object, applies masking, formatting, and injects additional metadata if needed.


[10] Step : sendResponse

Delivers the response to the controller for client delivery.


[11] Step : raiseApiEvent

Triggers optional API-level events after workflow completion, sending messages to integrations like Kafka if configured.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The getBriefUser api has got 1 regular client parameter

Parameter Type Required Population
userId ID true request.params?.[“userId”]

REST Request

To access the api you can use the REST controller with the path GET /v1/briefuser/:userId

  axios({
    method: 'GET',
    url: `/v1/briefuser/${userId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the user object in the respones. However, some properties may be omitted based on the object’s internal logic.

This route’s response is constrained to a select list of properties, and therefore does not encompass all attributes of the resource.

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "user",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"user": {
		"isActive": true
	}
}

Business API Design Specification - Stream Test

Business API Design Specification - Stream Test

A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic.

While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized.

This document provides an in-depth explanation of the architectural design of the streamTest Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side.

Main Data Object and CRUD Operation

The streamTest Business API is designed to handle a get operation on the User data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

Test API for iterator action streaming via SSE.

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The streamTest Business API includes a REST controller that can be triggered via the following route:

/v1/streamtest/:userId

By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the Parameters section.

MCP Tool

REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This streamTest Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The streamTest Business API has 1 parameter that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client.

Business API parameters can be:

Regular Parameters

Name Type Required Default Location Data Path
userId ID Yes - urlpath userId
Description: This id paremeter is used to query the required data object.

Parameter Transformations

Some parameters are post-processed using transform scripts after being read from the request but before validation or workflow execution. Only parameters with a transform script are listed below.

No parameters are transformed in this API.

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the streamTest Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Select Clause

Specifies which fields will be selected from the main data object during a get or list operation. Leave blank to select all properties. This applies only to get and list type APIs.",

``

Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({$and:[{id:this.userId},{isActive:true}]}), {"path":"services[0].businessLogic[12].whereClause.fullWhereClause"})

Get Options

Use these options to set get specific settings.

setAsRead: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed.

No setAsread field-value pair is configured.

Business Logic Workflow

[1] Step : startBusinessApi

Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Extracts parameters from request and Redis, applies defaults, and writes them to context.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Executes parameter transformation scripts, applies type coercion, merges derived values, and reshapes inputs for downstream milestones.


[4] Step : checkParameters

Validates required and custom parameters, enforcing business-specific rules and constraints.


[5] Step : checkBasicAuth

Performs login, role, and permission checks, and applies dynamic object-level access rules.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildWhereClause

Builds the WHERE clause for fetching the object and applies additional scoped filters if configured.

You can use the following settings to change some behavior of this step. whereClause

[7] Step : mainGetOperation

Executes the database fetch, retrieves the object, and stores it in context for enrichment or further checks.

You can use the following settings to change some behavior of this step. selectClause, getOptions

[8] Step : checkInstance

Performs instance-level validations, such as ownership, existence, or access conditions.


[9] Step : buildOutput

Assembles the response from the object, applies masking, formatting, and injects additional metadata if needed.


[10] Step : sendResponse

Delivers the response to the controller for client delivery.


[11] Step : raiseApiEvent

Triggers optional API-level events after workflow completion, sending messages to integrations like Kafka if configured.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The streamTest api has got 1 regular client parameter

Parameter Type Required Population
userId ID true request.params?.[“userId”]

REST Request

To access the api you can use the REST controller with the path GET /v1/streamtest/:userId

  axios({
    method: 'GET',
    url: `/v1/streamtest/${userId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the user object in the respones. However, some properties may be omitted based on the object’s internal logic.

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "user",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"user": {
		"id": "ID",
		"email": "String",
		"password": "String",
		"fullname": "String",
		"avatar": "String",
		"roleId": "String",
		"emailVerified": "Boolean",
		"approvalStatus": "Enum",
		"approvalStatus_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Business API Design Specification - Register User

Business API Design Specification - Register User

A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic.

While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized.

This document provides an in-depth explanation of the architectural design of the registerUser Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side.

Main Data Object and CRUD Operation

The registerUser Business API is designed to handle a create operation on the User data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

This api is used by public users to register themselves

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The registerUser Business API includes a REST controller that can be triggered via the following route:

/v1/registeruser

By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the Parameters section.

gRPC Controller

The registerUser Business API includes a gRPC controller that can be triggered via the following function:

registerUser()

By calling this gRPC endpoint using a gRPC client, you can execute the Business API. Note that all parameters must be provided as function arguments, regardless of their HTTP location configuration, which is relevant only for the REST controller.

MCP Tool

REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This registerUser Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The registerUser Business API has 6 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client.

Business API parameters can be:

Regular Parameters

Name Type Required Default Location Data Path
userId ID No - body userId
Description: This id paremeter is used to create the data object with a given specific id. Leave null for automatic id.
avatar String No - body avatar
Description: The avatar url of the user. If not sent, a default random one will be generated.
socialCode String No - body socialCode
Description: Send this social code if it is sent to you after a social login authetication of an unregistred user. The users profile data will be complemented from the autheticated social profile using this code. If you provide the social code there is no need to give full profile data of the user, just give the ones that are not included in social profiles.
password String Yes - body password
Description: The password defined by the the user that is being registered.
fullname String Yes - body fullname
Description: The fullname defined by the the user that is being registered.
email String Yes - body email
Description: The email defined by the the user that is being registered.

Parameter Transformations

Some parameters are post-processed using transform scripts after being read from the request but before validation or workflow execution. Only parameters with a transform script are listed below.

this.avatar = 
  runMScript(() => (this.socialProfile?.avatar ?? (this.avatar ? this.avatar : `https://gravatar.com/avatar/${LIB.common.md5(this.email ?? 'nullValue')}?s=200&d=identicon`)), {"path":"services[0].businessLogic[13].customParameters[0].transform"})
this.password = 
  runMScript(() => (this.socialProfile ? this.password ?? LIB.common.randomCode() : this.password), {"path":"services[0].businessLogic[13].customParameters[2].transform"})
this.fullname = 
  runMScript(() => (this.socialProfile?.fullname ?? this.fullname), {"path":"services[0].businessLogic[13].customParameters[3].transform"})
this.email = 
  runMScript(() => (this.socialProfile?.email ?? this.email), {"path":"services[0].businessLogic[13].customParameters[4].transform"})

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the registerUser Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API is public and can be accessed without login (loginRequired = false).


Ownership Checks


Role and Permission Settings


Data Clause

Defines custom field-value assignments used to modify or augment the default payload for create and update operations. These settings override values derived from the session or parameters if explicitly provided.", Note that a default data clause is always prepared by Mindbricks using data property settings, however any property in the data clause can be override by Data Clause Settings.

Custom Data Clause Override

{
    emailVerified: runMScript(() => (this.socialProfile?.emailVerified ?? false), {"path":"services[0].businessLogic[13].dataClause.customData[0].value"}),
    roleId: runMScript(() => (this.socialProfile?.roleId ?? 'user'), {"path":"services[0].businessLogic[13].dataClause.customData[1].value"}),
   
}

Actual Data Clause

The business api will use the following data clause. Note that any calculated value will be added to the data clause in the api manager.

{
  id: this.userId,
  email: this.email,
  password: this.hashString(this.password),
  fullname: this.fullname,
  avatar: this.avatar,
  emailVerified: runMScript(() => (this.socialProfile?.emailVerified ?? false), {"path":"services[0].businessLogic[13].dataClause.customData[0].value"}),
  roleId: runMScript(() => (this.socialProfile?.roleId ?? 'user'), {"path":"services[0].businessLogic[13].dataClause.customData[1].value"}),
  isActive: true,
  _archivedAt: null,
}

Business Logic Workflow

[1] Step : startBusinessApi

Manager initializes context, populates session and request objects, prepares internal structures for parameter handling and workflow execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Manager reads input parameters, normalizes missing values, applies default type casting, and stores them in the API context.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Manager transforms parameters, computes derived values, flattens or remaps arrays/objects, and adjusts formats for downstream processing.


[4] Step : checkParameters

Manager executes built-in validations: required field checks, type enforcement, and basic business rules. Prevents operation if validation fails.


[5] Action : validateEmail

Action Type: ValidationAction

Validates that the provided email address has a valid format

class Api {
  async validateEmail() {
    const isValid = runMScript(
      () => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(this.email),
      {
        path: "services[0].businessLogic[13].actions.validationActions[0].validationScript",
      },
    );

    if (!isValid) {
      throw new BadRequestError("InvalidEmailFormat");
    }
    return isValid;
  }
}

[6] Action : fetchArchivedUser

Action Type: FetchObjectAction

Check and get if any deleted user(in 30 days) exists with the same identifier

class Api {
  async fetchArchivedUser() {
    // Fetch Object on childObject user

    const userQuery = runMScript(
      () => ({
        $and: [
          { email: this.email, isActive: false },
          {
            _archivedAt: {
              $gte: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000),
            },
          },
        ],
      }),
      {
        path: "services[0].businessLogic[13].actions.fetchObjectActions[0].whereClause",
      },
    );

    const { convertUserQueryToSequelizeQuery } = require("common");
    const scriptQuery = convertUserQueryToSequelizeQuery(userQuery);

    // get object from db
    const data = await getUserByQuery(scriptQuery);

    return data
      ? {
          id: data["id"],
        }
      : null;
  }
}

[7] Action : checkArchivedUser

Action Type: ValidationAction

Prevents re-register of a user when their profile is still in 30days archive

class Api {
  async checkArchivedUser() {
    const isError = runMScript(() => this.archivedUser?.email != null, {
      path: "services[0].businessLogic[13].actions.validationActions[1].validationScript",
    });

    if (isError) {
      throw new BadRequestError("YourProfileIsArchivedPleaseLoginToRestore");
    }
    return isError;
  }
}

[8] Step : checkBasicAuth

Manager performs authentication and authorization checks: verifies session, user roles, permissions, and tenant restrictions.

You can use the following settings to change some behavior of this step. authOptions

[9] Step : buildDataClause

Manager constructs the final data object for creation, fills auto-generated fields (IDs, timestamps, owner fields), and ensures schema consistency.

You can use the following settings to change some behavior of this step. dataClause

[10] Step : mainCreateOperation

Manager executes the database insert operation, updates indexes/caches, and triggers internal post-processing like linked default records.


[11] Step : buildOutput

Manager shapes the response: masks sensitive fields, resolves linked references, and formats output according to API contract.


[12] Action : writeVerificationNeedsToResponse

Action Type: AddToResponseAction

Set if email or mobile verification needed

class Api {
  async writeVerificationNeedsToResponse() {
    try {
      this.output["emailVerificationNeeded"] = runMScript(() => false, {
        path: "services[0].businessLogic[13].actions.addToResponseActions[0].context[0].contextValue",
      });

      this.output["mobileVerificationNeeded"] = runMScript(() => false, {
        path: "services[0].businessLogic[13].actions.addToResponseActions[0].context[1].contextValue",
      });

      return true;
    } catch (error) {
      console.error("AddToResponseAction error:", error);
      throw error;
    }
  }
}

[13] Action : autoLoginAfterRegister

Action Type: FunctionCallAction

If no email or mobile verification is needed after registration, automatically create a login session and return the access token in the registration response. This provides a seamless register-and-login experience.

class Api {
  async autoLoginAfterRegister() {
    try {
      return await runMScript(
        () =>
          (async () =>
            await (async () => {
              try {
                if (
                  this.output.emailVerificationNeeded ||
                  this.output.mobileVerificationNeeded
                )
                  return;
                const identifier = this.output[this.dataName]?.email;
                if (!identifier) return;
                const { createSessionManager } = require("sessionLayer");
                const sm = createSessionManager();
                await sm.setLoginToRequest(this.request, null, {
                  userField: "email",
                  subjectClaim: identifier,
                });
                this.output.accessToken = sm.accessToken;
                this.output.autoLoginSession = sm.session;
                this.request.autoLoginToken = sm.accessToken;
                console.log(
                  "Auto-login after registration successful for:",
                  identifier,
                );
              } catch (autoLoginErr) {
                console.log(
                  "Auto-login after registration failed:",
                  autoLoginErr.message,
                );
              }
            })())(),
        {
          path: "services[0].businessLogic[13].actions.functionCallActions[0].callScript",
        },
      );
    } catch (err) {
      console.error("Error in FunctionCallAction autoLoginAfterRegister:", err);
      throw err;
    }
  }
}

[14] Step : sendResponse

Manager sends the response to the client and finalizes internal tasks like flushing logs or updating session state.


[15] Step : raiseApiEvent

Manager triggers API-level events (Kafka, WebSocket, async workflows) as the final internal step.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The registerUser api has got 4 regular client parameters

Parameter Type Required Population
avatar String false request.body?.[“avatar”]
password String true request.body?.[“password”]
fullname String true request.body?.[“fullname”]
email String true request.body?.[“email”]

REST Request

To access the api you can use the REST controller with the path POST /v1/registeruser

  axios({
    method: 'POST',
    url: '/v1/registeruser',
    data: {
            avatar:"String",  
            password:"String",  
            fullname:"String",  
            email:"String",  
    
    },
    params: {
    
        }
  });

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the user object in the respones. However, some properties may be omitted based on the object’s internal logic.

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "user",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"user": {
		"id": "ID",
		"email": "String",
		"password": "String",
		"fullname": "String",
		"avatar": "String",
		"roleId": "String",
		"emailVerified": "Boolean",
		"approvalStatus": "Enum",
		"approvalStatus_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Business API Design Specification - Get Useravatarsfile

Business API Design Specification - Get Useravatarsfile

A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic.

While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized.

This document provides an in-depth explanation of the architectural design of the getUserAvatarsFile Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side.

Main Data Object and CRUD Operation

The getUserAvatarsFile Business API is designed to handle a get operation on the UserAvatarsFile data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The getUserAvatarsFile Business API includes a REST controller that can be triggered via the following route:

/v1/useravatarsfiles/:userAvatarsFileId

By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the Parameters section.

MCP Tool

REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This getUserAvatarsFile Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The getUserAvatarsFile Business API has 1 parameter that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client.

Business API parameters can be:

Regular Parameters

Name Type Required Default Location Data Path
userAvatarsFileId ID Yes - urlpath userAvatarsFileId
Description: This id paremeter is used to query the required data object.

Parameter Transformations

Some parameters are post-processed using transform scripts after being read from the request but before validation or workflow execution. Only parameters with a transform script are listed below.

No parameters are transformed in this API.

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the getUserAvatarsFile Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Select Clause

Specifies which fields will be selected from the main data object during a get or list operation. Leave blank to select all properties. This applies only to get and list type APIs.",

``

Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({id:this.userAvatarsFileId}), {"path":"services[0].businessLogic[14].whereClause.fullWhereClause"})

Get Options

Use these options to set get specific settings.

setAsRead: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed.

No setAsread field-value pair is configured.

Business Logic Workflow

[1] Step : startBusinessApi

Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Extracts parameters from request and Redis, applies defaults, and writes them to context.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Executes parameter transformation scripts, applies type coercion, merges derived values, and reshapes inputs for downstream milestones.


[4] Step : checkParameters

Validates required and custom parameters, enforcing business-specific rules and constraints.


[5] Step : checkBasicAuth

Performs login, role, and permission checks, and applies dynamic object-level access rules.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildWhereClause

Builds the WHERE clause for fetching the object and applies additional scoped filters if configured.

You can use the following settings to change some behavior of this step. whereClause

[7] Step : mainGetOperation

Executes the database fetch, retrieves the object, and stores it in context for enrichment or further checks.

You can use the following settings to change some behavior of this step. selectClause, getOptions

[8] Step : checkInstance

Performs instance-level validations, such as ownership, existence, or access conditions.


[9] Step : buildOutput

Assembles the response from the object, applies masking, formatting, and injects additional metadata if needed.


[10] Step : sendResponse

Delivers the response to the controller for client delivery.


[11] Step : raiseApiEvent

Triggers optional API-level events after workflow completion, sending messages to integrations like Kafka if configured.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The getUserAvatarsFile api has got 1 regular client parameter

Parameter Type Required Population
userAvatarsFileId ID true request.params?.[“userAvatarsFileId”]

REST Request

To access the api you can use the REST controller with the path GET /v1/useravatarsfiles/:userAvatarsFileId

  axios({
    method: 'GET',
    url: `/v1/useravatarsfiles/${userAvatarsFileId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the userAvatarsFile object in the respones. However, some properties may be omitted based on the object’s internal logic.

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "userAvatarsFile",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"userAvatarsFile": {
		"id": "ID",
		"fileName": "String",
		"mimeType": "String",
		"fileSize": "Integer",
		"accessKey": "String",
		"ownerId": "ID",
		"fileData": "Blob",
		"metadata": "Object",
		"userId": "ID",
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"isActive": true
	}
}

Business API Design Specification - List Useravatarsfiles

Business API Design Specification - List Useravatarsfiles

A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic.

While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized.

This document provides an in-depth explanation of the architectural design of the listUserAvatarsFiles Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side.

Main Data Object and CRUD Operation

The listUserAvatarsFiles Business API is designed to handle a list operation on the UserAvatarsFile data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The listUserAvatarsFiles Business API includes a REST controller that can be triggered via the following route:

/v1/useravatarsfiles

By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the Parameters section.

MCP Tool

REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This listUserAvatarsFiles Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The listUserAvatarsFiles Business API has 3 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client.

Business API parameters can be:

Filter Parameters

The listUserAvatarsFiles api supports 3 optional filter parameters for filtering list results using URL query parameters. These parameters are only available for list type APIs.

mimeType Filter

Type: String
Description: MIME type of the uploaded file (e.g., image/png, application/pdf).
Location: Query Parameter

Usage:

Non-Array Property (Case-Insensitive Partial Matching):

Examples:

// Find records with "john" in the field (case-insensitive partial match)
GET /v1/useravatarsfiles?mimeType=john
// Matches: "John", "Johnny", "johnson", "McJohn", etc.

// Find records with multiple values (use multiple parameters)
GET /v1/useravatarsfiles?mimeType=laptop&mimeType=phone&mimeType=tablet
// Matches records containing "laptop", "phone", or "tablet" anywhere in the field

// Find records without this field
GET /v1/useravatarsfiles?mimeType=null

ownerId Filter

Type: ID
Description: ID of the user who uploaded the file (from session).
Location: Query Parameter

Usage:

Non-Array Property:

Examples:

// Get records with a specific ID
GET /v1/useravatarsfiles?ownerId=550e8400-e29b-41d4-a716-446655440000

// Get records with multiple IDs (use multiple parameters)
GET /v1/useravatarsfiles?ownerId=550e8400-e29b-41d4-a716-446655440000&ownerId=660e8400-e29b-41d4-a716-446655440001

// Get records without this field
GET /v1/useravatarsfiles?ownerId=null

userId Filter

Type: ID
Description: Reference to the owner user record.
Location: Query Parameter

Usage:

Non-Array Property:

Examples:

// Get records with a specific ID
GET /v1/useravatarsfiles?userId=550e8400-e29b-41d4-a716-446655440000

// Get records with multiple IDs (use multiple parameters)
GET /v1/useravatarsfiles?userId=550e8400-e29b-41d4-a716-446655440000&userId=660e8400-e29b-41d4-a716-446655440001

// Get records without this field
GET /v1/useravatarsfiles?userId=null

Parameter Transformations

Some parameters are post-processed using transform scripts after being read from the request but before validation or workflow execution. Only parameters with a transform script are listed below.

No parameters are transformed in this API.

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the listUserAvatarsFiles Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Select Clause

Specifies which fields will be selected from the main data object during a get or list operation. Leave blank to select all properties. This applies only to get and list type APIs.",

``

Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

null

List Options

Defines list-specific options including filtering logic, default sorting, and result customization for APIs that return multiple records.

List Sort By Sort order definitions for the result set. Multiple fields can be provided with direction (asc/desc).

Specific sort order is not configure, natural order (ascending id) will be used.

List Group By Grouping definitions for the result set. This is typically used for visual or report-based grouping.

The list is not grouped.

setAsRead: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed.

No setAsread field-value pair is configured.

Permission Filter Optional filter that applies permission constraints dynamically based on session or object roles. So that the list items are filtered by the user’s OBAC or ABAC permissions.

Permission filter is not active at the moment. Follow Mindbricks updates to be able to use it.

Pagination Options

Contains settings to configure pagination behavior for list APIs. Includes options like page size, offset, cursor support, and total count inclusion.

Business Logic Workflow

[1] Step : startBusinessApi

Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Reads request and Redis parameters, applies defaults, and writes them to context for downstream processing.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Transforms and normalizes parameters, derives dependent values, and reshapes inputs for the main list query.


[4] Step : checkParameters

Executes validation logic on required and custom parameters, enforcing business rules and cross-field consistency.


[5] Step : checkBasicAuth

Performs role-based access checks and applies dynamic membership or session-based restrictions.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildWhereClause

Constructs the main query WHERE clause and applies optional filters or scoped access controls.

You can use the following settings to change some behavior of this step. whereClause

[7] Step : mainListOperation

Executes the paginated database query, retrieves the list, and stores results in context for enrichment.

You can use the following settings to change some behavior of this step. selectClause, listOptions, paginationOptions

[8] Step : buildOutput

Assembles the list response, sanitizes sensitive fields, applies transformations, and injects extra context if needed.


[9] Step : sendResponse

Sends the paginated list to the client through the controller.


[10] Step : raiseApiEvent

Triggers optional post-workflow events, such as Kafka messages, logs, or system notifications.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The listUserAvatarsFiles api has 3 filter parameters available for filtering list results. See the Filter Parameters section above for detailed usage examples.

Filter Parameter Type Array Property Description
mimeType String No MIME type of the uploaded file (e.g., image/png, application/pdf).
ownerId ID No ID of the user who uploaded the file (from session).
userId ID No Reference to the owner user record.

REST Request

To access the api you can use the REST controller with the path GET /v1/useravatarsfiles

  axios({
    method: 'GET',
    url: '/v1/useravatarsfiles',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section for usage examples)
        // mimeType: '<value>' // Filter by mimeType
        // ownerId: '<value>' // Filter by ownerId
        // userId: '<value>' // Filter by userId
            }
  });

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the userAvatarsFiles object in the respones. However, some properties may be omitted based on the object’s internal logic.

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "userAvatarsFiles",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"userAvatarsFiles": [
		{
			"id": "ID",
			"fileName": "String",
			"mimeType": "String",
			"fileSize": "Integer",
			"accessKey": "String",
			"ownerId": "ID",
			"fileData": "Blob",
			"metadata": "Object",
			"userId": "ID",
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID",
			"isActive": true
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Business API Design Specification - Delete Useravatarsfile

Business API Design Specification - Delete Useravatarsfile

A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic.

While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized.

This document provides an in-depth explanation of the architectural design of the deleteUserAvatarsFile Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side.

Main Data Object and CRUD Operation

The deleteUserAvatarsFile Business API is designed to handle a delete operation on the UserAvatarsFile data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The deleteUserAvatarsFile Business API includes a REST controller that can be triggered via the following route:

/v1/useravatarsfiles/:userAvatarsFileId

By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the Parameters section.

MCP Tool

REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This deleteUserAvatarsFile Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The deleteUserAvatarsFile Business API has 1 parameter that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client.

Business API parameters can be:

Regular Parameters

Name Type Required Default Location Data Path
userAvatarsFileId ID Yes - urlpath userAvatarsFileId
Description: This id paremeter is used to select the required data object that will be deleted

Parameter Transformations

Some parameters are post-processed using transform scripts after being read from the request but before validation or workflow execution. Only parameters with a transform script are listed below.

No parameters are transformed in this API.

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the deleteUserAvatarsFile Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({id:this.userAvatarsFileId}), {"path":"services[0].businessLogic[16].whereClause.fullWhereClause"})

Delete Options

Use these options to set delete specific settings.

useSoftDelete: If true, the record will be marked as deleted (isActive: false) instead of removed. The implementation depends on the data object’s soft delete configuration.

Business Logic Workflow

[1] Step : startBusinessApi

Manager initializes context, prepares request/session objects, and sets up internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Manager reads and normalizes parameters, applies defaults, and stores them in the context for downstream steps.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Manager executes parameter transform scripts, computes derived values, and remaps objects or arrays as needed for later processing.


[4] Step : checkParameters

Manager runs built-in validations including required field checks, type enforcement, and deletion preconditions. Stops execution if validation fails.


[5] Step : checkBasicAuth

Manager validates session, user roles, permissions, and tenant-specific access rules to enforce basic auth restrictions.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildWhereClause

Manager generates the query conditions, applies ownership and parent checks, and ensures the clause is correct for the delete operation.

You can use the following settings to change some behavior of this step. whereClause

[7] Step : fetchInstance

Manager fetches the target record, applies filters from WHERE clause, and writes the instance to the context for further checks.


[8] Step : checkInstance

Manager performs object-level validations such as lock status, soft-delete eligibility, and multi-step approval enforcement.


[9] Step : mainDeleteOperation

Manager executes the delete query, updates related indexes/caches, and handles soft/hard delete logic according to configuration.

You can use the following settings to change some behavior of this step. deleteOptions

[10] Step : buildOutput

Manager shapes the response payload, masks sensitive fields, and formats related cleanup results for output.


[11] Step : sendResponse

Manager delivers the response to the client and finalizes any temporary internal structures.


[12] Step : raiseApiEvent

Manager triggers asynchronous API events, notifies queues or streams, and performs final cleanup for the workflow.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The deleteUserAvatarsFile api has got 1 regular client parameter

Parameter Type Required Population
userAvatarsFileId ID true request.params?.[“userAvatarsFileId”]

REST Request

To access the api you can use the REST controller with the path DELETE /v1/useravatarsfiles/:userAvatarsFileId

  axios({
    method: 'DELETE',
    url: `/v1/useravatarsfiles/${userAvatarsFileId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the userAvatarsFile object in the respones. However, some properties may be omitted based on the object’s internal logic.

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "userAvatarsFile",
	"method": "DELETE",
	"action": "delete",
	"appVersion": "Version",
	"rowCount": 1,
	"userAvatarsFile": {
		"id": "ID",
		"fileName": "String",
		"mimeType": "String",
		"fileSize": "Integer",
		"accessKey": "String",
		"ownerId": "ID",
		"fileData": "Blob",
		"metadata": "Object",
		"userId": "ID",
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"isActive": false
	}
}

Database Buckets

Database Bucket Design Specification - userAvatars

Database Bucket Design Specification - userAvatars

This document provides a detailed architectural overview of the userAvatars database bucket within the auth service. It covers the bucket’s storage configuration, authorization model, endpoints, and optional owner DataObject pairing.

Bucket Overview

Description: User profile avatar images stored in the database.

A database bucket stores files as BYTEA columns in PostgreSQL. It is suited for small files such as icons, avatars, documents, and secret files.

Authorization

The bucket uses a layered authorization model for both read and write operations:

Read Access

Write Access

Key-Based Access

Owner DataObject

This bucket is paired with an owner DataObject for relational file management. Each uploaded file is linked to a record in the owner DataObject via a foreign key, enabling structured file ownership and access patterns.

REST Endpoints

The following endpoints are auto-generated for this bucket:

Method Path Description Auth
POST /bucket/userAvatars/upload Upload a file Authenticated
GET /bucket/userAvatars/download/:id Download a file by ID public
GET /bucket/userAvatars/download/key/:accessKey Download via access key Public
GET /bucket/userAvatars/meta/:id Get file metadata public
DELETE /bucket/userAvatars/:id Delete a file Authenticated

Upload Request

POST /bucket/userAvatars/upload
Content-Type: multipart/form-data

file: <binary file data>

The upload response returns the file metadata including the generated id and accessKey.

Download Response

The download endpoint returns the raw file bytes with the appropriate Content-Type header set from the stored MIME type.

Auto-Generated DataObject: userAvatarsFile

The bucket automatically generates a userAvatarsFile DataObject with metadata properties:

Property Type Description
id ID Unique file identifier (UUID)
fileName String Original file name
mimeType String MIME type of the file
fileSize Integer File size in bytes
accessKey String 12-character random access key for shareable links
createdAt Date Upload timestamp
ownerId ID User ID of uploader (from session)

Standard CRUD APIs are generated for the metadata object, allowing listing, filtering, and management of file records independently of the binary content.


This document was generated from the database bucket configuration and should be kept in sync with design changes.


ProjectPortfolio Service

Service Design Specification

Service Design Specification

auteurlabb-projectportfolio-service documentation Version: 1.0.33

Scope

This document provides a structured architectural overview of the projectPortfolio microservice, detailing its configuration, data model, authorization logic, business rules, and API design. It has been automatically generated based on the service definition within Mindbricks, ensuring that the information reflects the source of truth used during code generation and deployment.

The document is intended to serve multiple audiences:

Note for Frontend Developers: While this document is valuable for understanding business logic and data interactions, please refer to the Service API Documentation for endpoint-level specifications and integration details.

Note for Backend Developers: Since the code for this service is automatically generated by Mindbricks, you typically won’t need to implement or modify it manually. However, this document is especially valuable when you’re building other services—whether within Mindbricks or externally—that need to interact with or depend on this service. It provides a clear reference to the service’s data contracts, business rules, and API structure, helping ensure compatibility and correct integration.

ProjectPortfolio Service Settings

Handles the lifecycle of film projects and access management, allowing filmmakers & studios to submit, update, publish (public/private), withdraw projects, and manage project access for investors/bookmarks. Enforces admin approval & efficient searching/filtering. Connects projects to user (and optionally studio) ownership.

Service Overview

This service is configured to listen for HTTP requests on port 3001, serving both the main API interface and default administrative endpoints.

The following routes are available by default:

The service uses a PostgreSQL database for data storage, with the database name set to auteurlabb-projectportfolio-service.

This service is accessible via the following environment-specific URLs:

Authentication & Security

This service requires user authentication for access. It supports both JWT and RSA-based authentication mechanisms, ensuring secure user sessions and data integrity. If a crud route also is configured to require login, it will check a valid JWT token in the request query/header/bearer/cookie. If the token is valid, it will extract the user information from the token and make the fetched session data available in the request context.

Service Data Objects

The service uses a PostgreSQL database for data storage, with the database name set to auteurlabb-projectportfolio-service.

Data deletion is managed using a soft delete strategy. Instead of removing records from the database, they are flagged as inactive by setting the isActive field to false.

Object Name Description Public Access
filmProject A film project submitted by a filmmaker or studio with all required metadata, visibility, and lifecycle status. accessPrivate
accessGrant Access grants to private projects, allowing selected users to view restricted projects (requested/granted/revoked/denied). accessPrivate
projectBookmark User bookmarks/follows for projects. Each bookmark is per user+project. accessProtected
investmentOffer Tracks investment offers from investors to film projects. Each offer has an amount, optional message, and status workflow (pending/accepted/rejected/withdrawn). accessPrivate
userFollow Tracks user-to-user follow relationships. A follower follows a target user (filmmaker, studio, investor). accessProtected

filmProject Data Object

Object Overview

Description: A film project submitted by a filmmaker or studio with all required metadata, visibility, and lifecycle status.

This object represents a core data structure within the service and acts as the blueprint for database interaction, API generation, and business logic enforcement. It is defined using the ObjectSettings pattern, which governs its behavior, access control, caching strategy, and integration points with other systems such as Stripe and Redis.

Core Configuration

Composite Indexes

The index also defines a conflict resolution strategy for duplicate key violations.

When a new record would violate this composite index, the following action will be taken:

On Duplicate: throwError

An error will be thrown, preventing the insertion of conflicting data.

Properties Schema

Display Label Property: title — This property is the default display label for records of this data object. Relation dropdowns and record references in the frontend will show the value of this property as the human-readable label.

Property Type Required Description
title String Yes Project title, unique per owner
description Text Yes Project description (for details page/fulltext search)
synopsis Text No Short synopsis or tagline
budget Double Yes Estimated budget (USD)
cast String No List of major cast members (names)
genre String No Project genres/tags
projectType Enum Yes Origin: filmmaker or studio
ownerUserId ID Yes User ID of project owner (filmmaker/studio admin)
studioId ID No (Optional) User ID of the studio (for studio projects)
isPublic Boolean Yes Project public visibility flag
approvalStatus Enum Yes Project approval/publication workflow status
mediaUrls String No Project demo reel/trailer/cover media URLs
featured Boolean No Platform feature flag (for promoted projects)
publishedAt Date No Publication date
accessPolicy Enum Yes Access policy (open: any authorized user, restricted: need grant)
director String No Director of the film project
fundingGoal Double No Funding goal amount (USD)

Array Properties

cast genre mediaUrls

Array properties can hold multiple values and are indicated by the [] suffix in their type. Avoid using arrays in properties that are used for relations, as they will not work correctly. Note that using connection objects instead of arrays is recommended for relations, as they provide better performance and flexibility.

Default Values

Default values are automatically assigned to properties when a new object is created, if no value is provided in the request body. Since default values are applied on db level, they should be literal values, not expressions.If you want to use expressions, you can use transposed parameters in any business API to set default values dynamically.

Always Create with Default Values

Some of the default values are set to be always used when creating a new object, even if the property value is provided in the request body. It ensures that the property is always initialized with a default value when the object is created.

Constant Properties

projectType ownerUserId studioId

Constant properties are defined to be immutable after creation, meaning they cannot be updated or changed once set. They are typically used for properties that should remain constant throughout the object’s lifecycle. A property is set to be constant if the Allow Update option is set to false.

Auto Update Properties

title description synopsis budget cast genre isPublic approvalStatus mediaUrls featured publishedAt accessPolicy director fundingGoal

An update crud API created with the option Auto Params enabled will automatically update these properties with the provided values in the request body. If you want to update any property in your own business logic not by user input, you can set the Allow Auto Update option to false. These properties will be added to the update API’s body parameters and can be updated by the user if any value is provided in the request body.

Enum Properties

Enum properties are defined with a set of allowed values, ensuring that only valid options can be assigned to them. The enum options value will be stored as strings in the database, but when a data object is created an addtional property with the same name plus an idx suffix will be created, which will hold the index of the selected enum option. You can use the index property to sort by the enum value or when your enum options represent a sequence of values.

Elastic Search Indexing

title description synopsis budget cast genre projectType ownerUserId studioId isPublic approvalStatus mediaUrls featured publishedAt accessPolicy director fundingGoal

Properties that are indexed in Elastic Search will be searchable via the Elastic Search API. While all properties are stored in the elastic search index of the data object, only those marked for Elastic Search indexing will be available for search queries.

Database Indexing

title budget projectType ownerUserId studioId isPublic approvalStatus featured publishedAt accessPolicy fundingGoal

Properties that are indexed in the database will be optimized for query performance, allowing for faster data retrieval. Make a property indexed in the database if you want to use it frequently in query filters or sorting.

Secondary Key Properties

ownerUserId

Secondary key properties are used to create an additional indexed identifiers for the data object, allowing for alternative access patterns. Different than normal indexed properties, secondary keys will act as primary keys and Mindbricks will provide automatic secondary key db utility functions to access the data object by the secondary key.

Relation Properties

ownerUserId studioId

Mindbricks supports relations between data objects, allowing you to define how objects are linked together. You can define relations in the data object properties, which will be used to create foreign key constraints in the database. For complex joins operations, Mindbricks supportsa BFF pattern, where you can view dynamic and static views based on Elastic Search Indexes. Use db level relations for simple one-to-one or one-to-many relationships, and use BFF views for complex joins that require multiple data objects to be joined together.

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

On Delete: Set Null Required: Yes

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

On Delete: Set Null Required: No

Session Data Properties

ownerUserId

Session data properties are used to store data that is specific to the user session, allowing for personalized experiences and temporary data storage. If a property is configured as session data, it will be automatically mapped to the related field in the user session during CRUD operations. Note that session data properties can not be mutated by the user, but only by the system.

This property is also used to store the owner of the session data, allowing for ownership checks and access control.

Filter Properties

title description synopsis budget genre projectType isPublic approvalStatus featured accessPolicy director fundingGoal

Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API’s that have “Auto Params” enabled.

accessGrant Data Object

Object Overview

Description: Access grants to private projects, allowing selected users to view restricted projects (requested/granted/revoked/denied).

This object represents a core data structure within the service and acts as the blueprint for database interaction, API generation, and business logic enforcement. It is defined using the ObjectSettings pattern, which governs its behavior, access control, caching strategy, and integration points with other systems such as Stripe and Redis.

Core Configuration

Composite Indexes

The index also defines a conflict resolution strategy for duplicate key violations.

When a new record would violate this composite index, the following action will be taken:

On Duplicate: throwError

An error will be thrown, preventing the insertion of conflicting data.

Properties Schema

Property Type Required Description
projectId ID Yes Film project ID for which access is granted/requested
granteeUserId ID Yes ID of user being granted/requesting access
grantedByUserId ID No Who granted/revoked the access (or null for self-request)
status Enum Yes requested (pending); granted (success); revoked; denied
requestMessage Text No Message from requester (for context)
dateGranted Date No Timestamp when access status last updated

Default Values

Default values are automatically assigned to properties when a new object is created, if no value is provided in the request body. Since default values are applied on db level, they should be literal values, not expressions.If you want to use expressions, you can use transposed parameters in any business API to set default values dynamically.

Constant Properties

projectId granteeUserId grantedByUserId

Constant properties are defined to be immutable after creation, meaning they cannot be updated or changed once set. They are typically used for properties that should remain constant throughout the object’s lifecycle. A property is set to be constant if the Allow Update option is set to false.

Auto Update Properties

status requestMessage dateGranted

An update crud API created with the option Auto Params enabled will automatically update these properties with the provided values in the request body. If you want to update any property in your own business logic not by user input, you can set the Allow Auto Update option to false. These properties will be added to the update API’s body parameters and can be updated by the user if any value is provided in the request body.

Enum Properties

Enum properties are defined with a set of allowed values, ensuring that only valid options can be assigned to them. The enum options value will be stored as strings in the database, but when a data object is created an addtional property with the same name plus an idx suffix will be created, which will hold the index of the selected enum option. You can use the index property to sort by the enum value or when your enum options represent a sequence of values.

Elastic Search Indexing

projectId granteeUserId grantedByUserId status dateGranted

Properties that are indexed in Elastic Search will be searchable via the Elastic Search API. While all properties are stored in the elastic search index of the data object, only those marked for Elastic Search indexing will be available for search queries.

Database Indexing

projectId granteeUserId grantedByUserId status dateGranted

Properties that are indexed in the database will be optimized for query performance, allowing for faster data retrieval. Make a property indexed in the database if you want to use it frequently in query filters or sorting.

Secondary Key Properties

projectId granteeUserId

Secondary key properties are used to create an additional indexed identifiers for the data object, allowing for alternative access patterns. Different than normal indexed properties, secondary keys will act as primary keys and Mindbricks will provide automatic secondary key db utility functions to access the data object by the secondary key.

Relation Properties

projectId granteeUserId grantedByUserId

Mindbricks supports relations between data objects, allowing you to define how objects are linked together. You can define relations in the data object properties, which will be used to create foreign key constraints in the database. For complex joins operations, Mindbricks supportsa BFF pattern, where you can view dynamic and static views based on Elastic Search Indexes. Use db level relations for simple one-to-one or one-to-many relationships, and use BFF views for complex joins that require multiple data objects to be joined together.

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

On Delete: Set Null Required: Yes

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

On Delete: Set Null Required: Yes

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

On Delete: Set Null Required: No

Filter Properties

projectId granteeUserId status

Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API’s that have “Auto Params” enabled.

projectBookmark Data Object

Object Overview

Description: User bookmarks/follows for projects. Each bookmark is per user+project.

This object represents a core data structure within the service and acts as the blueprint for database interaction, API generation, and business logic enforcement. It is defined using the ObjectSettings pattern, which governs its behavior, access control, caching strategy, and integration points with other systems such as Stripe and Redis.

Core Configuration

Composite Indexes

The index also defines a conflict resolution strategy for duplicate key violations.

When a new record would violate this composite index, the following action will be taken:

On Duplicate: throwError

An error will be thrown, preventing the insertion of conflicting data.

Properties Schema

Property Type Required Description
projectId ID Yes The project being bookmarked
userId ID Yes The user who bookmarked this project
createdAtBookmark Date No When bookmark was made

Default Values

Default values are automatically assigned to properties when a new object is created, if no value is provided in the request body. Since default values are applied on db level, they should be literal values, not expressions.If you want to use expressions, you can use transposed parameters in any business API to set default values dynamically.

Constant Properties

projectId userId createdAtBookmark

Constant properties are defined to be immutable after creation, meaning they cannot be updated or changed once set. They are typically used for properties that should remain constant throughout the object’s lifecycle. A property is set to be constant if the Allow Update option is set to false.

Elastic Search Indexing

projectId userId createdAtBookmark

Properties that are indexed in Elastic Search will be searchable via the Elastic Search API. While all properties are stored in the elastic search index of the data object, only those marked for Elastic Search indexing will be available for search queries.

Database Indexing

projectId userId createdAtBookmark

Properties that are indexed in the database will be optimized for query performance, allowing for faster data retrieval. Make a property indexed in the database if you want to use it frequently in query filters or sorting.

Secondary Key Properties

projectId userId

Secondary key properties are used to create an additional indexed identifiers for the data object, allowing for alternative access patterns. Different than normal indexed properties, secondary keys will act as primary keys and Mindbricks will provide automatic secondary key db utility functions to access the data object by the secondary key.

Relation Properties

projectId userId

Mindbricks supports relations between data objects, allowing you to define how objects are linked together. You can define relations in the data object properties, which will be used to create foreign key constraints in the database. For complex joins operations, Mindbricks supportsa BFF pattern, where you can view dynamic and static views based on Elastic Search Indexes. Use db level relations for simple one-to-one or one-to-many relationships, and use BFF views for complex joins that require multiple data objects to be joined together.

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

On Delete: Set Null Required: Yes

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

On Delete: Set Null Required: Yes

Session Data Properties

userId

Session data properties are used to store data that is specific to the user session, allowing for personalized experiences and temporary data storage. If a property is configured as session data, it will be automatically mapped to the related field in the user session during CRUD operations. Note that session data properties can not be mutated by the user, but only by the system.

This property is also used to store the owner of the session data, allowing for ownership checks and access control.

Context Data Properties

createdAtBookmark

Context data properties are used to store data that is specific to the request context, allowing for dynamic data retrieval based on the current request. If a property is configured as context data, it will be automatically mapped to the related field in the request context during CRUD operations.

Formula Properties

createdAtBookmark

Formula properties are used to define calculated fields that derive their values from other properties or external data. These properties are automatically calculated based on the defined formula and can be used for dynamic data retrieval.

Filter Properties

projectId userId

Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API’s that have “Auto Params” enabled.

investmentOffer Data Object

Object Overview

Description: Tracks investment offers from investors to film projects. Each offer has an amount, optional message, and status workflow (pending/accepted/rejected/withdrawn).

This object represents a core data structure within the service and acts as the blueprint for database interaction, API generation, and business logic enforcement. It is defined using the ObjectSettings pattern, which governs its behavior, access control, caching strategy, and integration points with other systems such as Stripe and Redis.

Core Configuration

Composite Indexes

The index also defines a conflict resolution strategy for duplicate key violations.

When a new record would violate this composite index, the following action will be taken:

On Duplicate: throwError

An error will be thrown, preventing the insertion of conflicting data.

Properties Schema

Property Type Required Description
projectId ID Yes Film project receiving the investment offer
investorUserId ID Yes Investor who made the offer
offerAmount Double Yes Investment amount in USD
message Text No Cover letter or terms from the investor
status Enum No Offer lifecycle status
respondedAt Date No When the project owner responded
responseNote Text No Project owner note on accept/reject

Default Values

Default values are automatically assigned to properties when a new object is created, if no value is provided in the request body. Since default values are applied on db level, they should be literal values, not expressions.If you want to use expressions, you can use transposed parameters in any business API to set default values dynamically.

Always Create with Default Values

Some of the default values are set to be always used when creating a new object, even if the property value is provided in the request body. It ensures that the property is always initialized with a default value when the object is created.

Constant Properties

projectId investorUserId

Constant properties are defined to be immutable after creation, meaning they cannot be updated or changed once set. They are typically used for properties that should remain constant throughout the object’s lifecycle. A property is set to be constant if the Allow Update option is set to false.

Auto Update Properties

offerAmount message status respondedAt responseNote

An update crud API created with the option Auto Params enabled will automatically update these properties with the provided values in the request body. If you want to update any property in your own business logic not by user input, you can set the Allow Auto Update option to false. These properties will be added to the update API’s body parameters and can be updated by the user if any value is provided in the request body.

Enum Properties

Enum properties are defined with a set of allowed values, ensuring that only valid options can be assigned to them. The enum options value will be stored as strings in the database, but when a data object is created an addtional property with the same name plus an idx suffix will be created, which will hold the index of the selected enum option. You can use the index property to sort by the enum value or when your enum options represent a sequence of values.

Elastic Search Indexing

projectId investorUserId offerAmount status

Properties that are indexed in Elastic Search will be searchable via the Elastic Search API. While all properties are stored in the elastic search index of the data object, only those marked for Elastic Search indexing will be available for search queries.

Database Indexing

projectId investorUserId offerAmount status

Properties that are indexed in the database will be optimized for query performance, allowing for faster data retrieval. Make a property indexed in the database if you want to use it frequently in query filters or sorting.

Secondary Key Properties

projectId investorUserId

Secondary key properties are used to create an additional indexed identifiers for the data object, allowing for alternative access patterns. Different than normal indexed properties, secondary keys will act as primary keys and Mindbricks will provide automatic secondary key db utility functions to access the data object by the secondary key.

Relation Properties

projectId investorUserId

Mindbricks supports relations between data objects, allowing you to define how objects are linked together. You can define relations in the data object properties, which will be used to create foreign key constraints in the database. For complex joins operations, Mindbricks supportsa BFF pattern, where you can view dynamic and static views based on Elastic Search Indexes. Use db level relations for simple one-to-one or one-to-many relationships, and use BFF views for complex joins that require multiple data objects to be joined together.

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

On Delete: Set Null Required: Yes

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

On Delete: Set Null Required: Yes

Session Data Properties

investorUserId

Session data properties are used to store data that is specific to the user session, allowing for personalized experiences and temporary data storage. If a property is configured as session data, it will be automatically mapped to the related field in the user session during CRUD operations. Note that session data properties can not be mutated by the user, but only by the system.

This property is also used to store the owner of the session data, allowing for ownership checks and access control.

Filter Properties

projectId investorUserId offerAmount status

Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API’s that have “Auto Params” enabled.

userFollow Data Object

Object Overview

Description: Tracks user-to-user follow relationships. A follower follows a target user (filmmaker, studio, investor).

This object represents a core data structure within the service and acts as the blueprint for database interaction, API generation, and business logic enforcement. It is defined using the ObjectSettings pattern, which governs its behavior, access control, caching strategy, and integration points with other systems such as Stripe and Redis.

Core Configuration

Composite Indexes

The index also defines a conflict resolution strategy for duplicate key violations.

When a new record would violate this composite index, the following action will be taken:

On Duplicate: throwError

An error will be thrown, preventing the insertion of conflicting data.

Properties Schema

Property Type Required Description
followerUserId ID Yes The user who is following
followingUserId ID Yes The user being followed
followedAt Date No When the follow relationship was created

Default Values

Default values are automatically assigned to properties when a new object is created, if no value is provided in the request body. Since default values are applied on db level, they should be literal values, not expressions.If you want to use expressions, you can use transposed parameters in any business API to set default values dynamically.

Constant Properties

followerUserId followingUserId followedAt

Constant properties are defined to be immutable after creation, meaning they cannot be updated or changed once set. They are typically used for properties that should remain constant throughout the object’s lifecycle. A property is set to be constant if the Allow Update option is set to false.

Elastic Search Indexing

followerUserId followingUserId followedAt

Properties that are indexed in Elastic Search will be searchable via the Elastic Search API. While all properties are stored in the elastic search index of the data object, only those marked for Elastic Search indexing will be available for search queries.

Database Indexing

followerUserId followingUserId followedAt

Properties that are indexed in the database will be optimized for query performance, allowing for faster data retrieval. Make a property indexed in the database if you want to use it frequently in query filters or sorting.

Secondary Key Properties

followerUserId followingUserId

Secondary key properties are used to create an additional indexed identifiers for the data object, allowing for alternative access patterns. Different than normal indexed properties, secondary keys will act as primary keys and Mindbricks will provide automatic secondary key db utility functions to access the data object by the secondary key.

Relation Properties

followerUserId followingUserId

Mindbricks supports relations between data objects, allowing you to define how objects are linked together. You can define relations in the data object properties, which will be used to create foreign key constraints in the database. For complex joins operations, Mindbricks supportsa BFF pattern, where you can view dynamic and static views based on Elastic Search Indexes. Use db level relations for simple one-to-one or one-to-many relationships, and use BFF views for complex joins that require multiple data objects to be joined together.

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

On Delete: Set Null Required: Yes

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

On Delete: Set Null Required: Yes

Session Data Properties

followerUserId

Session data properties are used to store data that is specific to the user session, allowing for personalized experiences and temporary data storage. If a property is configured as session data, it will be automatically mapped to the related field in the user session during CRUD operations. Note that session data properties can not be mutated by the user, but only by the system.

This property is also used to store the owner of the session data, allowing for ownership checks and access control.

Filter Properties

followerUserId followingUserId

Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API’s that have “Auto Params” enabled.

Business Logic

projectPortfolio has got 18 Business APIs to manage its internal and crud logic. For the details of each business API refer to its chapter.

Service Library

Functions

isUserGrantedAccess.js

const { fetchRemoteObjectByMQuery } = require('serviceCommon');
module.exports = async function isUserGrantedAccess(projectId, userId) {
  if(!projectId || !userId) return false;
  const grant = await fetchRemoteObjectByMQuery('accessGrant', { projectId, granteeUserId: userId, status: 'granted' });
  return !!grant;
};

listProjectIdsGrantedToUser.js

const { fetchRemoteListByMQuery } = require('serviceCommon');
module.exports = async function listProjectIdsGrantedToUser(userId) {
  if(!userId) return [];
  const grants = await fetchRemoteListByMQuery('accessGrant', { granteeUserId: userId, status: 'granted' }, 0, 1000);
  return grants.map(g=>g.projectId);
};

This document was generated from the service architecture definition and should be kept in sync with implementation changes.


REST API GUIDE

REST API GUIDE

auteurlabb-projectportfolio-service

Version: 1.0.33

Handles the lifecycle of film projects and access management, allowing filmmakers & studios to submit, update, publish (public/private), withdraw projects, and manage project access for investors/bookmarks. Enforces admin approval & efficient searching/filtering. Connects projects to user (and optionally studio) ownership.

Architectural Design Credit and Contact Information

The architectural design of this microservice is credited to . For inquiries, feedback, or further information regarding the architecture, please direct your communication to:

Email:

We encourage open communication and welcome any questions or discussions related to the architectural aspects of this microservice.

Documentation Scope

Welcome to the official documentation for the ProjectPortfolio Service’s REST API. This document is designed to provide a comprehensive guide to interfacing with our ProjectPortfolio Service exclusively through RESTful API endpoints.

Intended Audience

This documentation is intended for developers and integrators who are looking to interact with the ProjectPortfolio Service via HTTP requests for purposes such as creating, updating, deleting and querying ProjectPortfolio objects.

Overview

Within these pages, you will find detailed information on how to effectively utilize the REST API, including authentication methods, request and response formats, endpoint descriptions, and examples of common use cases.

Beyond REST It’s important to note that the ProjectPortfolio Service also supports alternative methods of interaction, such as gRPC and messaging via a Message Broker. These communication methods are beyond the scope of this document. For information regarding these protocols, please refer to their respective documentation.

Authentication And Authorization

To ensure secure access to the ProjectPortfolio service’s protected endpoints, a project-wide access token is required. This token serves as the primary method for authenticating requests to our service. However, it’s important to note that access control varies across different routes:

Protected API: Certain API (routes) require specific authorization levels. Access to these routes is contingent upon the possession of a valid access token that meets the route-specific authorization criteria. Unauthorized requests to these routes will be rejected.

**Public API **: The service also includes public API (routes) that are accessible without authentication. These public endpoints are designed for open access and do not require an access token.

Token Locations

When including your access token in a request, ensure it is placed in one of the following specified locations. The service will sequentially search these locations for the token, utilizing the first one it encounters.

Location Token Name / Param Name
Query access_token
Authorization Header Bearer
Header auteurlabb-access-token
Cookie auteurlabb-access-token

Please ensure the token is correctly placed in one of these locations, using the appropriate label as indicated. The service prioritizes these locations in the order listed, processing the first token it successfully identifies.

Api Definitions

This section outlines the API endpoints available within the ProjectPortfolio service. Each endpoint can receive parameters through various methods, meticulously described in the following definitions. It’s important to understand the flexibility in how parameters can be included in requests to effectively interact with the ProjectPortfolio service.

This service is configured to listen for HTTP requests on port 3001, serving both the main API interface and default administrative endpoints.

The following routes are available by default:

This service is accessible via the following environment-specific URLs:

Parameter Inclusion Methods: Parameters can be incorporated into API requests in several ways, each with its designated location. Understanding these methods is crucial for correctly constructing your requests:

Query Parameters: Included directly in the URL’s query string.

Path Parameters: Embedded within the URL’s path.

Body Parameters: Sent within the JSON body of the request.

Session Parameters: Automatically read from the session object. This method is used for parameters that are intrinsic to the user’s session, such as userId. When using an API that involves session parameters, you can omit these from your request. The service will automatically bind them to the API layer, provided that a session is associated with your request.

Note on Session Parameters: Session parameters represent a unique method of parameter inclusion, relying on the context of the user’s session. A common example of a session parameter is userId, which the service automatically associates with your request when a session exists. This feature ensures seamless integration of user-specific data without manual input for each request.

By adhering to the specified parameter inclusion methods, you can effectively utilize the ProjectPortfolio service’s API endpoints. For detailed information on each endpoint, including required parameters and their accepted locations, refer to the individual API definitions below.

Common Parameters

The ProjectPortfolio service’s business API support several common parameters designed to modify and enhance the behavior of API requests. These parameters are not individually listed in the API route definitions to avoid repetition. Instead, refer to this section to understand how to leverage these common behaviors across different routes. Note that all common parameters should be included in the query part of the URL.

Supported Common Parameters:

By utilizing these common parameters, you can tailor the behavior of API requests to suit your specific requirements, ensuring optimal performance and usability of the ProjectPortfolio service.

Error Response

If a request encounters an issue, whether due to a logical fault or a technical problem, the service responds with a standardized JSON error structure. The HTTP status code within this response indicates the nature of the error, utilizing commonly recognized codes for clarity:

Each error response is structured to provide meaningful insight into the problem, assisting in diagnosing and resolving issues efficiently.

{
  "result": "ERR",
  "status": 400,
  "message": "errMsg_organizationIdisNotAValidID",
  "errCode": 400,
  "date": "2024-03-19T12:13:54.124Z",
  "detail": "String"
}

Object Structure of a Successfull Response

When the ProjectPortfolio service processes requests successfully, it wraps the requested resource(s) within a JSON envelope. This envelope not only contains the data but also includes essential metadata, such as configuration details and pagination information, to enrich the response and provide context to the client.

Key Characteristics of the Response Envelope:

Design Considerations: The structure of a API’s response data is meticulously crafted during the service’s architectural planning. This design ensures that responses adequately reflect the intended data relationships and service logic, providing clients with rich and meaningful information.

Brief Data: Certain API’s return a condensed version of the object data, intentionally selecting only specific fields deemed useful for that request. In such instances, the API documentation will detail the properties included in the response, guiding developers on what to expect.

API Response Structure

The API utilizes a standardized JSON envelope to encapsulate responses. This envelope is designed to consistently deliver both the requested data and essential metadata, ensuring that clients can efficiently interpret and utilize the response.

HTTP Status Codes:

Success Response Format:

For successful operations, the response includes a "status": "OK" property, signaling the successful execution of the request. The structure of a successful response is outlined below:

{
  "status":"OK",
  "statusCode": 200,   
  "elapsedMs":126,
  "ssoTime":120,
  "source": "db",
  "cacheKey": "hexCode",
  "userId": "ID",
  "sessionId": "ID",
  "requestId": "ID",
  "dataName":"products",
  "method":"GET",
  "action":"list",
  "appVersion":"Version",
  "rowCount":3
  "products":[{},{},{}],
  "paging": {
    "pageNumber":1, 
    "pageRowCount":25, 
    "totalRowCount":3,
    "pageCount":1
  },
  "filters": [],
  "uiPermissions": []
}

Handling Errors:

For details on handling error scenarios and understanding the structure of error responses, please refer to the “Error Response” section provided earlier in this documentation. It outlines how error conditions are communicated, including the use of HTTP status codes and standardized JSON structures for error messages.

Resources

ProjectPortfolio service provides the following resources which are stored in its own database as a data object. Note that a resource for an api access is a data object for the service.

FilmProject resource

Resource Definition : A film project submitted by a filmmaker or studio with all required metadata, visibility, and lifecycle status. FilmProject Resource Properties

Name Type Required Default Definition
title String Project title, unique per owner
description Text Project description (for details page/fulltext search)
synopsis Text Short synopsis or tagline
budget Double Estimated budget (USD)
cast String List of major cast members (names)
genre String Project genres/tags
projectType Enum Origin: filmmaker or studio
ownerUserId ID User ID of project owner (filmmaker/studio admin)
studioId ID (Optional) User ID of the studio (for studio projects)
isPublic Boolean Project public visibility flag
approvalStatus Enum Project approval/publication workflow status
mediaUrls String Project demo reel/trailer/cover media URLs
featured Boolean Platform feature flag (for promoted projects)
publishedAt Date Publication date
accessPolicy Enum Access policy (open: any authorized user, restricted: need grant)
director String Director of the film project
fundingGoal Double Funding goal amount (USD)

Enum Properties

Enum properties are represented as strings in the database. The values are mapped to their corresponding names in the application layer.

projectType Enum Property

Property Definition : Origin: filmmaker or studioEnum Options

Name Value Index
filmmaker "filmmaker"" 0
studio "studio"" 1
approvalStatus Enum Property

Property Definition : Project approval/publication workflow statusEnum Options

Name Value Index
pending "pending"" 0
approved "approved"" 1
rejected "rejected"" 2
withdrawn "withdrawn"" 3
accessPolicy Enum Property

Property Definition : Access policy (open: any authorized user, restricted: need grant)Enum Options

Name Value Index
open "open"" 0
restricted "restricted"" 1

AccessGrant resource

Resource Definition : Access grants to private projects, allowing selected users to view restricted projects (requested/granted/revoked/denied). AccessGrant Resource Properties

Name Type Required Default Definition
projectId ID Film project ID for which access is granted/requested
granteeUserId ID ID of user being granted/requesting access
grantedByUserId ID Who granted/revoked the access (or null for self-request)
status Enum requested (pending); granted (success); revoked; denied
requestMessage Text Message from requester (for context)
dateGranted Date Timestamp when access status last updated

Enum Properties

Enum properties are represented as strings in the database. The values are mapped to their corresponding names in the application layer.

status Enum Property

Property Definition : requested (pending); granted (success); revoked; deniedEnum Options

Name Value Index
requested "requested"" 0
granted "granted"" 1
revoked "revoked"" 2
denied "denied"" 3

ProjectBookmark resource

Resource Definition : User bookmarks/follows for projects. Each bookmark is per user+project. ProjectBookmark Resource Properties

Name Type Required Default Definition
projectId ID The project being bookmarked
userId ID The user who bookmarked this project
createdAtBookmark Date When bookmark was made

InvestmentOffer resource

Resource Definition : Tracks investment offers from investors to film projects. Each offer has an amount, optional message, and status workflow (pending/accepted/rejected/withdrawn). InvestmentOffer Resource Properties

Name Type Required Default Definition
projectId ID Film project receiving the investment offer
investorUserId ID Investor who made the offer
offerAmount Double Investment amount in USD
message Text Cover letter or terms from the investor
status Enum Offer lifecycle status
respondedAt Date When the project owner responded
responseNote Text Project owner note on accept/reject

Enum Properties

Enum properties are represented as strings in the database. The values are mapped to their corresponding names in the application layer.

status Enum Property

Property Definition : Offer lifecycle statusEnum Options

Name Value Index
pending "pending"" 0
accepted "accepted"" 1
rejected "rejected"" 2
withdrawn "withdrawn"" 3

UserFollow resource

Resource Definition : Tracks user-to-user follow relationships. A follower follows a target user (filmmaker, studio, investor). UserFollow Resource Properties

Name Type Required Default Definition
followerUserId ID The user who is following
followingUserId ID The user being followed
followedAt Date When the follow relationship was created

Business Api

Create Filmproject API

[Default create API] — This is the designated default create API for the filmProject data object. Frontend generators and AI agents should use this API for standard CRUD operations. Submit a new film project (by filmmaker/studio). Sets approvalStatus=pending and assigns ownerUserId from session. Studio projects require studioId.

API Frontend Description By The Backend Architect

Used by filmmakers/studios to submit a new project. Standard create form. Approval workflow starts automatically. Owner assigned from session.

Rest Route

The createFilmProject API REST controller can be triggered via the following route:

/v1/filmprojects

Rest Request Parameters

The createFilmProject api has got 15 regular request parameters

Parameter Type Required Population
title String true request.body?.[“title”]
description Text true request.body?.[“description”]
synopsis Text false request.body?.[“synopsis”]
budget Double true request.body?.[“budget”]
cast String false request.body?.[“cast”]
genre String false request.body?.[“genre”]
projectType Enum true request.body?.[“projectType”]
studioId ID false request.body?.[“studioId”]
isPublic Boolean true request.body?.[“isPublic”]
mediaUrls String false request.body?.[“mediaUrls”]
featured Boolean false request.body?.[“featured”]
publishedAt Date false request.body?.[“publishedAt”]
accessPolicy Enum true request.body?.[“accessPolicy”]
director String false request.body?.[“director”]
fundingGoal Double false request.body?.[“fundingGoal”]
title : Project title, unique per owner
description : Project description (for details page/fulltext search)
synopsis : Short synopsis or tagline
budget : Estimated budget (USD)
cast : List of major cast members (names)
genre : Project genres/tags
projectType : Origin: filmmaker or studio
studioId : (Optional) User ID of the studio (for studio projects)
isPublic : Project public visibility flag
mediaUrls : Project demo reel/trailer/cover media URLs
featured : Platform feature flag (for promoted projects)
publishedAt : Publication date
accessPolicy : Access policy (open: any authorized user, restricted: need grant)
director : Director of the film project
fundingGoal : Funding goal amount (USD)

REST Request To access the api you can use the REST controller with the path POST /v1/filmprojects

  axios({
    method: 'POST',
    url: '/v1/filmprojects',
    data: {
            title:"String",  
            description:"Text",  
            synopsis:"Text",  
            budget:"Double",  
            cast:"String",  
            genre:"String",  
            projectType:"Enum",  
            studioId:"ID",  
            isPublic:"Boolean",  
            mediaUrls:"String",  
            featured:"Boolean",  
            publishedAt:"Date",  
            accessPolicy:"Enum",  
            director:"String",  
            fundingGoal:"Double",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "filmProject",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"filmProject": {
		"id": "ID",
		"title": "String",
		"description": "Text",
		"synopsis": "Text",
		"budget": "Double",
		"cast": "String",
		"genre": "String",
		"projectType": "Enum",
		"projectType_idx": "Integer",
		"ownerUserId": "ID",
		"studioId": "ID",
		"isPublic": "Boolean",
		"approvalStatus": "Enum",
		"approvalStatus_idx": "Integer",
		"mediaUrls": "String",
		"featured": "Boolean",
		"publishedAt": "Date",
		"accessPolicy": "Enum",
		"accessPolicy_idx": "Integer",
		"director": "String",
		"fundingGoal": "Double",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Update Filmproject API

[Default update API] — This is the designated default update API for the filmProject data object. Frontend generators and AI agents should use this API for standard CRUD operations. Update a film project. Only the owner or admin can update. Only admin can set approvalStatus=approved/rejected. Owner can withdraw (approvalStatus=withdrawn).

API Frontend Description By The Backend Architect

For editing project details (including withdrawal). ApprovalStatus can only be changed by admin (other than withdrawn by owner). Owner cannot submit direct publish/approve requests; always wait admin.

Rest Route

The updateFilmProject API REST controller can be triggered via the following route:

/v1/filmprojects/:filmProjectId

Rest Request Parameters

The updateFilmProject api has got 15 regular request parameters

Parameter Type Required Population
filmProjectId ID true request.params?.[“filmProjectId”]
title String false request.body?.[“title”]
description Text false request.body?.[“description”]
synopsis Text false request.body?.[“synopsis”]
budget Double false request.body?.[“budget”]
cast String false request.body?.[“cast”]
genre String false request.body?.[“genre”]
isPublic Boolean false request.body?.[“isPublic”]
approvalStatus Enum true request.body?.[“approvalStatus”]
mediaUrls String false request.body?.[“mediaUrls”]
featured Boolean false request.body?.[“featured”]
publishedAt Date false request.body?.[“publishedAt”]
accessPolicy Enum false request.body?.[“accessPolicy”]
director String false request.body?.[“director”]
fundingGoal Double false request.body?.[“fundingGoal”]
filmProjectId : This id paremeter is used to select the required data object that will be updated
title : Project title, unique per owner
description : Project description (for details page/fulltext search)
synopsis : Short synopsis or tagline
budget : Estimated budget (USD)
cast : List of major cast members (names)
genre : Project genres/tags
isPublic : Project public visibility flag
approvalStatus : Project approval/publication workflow status
mediaUrls : Project demo reel/trailer/cover media URLs
featured : Platform feature flag (for promoted projects)
publishedAt : Publication date
accessPolicy : Access policy (open: any authorized user, restricted: need grant)
director : Director of the film project
fundingGoal : Funding goal amount (USD)

REST Request To access the api you can use the REST controller with the path PATCH /v1/filmprojects/:filmProjectId

  axios({
    method: 'PATCH',
    url: `/v1/filmprojects/${filmProjectId}`,
    data: {
            title:"String",  
            description:"Text",  
            synopsis:"Text",  
            budget:"Double",  
            cast:"String",  
            genre:"String",  
            isPublic:"Boolean",  
            approvalStatus:"Enum",  
            mediaUrls:"String",  
            featured:"Boolean",  
            publishedAt:"Date",  
            accessPolicy:"Enum",  
            director:"String",  
            fundingGoal:"Double",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "filmProject",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"filmProject": {
		"id": "ID",
		"title": "String",
		"description": "Text",
		"synopsis": "Text",
		"budget": "Double",
		"cast": "String",
		"genre": "String",
		"projectType": "Enum",
		"projectType_idx": "Integer",
		"ownerUserId": "ID",
		"studioId": "ID",
		"isPublic": "Boolean",
		"approvalStatus": "Enum",
		"approvalStatus_idx": "Integer",
		"mediaUrls": "String",
		"featured": "Boolean",
		"publishedAt": "Date",
		"accessPolicy": "Enum",
		"accessPolicy_idx": "Integer",
		"director": "String",
		"fundingGoal": "Double",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	},
	"ownerUser": {}
}

Get Filmproject API

[Default get API] — This is the designated default get API for the filmProject data object. Frontend generators and AI agents should use this API for standard CRUD operations. Fetch project details. Accessible by owner, admin, or for public + approved projects. Also for granted investors/users (accessGrant).

API Frontend Description By The Backend Architect

Used to display project details page. Applies access and visibility policy – if project is private, only owner/admin/granted users can see; if public+approved, visible to everyone logged in. User denied access gets 404.

Rest Route

The getFilmProject API REST controller can be triggered via the following route:

/v1/filmprojects/:filmProjectId

Rest Request Parameters

The getFilmProject api has got 1 regular request parameter

Parameter Type Required Population
filmProjectId ID true request.params?.[“filmProjectId”]
filmProjectId : This id paremeter is used to query the required data object.

REST Request To access the api you can use the REST controller with the path GET /v1/filmprojects/:filmProjectId

  axios({
    method: 'GET',
    url: `/v1/filmprojects/${filmProjectId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

This route’s response is constrained to a select list of properties, and therefore does not encompass all attributes of the resource.

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "filmProject",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"filmProject": {
		"ownerUser": {
			"fullname": "String",
			"avatar": "String",
			"roleId": "String"
		},
		"studio": {
			"fullname": "String",
			"avatar": "String",
			"roleId": "String"
		},
		"isActive": true
	}
}

List Filmprojects API

[Default list API] — This is the designated default list API for the filmProject data object. Frontend generators and AI agents should use this API for standard CRUD operations. List projects (public+approved, owned, or where granted). With filters for search. Results by role: owner/all their projects; normal users see only public+approved; investors/studios see owned or accessible, or public+approved. Filters: genre, budget, approvalStatus, isPublic, featured, projectType, title, description (text search).

API Frontend Description By The Backend Architect

Allows all users to search/browse projects. Only public/approved projects are visible to normal users; owners/investors get private projects to which they’re granted. Search by genre, budget, etc. Use for the main project directory.

Rest Route

The listFilmProjects API REST controller can be triggered via the following route:

/v1/filmprojects

Rest Request Parameters The listFilmProjects api has got no request parameters.

REST Request To access the api you can use the REST controller with the path GET /v1/filmprojects

  axios({
    method: 'GET',
    url: '/v1/filmprojects',
    data: {
    
    },
    params: {
    
        }
  });

REST Response

This route’s response is constrained to a select list of properties, and therefore does not encompass all attributes of the resource.

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "filmProjects",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"filmProjects": [
		{
			"ownerUser": [
				{
					"fullname": "String",
					"avatar": "String",
					"roleId": "String"
				},
				{},
				{}
			],
			"isActive": true
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Create Accessgrant API

[Default create API] — This is the designated default create API for the accessGrant data object. Frontend generators and AI agents should use this API for standard CRUD operations. Create a new accessGrant. Used for access requests (user) or direct grant (owner/admin).

API Frontend Description By The Backend Architect

Investors request access to private/restricted projects; project owners or admins grant/revoke access to users. Status flows: requested→granted/denied/revoked. Owner can only grant/revoke their own; admins can manage all.

Rest Route

The createAccessGrant API REST controller can be triggered via the following route:

/v1/accessgrants

Rest Request Parameters

The createAccessGrant api has got 6 regular request parameters

Parameter Type Required Population
projectId ID true request.body?.[“projectId”]
granteeUserId ID true request.body?.[“granteeUserId”]
grantedByUserId ID false request.body?.[“grantedByUserId”]
status Enum true request.body?.[“status”]
requestMessage Text false request.body?.[“requestMessage”]
dateGranted Date false request.body?.[“dateGranted”]
projectId : Film project ID for which access is granted/requested
granteeUserId : ID of user being granted/requesting access
grantedByUserId : Who granted/revoked the access (or null for self-request)
status : requested (pending); granted (success); revoked; denied
requestMessage : Message from requester (for context)
dateGranted : Timestamp when access status last updated

REST Request To access the api you can use the REST controller with the path POST /v1/accessgrants

  axios({
    method: 'POST',
    url: '/v1/accessgrants',
    data: {
            projectId:"ID",  
            granteeUserId:"ID",  
            grantedByUserId:"ID",  
            status:"Enum",  
            requestMessage:"Text",  
            dateGranted:"Date",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "accessGrant",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"accessGrant": {
		"id": "ID",
		"projectId": "ID",
		"granteeUserId": "ID",
		"grantedByUserId": "ID",
		"status": "Enum",
		"status_idx": "Integer",
		"requestMessage": "Text",
		"dateGranted": "Date",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Update Accessgrant API

[Default update API] — This is the designated default update API for the accessGrant data object. Frontend generators and AI agents should use this API for standard CRUD operations. Update status of an access grant. Only admin or project owner can grant, revoke, or deny. User can cancel (delete) their own pending request or see status.

API Frontend Description By The Backend Architect

Used for access management UI. Owners/admins can grant/revoke/deny access grants; requesters can cancel. For status transitions, always log who did it and when. Only valid transitions possible (ex: can’t grant if not owner/admin).

Rest Route

The updateAccessGrant API REST controller can be triggered via the following route:

/v1/accessgrants/:accessGrantId

Rest Request Parameters

The updateAccessGrant api has got 4 regular request parameters

Parameter Type Required Population
accessGrantId ID true request.params?.[“accessGrantId”]
status Enum true request.body?.[“status”]
requestMessage Text false request.body?.[“requestMessage”]
dateGranted Date false request.body?.[“dateGranted”]
accessGrantId : This id paremeter is used to select the required data object that will be updated
status : requested (pending); granted (success); revoked; denied
requestMessage : Message from requester (for context)
dateGranted : Timestamp when access status last updated

REST Request To access the api you can use the REST controller with the path PATCH /v1/accessgrants/:accessGrantId

  axios({
    method: 'PATCH',
    url: `/v1/accessgrants/${accessGrantId}`,
    data: {
            status:"Enum",  
            requestMessage:"Text",  
            dateGranted:"Date",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "accessGrant",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"accessGrant": {
		"id": "ID",
		"projectId": "ID",
		"granteeUserId": "ID",
		"grantedByUserId": "ID",
		"status": "Enum",
		"status_idx": "Integer",
		"requestMessage": "Text",
		"dateGranted": "Date",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Get Accessgrant API

[Default get API] — This is the designated default get API for the accessGrant data object. Frontend generators and AI agents should use this API for standard CRUD operations. Get a single accessGrant record by id. Used for grant management UI.

API Frontend Description By The Backend Architect

Shows a single access grant: who, for what project, current status, request message.

Rest Route

The getAccessGrant API REST controller can be triggered via the following route:

/v1/accessgrants/:accessGrantId

Rest Request Parameters

The getAccessGrant api has got 1 regular request parameter

Parameter Type Required Population
accessGrantId ID true request.params?.[“accessGrantId”]
accessGrantId : This id paremeter is used to query the required data object.

REST Request To access the api you can use the REST controller with the path GET /v1/accessgrants/:accessGrantId

  axios({
    method: 'GET',
    url: `/v1/accessgrants/${accessGrantId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "accessGrant",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"accessGrant": {
		"id": "ID",
		"projectId": "ID",
		"granteeUserId": "ID",
		"grantedByUserId": "ID",
		"status": "Enum",
		"status_idx": "Integer",
		"requestMessage": "Text",
		"dateGranted": "Date",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

List Accessgrants API

[Default list API] — This is the designated default list API for the accessGrant data object. Frontend generators and AI agents should use this API for standard CRUD operations. List all accessGrants for a project (owner/admin) or for a user (user’s own requests).

API Frontend Description By The Backend Architect

Used by project owners/admins to see all access requests; by users to see their own requests & statuses. Investors check their granted projects for dashboard; owners manage through this list.

Rest Route

The listAccessGrants API REST controller can be triggered via the following route:

/v1/accessgrants

Rest Request Parameters

Filter Parameters

The listAccessGrants api supports 3 optional filter parameters for filtering list results:

projectId (ID): Film project ID for which access is granted/requested

granteeUserId (ID): ID of user being granted/requesting access

status (Enum): requested (pending); granted (success); revoked; denied

REST Request To access the api you can use the REST controller with the path GET /v1/accessgrants

  axios({
    method: 'GET',
    url: '/v1/accessgrants',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section above)
        // projectId: '<value>' // Filter by projectId
        // granteeUserId: '<value>' // Filter by granteeUserId
        // status: '<value>' // Filter by status
            }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "accessGrants",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"accessGrants": [
		{
			"id": "ID",
			"projectId": "ID",
			"granteeUserId": "ID",
			"grantedByUserId": "ID",
			"status": "Enum",
			"status_idx": "Integer",
			"requestMessage": "Text",
			"dateGranted": "Date",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID"
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Create Bookmark API

[Default create API] — This is the designated default create API for the projectBookmark data object. Frontend generators and AI agents should use this API for standard CRUD operations. Add a project bookmark (user/project pair, unique).

API Frontend Description By The Backend Architect

Users bookmark projects for easy retrieval. Only one bookmark per (user, project).

Rest Route

The createBookmark API REST controller can be triggered via the following route:

/v1/bookmark

Rest Request Parameters

The createBookmark api has got 1 regular request parameter

Parameter Type Required Population
projectId ID true request.body?.[“projectId”]
projectId : The project being bookmarked

REST Request To access the api you can use the REST controller with the path POST /v1/bookmark

  axios({
    method: 'POST',
    url: '/v1/bookmark',
    data: {
            projectId:"ID",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "projectBookmark",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"projectBookmark": {
		"id": "ID",
		"projectId": "ID",
		"userId": "ID",
		"createdAtBookmark": "Date",
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"isActive": true
	}
}

Delete Bookmark API

[Default delete API] — This is the designated default delete API for the projectBookmark data object. Frontend generators and AI agents should use this API for standard CRUD operations. Remove a project bookmark (user can only delete their own bookmarks).

API Frontend Description By The Backend Architect

Bookmarks are always per-user: can only remove bookmark if you’re the owner.

Rest Route

The deleteBookmark API REST controller can be triggered via the following route:

/v1/bookmark/:projectBookmarkId

Rest Request Parameters

The deleteBookmark api has got 1 regular request parameter

Parameter Type Required Population
projectBookmarkId ID true request.params?.[“projectBookmarkId”]
projectBookmarkId : This id paremeter is used to select the required data object that will be deleted

REST Request To access the api you can use the REST controller with the path DELETE /v1/bookmark/:projectBookmarkId

  axios({
    method: 'DELETE',
    url: `/v1/bookmark/${projectBookmarkId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "projectBookmark",
	"method": "DELETE",
	"action": "delete",
	"appVersion": "Version",
	"rowCount": 1,
	"projectBookmark": {
		"id": "ID",
		"projectId": "ID",
		"userId": "ID",
		"createdAtBookmark": "Date",
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"isActive": false
	}
}

List Bookmarks API

[Default list API] — This is the designated default list API for the projectBookmark data object. Frontend generators and AI agents should use this API for standard CRUD operations. List a user’s own bookmarks. Only accessible for current user. Used for profile/bookmarks view.

API Frontend Description By The Backend Architect

Used for the user’s My Bookmarks page. Always lists only YOUR bookmarks, never others’.

Rest Route

The listBookmarks API REST controller can be triggered via the following route:

/v1/bookmarks

Rest Request Parameters

Filter Parameters

The listBookmarks api supports 2 optional filter parameters for filtering list results:

projectId (ID): The project being bookmarked

userId (ID): The user who bookmarked this project

REST Request To access the api you can use the REST controller with the path GET /v1/bookmarks

  axios({
    method: 'GET',
    url: '/v1/bookmarks',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section above)
        // projectId: '<value>' // Filter by projectId
        // userId: '<value>' // Filter by userId
            }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "projectBookmarks",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"projectBookmarks": [
		{
			"id": "ID",
			"projectId": "ID",
			"userId": "ID",
			"createdAtBookmark": "Date",
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID",
			"isActive": true
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Create Investmentoffer API

[Default create API] — This is the designated default create API for the investmentOffer data object. Frontend generators and AI agents should use this API for standard CRUD operations. Investor sends an investment offer to a film project. Status defaults to pending. Only investors can create offers.

Rest Route

The createInvestmentOffer API REST controller can be triggered via the following route:

/v1/investmentoffers

Rest Request Parameters

The createInvestmentOffer api has got 5 regular request parameters

Parameter Type Required Population
projectId ID true request.body?.[“projectId”]
offerAmount Double true request.body?.[“offerAmount”]
message Text false request.body?.[“message”]
respondedAt Date false request.body?.[“respondedAt”]
responseNote Text false request.body?.[“responseNote”]
projectId : Film project receiving the investment offer
offerAmount : Investment amount in USD
message : Cover letter or terms from the investor
respondedAt : When the project owner responded
responseNote : Project owner note on accept/reject

REST Request To access the api you can use the REST controller with the path POST /v1/investmentoffers

  axios({
    method: 'POST',
    url: '/v1/investmentoffers',
    data: {
            projectId:"ID",  
            offerAmount:"Double",  
            message:"Text",  
            respondedAt:"Date",  
            responseNote:"Text",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "investmentOffer",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"investmentOffer": {
		"id": "ID",
		"projectId": "ID",
		"investorUserId": "ID",
		"offerAmount": "Double",
		"message": "Text",
		"status": "Enum",
		"status_idx": "Integer",
		"respondedAt": "Date",
		"responseNote": "Text",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Respond Toinvestmentoffer API

[Default update API] — This is the designated default update API for the investmentOffer data object. Frontend generators and AI agents should use this API for standard CRUD operations. Project owner accepts or rejects an investment offer. Only the project owner or admin can respond.

Rest Route

The respondToInvestmentOffer API REST controller can be triggered via the following route:

/v1/respondtoinvestmentoffer/:investmentOfferId

Rest Request Parameters

The respondToInvestmentOffer api has got 6 regular request parameters

Parameter Type Required Population
investmentOfferId ID true request.params?.[“investmentOfferId”]
offerAmount Double false request.body?.[“offerAmount”]
message Text false request.body?.[“message”]
status Enum false request.body?.[“status”]
respondedAt Date false request.body?.[“respondedAt”]
responseNote Text false request.body?.[“responseNote”]
investmentOfferId : This id paremeter is used to select the required data object that will be updated
offerAmount : Investment amount in USD
message : Cover letter or terms from the investor
status : Offer lifecycle status
respondedAt : When the project owner responded
responseNote : Project owner note on accept/reject

REST Request To access the api you can use the REST controller with the path PATCH /v1/respondtoinvestmentoffer/:investmentOfferId

  axios({
    method: 'PATCH',
    url: `/v1/respondtoinvestmentoffer/${investmentOfferId}`,
    data: {
            offerAmount:"Double",  
            message:"Text",  
            status:"Enum",  
            respondedAt:"Date",  
            responseNote:"Text",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "investmentOffer",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"investmentOffer": {
		"id": "ID",
		"projectId": "ID",
		"investorUserId": "ID",
		"offerAmount": "Double",
		"message": "Text",
		"status": "Enum",
		"status_idx": "Integer",
		"respondedAt": "Date",
		"responseNote": "Text",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

List Investmentoffers API

[Default list API] — This is the designated default list API for the investmentOffer data object. Frontend generators and AI agents should use this API for standard CRUD operations. List investment offers. Admins see all, investors see their own, filmmakers/studios see offers on their projects.

Rest Route

The listInvestmentOffers API REST controller can be triggered via the following route:

/v1/investmentoffers

Rest Request Parameters

Filter Parameters

The listInvestmentOffers api supports 4 optional filter parameters for filtering list results:

projectId (ID): Film project receiving the investment offer

investorUserId (ID): Investor who made the offer

offerAmount (Double): Investment amount in USD

status (Enum): Offer lifecycle status

REST Request To access the api you can use the REST controller with the path GET /v1/investmentoffers

  axios({
    method: 'GET',
    url: '/v1/investmentoffers',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section above)
        // projectId: '<value>' // Filter by projectId
        // investorUserId: '<value>' // Filter by investorUserId
        // offerAmount: '<value>' // Filter by offerAmount
        // status: '<value>' // Filter by status
            }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "investmentOffers",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"investmentOffers": [
		{
			"id": "ID",
			"projectId": "ID",
			"investorUserId": "ID",
			"offerAmount": "Double",
			"message": "Text",
			"status": "Enum",
			"status_idx": "Integer",
			"respondedAt": "Date",
			"responseNote": "Text",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID"
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Withdraw Investmentoffer API

Investor withdraws their own pending offer. Sets status to withdrawn.

Rest Route

The withdrawInvestmentOffer API REST controller can be triggered via the following route:

/v1/withdrawinvestmentoffer/:investmentOfferId

Rest Request Parameters

The withdrawInvestmentOffer api has got 6 regular request parameters

Parameter Type Required Population
investmentOfferId ID true request.params?.[“investmentOfferId”]
offerAmount Double false request.body?.[“offerAmount”]
message Text false request.body?.[“message”]
status Enum false request.body?.[“status”]
respondedAt Date false request.body?.[“respondedAt”]
responseNote Text false request.body?.[“responseNote”]
investmentOfferId : This id paremeter is used to select the required data object that will be updated
offerAmount : Investment amount in USD
message : Cover letter or terms from the investor
status : Offer lifecycle status
respondedAt : When the project owner responded
responseNote : Project owner note on accept/reject

REST Request To access the api you can use the REST controller with the path PATCH /v1/withdrawinvestmentoffer/:investmentOfferId

  axios({
    method: 'PATCH',
    url: `/v1/withdrawinvestmentoffer/${investmentOfferId}`,
    data: {
            offerAmount:"Double",  
            message:"Text",  
            status:"Enum",  
            respondedAt:"Date",  
            responseNote:"Text",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "investmentOffer",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"investmentOffer": {
		"id": "ID",
		"projectId": "ID",
		"investorUserId": "ID",
		"offerAmount": "Double",
		"message": "Text",
		"status": "Enum",
		"status_idx": "Integer",
		"respondedAt": "Date",
		"responseNote": "Text",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Follow User API

[Default create API] — This is the designated default create API for the userFollow data object. Frontend generators and AI agents should use this API for standard CRUD operations. Follow a user. Creates a follow relationship between the session user and the target user. Duplicate follows are prevented by composite index.

Rest Route

The followUser API REST controller can be triggered via the following route:

/v1/followuser

Rest Request Parameters

The followUser api has got 2 regular request parameters

Parameter Type Required Population
followingUserId ID true request.body?.[“followingUserId”]
followedAt Date false request.body?.[“followedAt”]
followingUserId : The user being followed
followedAt : When the follow relationship was created

REST Request To access the api you can use the REST controller with the path POST /v1/followuser

  axios({
    method: 'POST',
    url: '/v1/followuser',
    data: {
            followingUserId:"ID",  
            followedAt:"Date",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "userFollow",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"userFollow": {
		"id": "ID",
		"followerUserId": "ID",
		"followingUserId": "ID",
		"followedAt": "Date",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Unfollow User API

[Default delete API] — This is the designated default delete API for the userFollow data object. Frontend generators and AI agents should use this API for standard CRUD operations. Unfollow a user. Removes the follow relationship. Only the follower (owner) can unfollow.

Rest Route

The unfollowUser API REST controller can be triggered via the following route:

/v1/unfollowuser/:userFollowId

Rest Request Parameters

The unfollowUser api has got 1 regular request parameter

Parameter Type Required Population
userFollowId ID true request.params?.[“userFollowId”]
userFollowId : This id paremeter is used to select the required data object that will be deleted

REST Request To access the api you can use the REST controller with the path DELETE /v1/unfollowuser/:userFollowId

  axios({
    method: 'DELETE',
    url: `/v1/unfollowuser/${userFollowId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "userFollow",
	"method": "DELETE",
	"action": "delete",
	"appVersion": "Version",
	"rowCount": 1,
	"userFollow": {
		"id": "ID",
		"followerUserId": "ID",
		"followingUserId": "ID",
		"followedAt": "Date",
		"isActive": false,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

List Userfollows API

[Default list API] — This is the designated default list API for the userFollow data object. Frontend generators and AI agents should use this API for standard CRUD operations. List follow relationships. Filter by followerUserId to get who a user follows, or by followingUserId to get a user’s followers.

Rest Route

The listUserFollows API REST controller can be triggered via the following route:

/v1/userfollows

Rest Request Parameters

Filter Parameters

The listUserFollows api supports 2 optional filter parameters for filtering list results:

followerUserId (ID): The user who is following

followingUserId (ID): The user being followed

REST Request To access the api you can use the REST controller with the path GET /v1/userfollows

  axios({
    method: 'GET',
    url: '/v1/userfollows',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section above)
        // followerUserId: '<value>' // Filter by followerUserId
        // followingUserId: '<value>' // Filter by followingUserId
            }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "userFollows",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"userFollows": [
		{
			"id": "ID",
			"followerUserId": "ID",
			"followingUserId": "ID",
			"followedAt": "Date",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID"
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Authentication Specific Routes

Common Routes

Route: currentuser

Route Definition: Retrieves the currently authenticated user’s session information.

Route Type: sessionInfo

Access Route: GET /currentuser

Parameters

This route does not require any request parameters.

Behavior

// Sample GET /currentuser call
axios.get("/currentuser", {
  headers: {
    "Authorization": "Bearer your-jwt-token"
  }
});

Success Response Returns the session object, including user-related data and token information.

{
  "sessionId": "9cf23fa8-07d4-4e7c-80a6-ec6d6ac96bb9",
  "userId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38",
  "email": "user@example.com",
  "fullname": "John Doe",
  "roleId": "user",
  "tenantId": "abc123",
  "accessToken": "jwt-token-string",
  ...
}

Error Response 401 Unauthorized: No active session found.

{
  "status": "ERR",
  "message": "No login found"
}

Notes

Route: permissions

*Route Definition*: Retrieves all effective permission records assigned to the currently authenticated user.

*Route Type*: permissionFetch

Access Route: GET /permissions

Parameters

This route does not require any request parameters.

Behavior

// Sample GET /permissions call
axios.get("/permissions", {
  headers: {
    "Authorization": "Bearer your-jwt-token"
  }
});

Success Response

Returns an array of permission objects.

[
  {
    "id": "perm1",
    "permissionName": "adminPanel.access",
    "roleId": "admin",
    "subjectUserId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38",
    "subjectUserGroupId": null,
    "objectId": null,
    "canDo": true,
    "tenantCodename": "store123"
  },
  {
    "id": "perm2",
    "permissionName": "orders.manage",
    "roleId": null,
    "subjectUserId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38",
    "subjectUserGroupId": null,
    "objectId": null,
    "canDo": true,
    "tenantCodename": "store123"
  }
]

Each object reflects a single permission grant, aligned with the givenPermissions model:

Error Responses

{
  "status": "ERR",
  "message": "No login found"
}

Notes

Tip: Applications can cache permission results client-side or server-side, but should occasionally refresh by calling this endpoint, especially after login or permission-changing operations.

Route: permissions/:permissionName

Route Definition: Checks whether the current user has access to a specific permission, and provides a list of scoped object exceptions or inclusions.

Route Type: permissionScopeCheck

Access Route: GET /permissions/:permissionName

Parameters

Parameter Type Required Population
permissionName String Yes request.params.permissionName

Behavior

// Sample GET /permissions/orders.manage
axios.get("/permissions/orders.manage", {
  headers: {
    "Authorization": "Bearer your-jwt-token"
  }
});

Success Response

{
  "canDo": true,
  "exceptions": [
    "a1f2e3d4-xxxx-yyyy-zzzz-object1",
    "b2c3d4e5-xxxx-yyyy-zzzz-object2"
  ]
}

Copyright

All sources, documents and other digital materials are copyright of .

About Us

For more information please visit our website: .

. .


EVENT GUIDE

EVENT GUIDE

auteurlabb-projectportfolio-service

Handles the lifecycle of film projects and access management, allowing filmmakers & studios to submit, update, publish (public/private), withdraw projects, and manage project access for investors/bookmarks. Enforces admin approval & efficient searching/filtering. Connects projects to user (and optionally studio) ownership.

Architectural Design Credit and Contact Information

The architectural design of this microservice is credited to . For inquiries, feedback, or further information regarding the architecture, please direct your communication to:

Email:

We encourage open communication and welcome any questions or discussions related to the architectural aspects of this microservice.

Documentation Scope

Welcome to the official documentation for the ProjectPortfolio Service Event descriptions. This guide is dedicated to detailing how to subscribe to and listen for state changes within the ProjectPortfolio Service, offering an exclusive focus on event subscription mechanisms.

Intended Audience

This documentation is aimed at developers and integrators looking to monitor ProjectPortfolio Service state changes. It is especially relevant for those wishing to implement or enhance business logic based on interactions with ProjectPortfolio objects.

Overview

This section provides detailed instructions on monitoring service events, covering payload structures and demonstrating typical use cases through examples.

Authentication and Authorization

Access to the ProjectPortfolio service’s events is facilitated through the project’s Kafka server, which is not accessible to the public. Subscription to a Kafka topic requires being on the same network and possessing valid Kafka user credentials. This document presupposes that readers have existing access to the Kafka server.

Additionally, the service offers a public subscription option via REST for real-time data management in frontend applications, secured through REST API authentication and authorization mechanisms. To subscribe to service events via the REST API, please consult the Realtime REST API Guide.

Database Events

Database events are triggered at the database layer, automatically and atomically, in response to any modifications at the data level. These events serve to notify subscribers about the creation, update, or deletion of objects within the database, distinct from any overarching business logic.

Listening to database events is particularly beneficial for those focused on tracking changes at the database level. A typical use case for subscribing to database events is to replicate the data store of one service within another service’s scope, ensuring data consistency and syncronization across services.

For example, while a business operation such as “approve membership” might generate a high-level business event like membership-approved, the underlying database changes could involve multiple state updates to different entities. These might be published as separate events, such as dbevent-member-updated and dbevent-user-updated, reflecting the granular changes at the database level.

Such detailed eventing provides a robust foundation for building responsive, data-driven applications, enabling fine-grained observability and reaction to the dynamics of the data landscape. It also facilitates the architectural pattern of event sourcing, where state changes are captured as a sequence of events, allowing for high-fidelity data replication and history replay for analytical or auditing purposes.

DbEvent filmProject-created

Event topic: auteurlabb-projectportfolio-service-dbevent-filmproject-created

This event is triggered upon the creation of a filmProject data object in the database. The event payload encompasses the newly created data, encapsulated within the root of the paylod.

Event payload:

{"id":"ID","title":"String","description":"Text","synopsis":"Text","budget":"Double","cast":"String","genre":"String","projectType":"Enum","projectType_idx":"Integer","ownerUserId":"ID","studioId":"ID","isPublic":"Boolean","approvalStatus":"Enum","approvalStatus_idx":"Integer","mediaUrls":"String","featured":"Boolean","publishedAt":"Date","accessPolicy":"Enum","accessPolicy_idx":"Integer","director":"String","fundingGoal":"Double","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

DbEvent filmProject-updated

Event topic: auteurlabb-projectportfolio-service-dbevent-filmproject-updated

Activation of this event follows the update of a filmProject data object. The payload contains the updated information under the filmProject attribute, along with the original data prior to update, labeled as old_filmProject and also you can find the old and new versions of updated-only portion of the data…

Event payload:

{
old_filmProject:{"id":"ID","title":"String","description":"Text","synopsis":"Text","budget":"Double","cast":"String","genre":"String","projectType":"Enum","projectType_idx":"Integer","ownerUserId":"ID","studioId":"ID","isPublic":"Boolean","approvalStatus":"Enum","approvalStatus_idx":"Integer","mediaUrls":"String","featured":"Boolean","publishedAt":"Date","accessPolicy":"Enum","accessPolicy_idx":"Integer","director":"String","fundingGoal":"Double","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},
filmProject:{"id":"ID","title":"String","description":"Text","synopsis":"Text","budget":"Double","cast":"String","genre":"String","projectType":"Enum","projectType_idx":"Integer","ownerUserId":"ID","studioId":"ID","isPublic":"Boolean","approvalStatus":"Enum","approvalStatus_idx":"Integer","mediaUrls":"String","featured":"Boolean","publishedAt":"Date","accessPolicy":"Enum","accessPolicy_idx":"Integer","director":"String","fundingGoal":"Double","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},
oldDataValues,
newDataValues
}

DbEvent filmProject-deleted

Event topic: auteurlabb-projectportfolio-service-dbevent-filmproject-deleted

This event announces the deletion of a filmProject data object, covering both hard deletions (permanent removal) and soft deletions (where the isActive attribute is set to false). Regardless of the deletion type, the event payload will present the data as it was immediately before deletion, highlighting an isActive status of false for soft deletions.

Event payload:

{"id":"ID","title":"String","description":"Text","synopsis":"Text","budget":"Double","cast":"String","genre":"String","projectType":"Enum","projectType_idx":"Integer","ownerUserId":"ID","studioId":"ID","isPublic":"Boolean","approvalStatus":"Enum","approvalStatus_idx":"Integer","mediaUrls":"String","featured":"Boolean","publishedAt":"Date","accessPolicy":"Enum","accessPolicy_idx":"Integer","director":"String","fundingGoal":"Double","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

DbEvent accessGrant-created

Event topic: auteurlabb-projectportfolio-service-dbevent-accessgrant-created

This event is triggered upon the creation of a accessGrant data object in the database. The event payload encompasses the newly created data, encapsulated within the root of the paylod.

Event payload:

{"id":"ID","projectId":"ID","granteeUserId":"ID","grantedByUserId":"ID","status":"Enum","status_idx":"Integer","requestMessage":"Text","dateGranted":"Date","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

DbEvent accessGrant-updated

Event topic: auteurlabb-projectportfolio-service-dbevent-accessgrant-updated

Activation of this event follows the update of a accessGrant data object. The payload contains the updated information under the accessGrant attribute, along with the original data prior to update, labeled as old_accessGrant and also you can find the old and new versions of updated-only portion of the data…

Event payload:

{
old_accessGrant:{"id":"ID","projectId":"ID","granteeUserId":"ID","grantedByUserId":"ID","status":"Enum","status_idx":"Integer","requestMessage":"Text","dateGranted":"Date","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},
accessGrant:{"id":"ID","projectId":"ID","granteeUserId":"ID","grantedByUserId":"ID","status":"Enum","status_idx":"Integer","requestMessage":"Text","dateGranted":"Date","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},
oldDataValues,
newDataValues
}

DbEvent accessGrant-deleted

Event topic: auteurlabb-projectportfolio-service-dbevent-accessgrant-deleted

This event announces the deletion of a accessGrant data object, covering both hard deletions (permanent removal) and soft deletions (where the isActive attribute is set to false). Regardless of the deletion type, the event payload will present the data as it was immediately before deletion, highlighting an isActive status of false for soft deletions.

Event payload:

{"id":"ID","projectId":"ID","granteeUserId":"ID","grantedByUserId":"ID","status":"Enum","status_idx":"Integer","requestMessage":"Text","dateGranted":"Date","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

DbEvent projectBookmark-created

Event topic: auteurlabb-projectportfolio-service-dbevent-projectbookmark-created

This event is triggered upon the creation of a projectBookmark data object in the database. The event payload encompasses the newly created data, encapsulated within the root of the paylod.

Event payload:

{"id":"ID","projectId":"ID","userId":"ID","createdAtBookmark":"Date","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

DbEvent projectBookmark-updated

Event topic: auteurlabb-projectportfolio-service-dbevent-projectbookmark-updated

Activation of this event follows the update of a projectBookmark data object. The payload contains the updated information under the projectBookmark attribute, along with the original data prior to update, labeled as old_projectBookmark and also you can find the old and new versions of updated-only portion of the data…

Event payload:

{
old_projectBookmark:{"id":"ID","projectId":"ID","userId":"ID","createdAtBookmark":"Date","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},
projectBookmark:{"id":"ID","projectId":"ID","userId":"ID","createdAtBookmark":"Date","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},
oldDataValues,
newDataValues
}

DbEvent projectBookmark-deleted

Event topic: auteurlabb-projectportfolio-service-dbevent-projectbookmark-deleted

This event announces the deletion of a projectBookmark data object, covering both hard deletions (permanent removal) and soft deletions (where the isActive attribute is set to false). Regardless of the deletion type, the event payload will present the data as it was immediately before deletion, highlighting an isActive status of false for soft deletions.

Event payload:

{"id":"ID","projectId":"ID","userId":"ID","createdAtBookmark":"Date","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":false}

DbEvent investmentOffer-created

Event topic: auteurlabb-projectportfolio-service-dbevent-investmentoffer-created

This event is triggered upon the creation of a investmentOffer data object in the database. The event payload encompasses the newly created data, encapsulated within the root of the paylod.

Event payload:

{"id":"ID","projectId":"ID","investorUserId":"ID","offerAmount":"Double","message":"Text","status":"Enum","status_idx":"Integer","respondedAt":"Date","responseNote":"Text","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

DbEvent investmentOffer-updated

Event topic: auteurlabb-projectportfolio-service-dbevent-investmentoffer-updated

Activation of this event follows the update of a investmentOffer data object. The payload contains the updated information under the investmentOffer attribute, along with the original data prior to update, labeled as old_investmentOffer and also you can find the old and new versions of updated-only portion of the data…

Event payload:

{
old_investmentOffer:{"id":"ID","projectId":"ID","investorUserId":"ID","offerAmount":"Double","message":"Text","status":"Enum","status_idx":"Integer","respondedAt":"Date","responseNote":"Text","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},
investmentOffer:{"id":"ID","projectId":"ID","investorUserId":"ID","offerAmount":"Double","message":"Text","status":"Enum","status_idx":"Integer","respondedAt":"Date","responseNote":"Text","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},
oldDataValues,
newDataValues
}

DbEvent investmentOffer-deleted

Event topic: auteurlabb-projectportfolio-service-dbevent-investmentoffer-deleted

This event announces the deletion of a investmentOffer data object, covering both hard deletions (permanent removal) and soft deletions (where the isActive attribute is set to false). Regardless of the deletion type, the event payload will present the data as it was immediately before deletion, highlighting an isActive status of false for soft deletions.

Event payload:

{"id":"ID","projectId":"ID","investorUserId":"ID","offerAmount":"Double","message":"Text","status":"Enum","status_idx":"Integer","respondedAt":"Date","responseNote":"Text","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

DbEvent userFollow-created

Event topic: auteurlabb-projectportfolio-service-dbevent-userfollow-created

This event is triggered upon the creation of a userFollow data object in the database. The event payload encompasses the newly created data, encapsulated within the root of the paylod.

Event payload:

{"id":"ID","followerUserId":"ID","followingUserId":"ID","followedAt":"Date","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

DbEvent userFollow-updated

Event topic: auteurlabb-projectportfolio-service-dbevent-userfollow-updated

Activation of this event follows the update of a userFollow data object. The payload contains the updated information under the userFollow attribute, along with the original data prior to update, labeled as old_userFollow and also you can find the old and new versions of updated-only portion of the data…

Event payload:

{
old_userFollow:{"id":"ID","followerUserId":"ID","followingUserId":"ID","followedAt":"Date","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},
userFollow:{"id":"ID","followerUserId":"ID","followingUserId":"ID","followedAt":"Date","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},
oldDataValues,
newDataValues
}

DbEvent userFollow-deleted

Event topic: auteurlabb-projectportfolio-service-dbevent-userfollow-deleted

This event announces the deletion of a userFollow data object, covering both hard deletions (permanent removal) and soft deletions (where the isActive attribute is set to false). Regardless of the deletion type, the event payload will present the data as it was immediately before deletion, highlighting an isActive status of false for soft deletions.

Event payload:

{"id":"ID","followerUserId":"ID","followingUserId":"ID","followedAt":"Date","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

ElasticSearch Index Events

Within the ProjectPortfolio service, most data objects are mirrored in ElasticSearch indices, ensuring these indices remain syncronized with their database counterparts through creation, updates, and deletions. These indices serve dual purposes: they act as a data source for external services and furnish aggregated data tailored to enhance frontend user experiences. Consequently, an ElasticSearch index might encapsulate data in its original form or aggregate additional information from other data objects.

These aggregations can include both one-to-one and one-to-many relationships not only with database objects within the same service but also across different services. This capability allows developers to access comprehensive, aggregated data efficiently. By subscribing to ElasticSearch index events, developers are notified when an index is updated and can directly obtain the aggregated entity within the event payload, bypassing the need for separate ElasticSearch queries.

It’s noteworthy that some services may augment another service’s index by appending to the entity’s extends object. In such scenarios, an *-extended event will contain only the newly added data. Should you require the complete dataset, you would need to retrieve the full ElasticSearch index entity using the provided ID.

This approach to indexing and event handling facilitates a modular, interconnected architecture where services can seamlessly integrate and react to changes, enriching the overall data ecosystem and enabling more dynamic, responsive applications.

Index Event filmproject-created

Event topic: elastic-index-auteurlabb_filmproject-created

Event payload:

{"id":"ID","title":"String","description":"Text","synopsis":"Text","budget":"Double","cast":"String","genre":"String","projectType":"Enum","projectType_idx":"Integer","ownerUserId":"ID","studioId":"ID","isPublic":"Boolean","approvalStatus":"Enum","approvalStatus_idx":"Integer","mediaUrls":"String","featured":"Boolean","publishedAt":"Date","accessPolicy":"Enum","accessPolicy_idx":"Integer","director":"String","fundingGoal":"Double","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event filmproject-updated

Event topic: elastic-index-auteurlabb_filmproject-created

Event payload:

{"id":"ID","title":"String","description":"Text","synopsis":"Text","budget":"Double","cast":"String","genre":"String","projectType":"Enum","projectType_idx":"Integer","ownerUserId":"ID","studioId":"ID","isPublic":"Boolean","approvalStatus":"Enum","approvalStatus_idx":"Integer","mediaUrls":"String","featured":"Boolean","publishedAt":"Date","accessPolicy":"Enum","accessPolicy_idx":"Integer","director":"String","fundingGoal":"Double","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event filmproject-deleted

Event topic: elastic-index-auteurlabb_filmproject-deleted

Event payload:

{"id":"ID","title":"String","description":"Text","synopsis":"Text","budget":"Double","cast":"String","genre":"String","projectType":"Enum","projectType_idx":"Integer","ownerUserId":"ID","studioId":"ID","isPublic":"Boolean","approvalStatus":"Enum","approvalStatus_idx":"Integer","mediaUrls":"String","featured":"Boolean","publishedAt":"Date","accessPolicy":"Enum","accessPolicy_idx":"Integer","director":"String","fundingGoal":"Double","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event filmproject-extended

Event topic: elastic-index-auteurlabb_filmproject-extended

Event payload:

{
  id: id,
  extends: {
    [extendName]: "Object",
    [extendName + "_count"]: "Number",
  },
}

Route Events

Route events are emitted following the successful execution of a route. While most routes perform CRUD (Create, Read, Update, Delete) operations on data objects, resulting in route events that closely resemble database events, there are distinctions worth noting. A single route execution might trigger multiple CRUD actions and ElasticSearch indexing operations. However, for those primarily concerned with the overarching business logic and its outcomes, listening to the consolidated route event, published once at the conclusion of the route’s execution, is more pertinent.

Moreover, routes often deliver aggregated data beyond the primary database object, catering to specific client needs. For instance, creating a data object via a route might not only return the entity’s data but also route-specific metrics, such as the executing user’s permissions related to the entity. Alternatively, a route might automatically generate default child entities following the creation of a parent object. Consequently, the route event encapsulates a unified dataset encompassing both the parent and its children, in contrast to individual events triggered for each entity created. Therefore, subscribing to route events can offer a richer, more contextually relevant set of information aligned with business logic.

The payload of a route event mirrors the REST response JSON of the route, providing a direct and comprehensive reflection of the data and metadata communicated to the client. This ensures that subscribers to route events receive a payload that encapsulates both the primary data involved and any additional information deemed significant at the business level, facilitating a deeper understanding and integration of the service’s functional outcomes.

Route Event filmproject-created

Event topic : auteurlabb-projectportfolio-service-filmproject-created

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the filmProject data object itself.

The following JSON included in the payload illustrates the fullest representation of the filmProject object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"filmProject","method":"POST","action":"create","appVersion":"Version","rowCount":1,"filmProject":{"id":"ID","title":"String","description":"Text","synopsis":"Text","budget":"Double","cast":"String","genre":"String","projectType":"Enum","projectType_idx":"Integer","ownerUserId":"ID","studioId":"ID","isPublic":"Boolean","approvalStatus":"Enum","approvalStatus_idx":"Integer","mediaUrls":"String","featured":"Boolean","publishedAt":"Date","accessPolicy":"Enum","accessPolicy_idx":"Integer","director":"String","fundingGoal":"Double","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event filmproject-updated

Event topic : auteurlabb-projectportfolio-service-filmproject-updated

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the filmProject data object itself.

The following JSON included in the payload illustrates the fullest representation of the filmProject object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"filmProject","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"filmProject":{"id":"ID","title":"String","description":"Text","synopsis":"Text","budget":"Double","cast":"String","genre":"String","projectType":"Enum","projectType_idx":"Integer","ownerUserId":"ID","studioId":"ID","isPublic":"Boolean","approvalStatus":"Enum","approvalStatus_idx":"Integer","mediaUrls":"String","featured":"Boolean","publishedAt":"Date","accessPolicy":"Enum","accessPolicy_idx":"Integer","director":"String","fundingGoal":"Double","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"ownerUser":{}}

Route Event accessgrant-created

Event topic : auteurlabb-projectportfolio-service-accessgrant-created

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the accessGrant data object itself.

The following JSON included in the payload illustrates the fullest representation of the accessGrant object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"accessGrant","method":"POST","action":"create","appVersion":"Version","rowCount":1,"accessGrant":{"id":"ID","projectId":"ID","granteeUserId":"ID","grantedByUserId":"ID","status":"Enum","status_idx":"Integer","requestMessage":"Text","dateGranted":"Date","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event accessgrant-updated

Event topic : auteurlabb-projectportfolio-service-accessgrant-updated

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the accessGrant data object itself.

The following JSON included in the payload illustrates the fullest representation of the accessGrant object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"accessGrant","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"accessGrant":{"id":"ID","projectId":"ID","granteeUserId":"ID","grantedByUserId":"ID","status":"Enum","status_idx":"Integer","requestMessage":"Text","dateGranted":"Date","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event bookmark-created

Event topic : auteurlabb-projectportfolio-service-bookmark-created

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the projectBookmark data object itself.

The following JSON included in the payload illustrates the fullest representation of the projectBookmark object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"projectBookmark","method":"POST","action":"create","appVersion":"Version","rowCount":1,"projectBookmark":{"id":"ID","projectId":"ID","userId":"ID","createdAtBookmark":"Date","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true}}

Route Event bookmark-deleted

Event topic : auteurlabb-projectportfolio-service-bookmark-deleted

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the projectBookmark data object itself.

The following JSON included in the payload illustrates the fullest representation of the projectBookmark object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"projectBookmark","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"projectBookmark":{"id":"ID","projectId":"ID","userId":"ID","createdAtBookmark":"Date","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":false}}

Route Event investmentoffer-created

Event topic : auteurlabb-projectportfolio-service-investmentoffer-created

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the investmentOffer data object itself.

The following JSON included in the payload illustrates the fullest representation of the investmentOffer object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"investmentOffer","method":"POST","action":"create","appVersion":"Version","rowCount":1,"investmentOffer":{"id":"ID","projectId":"ID","investorUserId":"ID","offerAmount":"Double","message":"Text","status":"Enum","status_idx":"Integer","respondedAt":"Date","responseNote":"Text","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event toinvestmentoffer-responded

Event topic : auteurlabb-projectportfolio-service-toinvestmentoffer-responded

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the investmentOffer data object itself.

The following JSON included in the payload illustrates the fullest representation of the investmentOffer object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"investmentOffer","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"investmentOffer":{"id":"ID","projectId":"ID","investorUserId":"ID","offerAmount":"Double","message":"Text","status":"Enum","status_idx":"Integer","respondedAt":"Date","responseNote":"Text","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event investmentoffer-withdrawn

Event topic : auteurlabb-projectportfolio-service-investmentoffer-withdrawn

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the investmentOffer data object itself.

The following JSON included in the payload illustrates the fullest representation of the investmentOffer object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"investmentOffer","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"investmentOffer":{"id":"ID","projectId":"ID","investorUserId":"ID","offerAmount":"Double","message":"Text","status":"Enum","status_idx":"Integer","respondedAt":"Date","responseNote":"Text","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event user-followed

Event topic : auteurlabb-projectportfolio-service-user-followed

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the userFollow data object itself.

The following JSON included in the payload illustrates the fullest representation of the userFollow object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"userFollow","method":"POST","action":"create","appVersion":"Version","rowCount":1,"userFollow":{"id":"ID","followerUserId":"ID","followingUserId":"ID","followedAt":"Date","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event user-unfollowed

Event topic : auteurlabb-projectportfolio-service-user-unfollowed

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the userFollow data object itself.

The following JSON included in the payload illustrates the fullest representation of the userFollow object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"userFollow","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"userFollow":{"id":"ID","followerUserId":"ID","followingUserId":"ID","followedAt":"Date","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Index Event accessgrant-created

Event topic: elastic-index-auteurlabb_accessgrant-created

Event payload:

{"id":"ID","projectId":"ID","granteeUserId":"ID","grantedByUserId":"ID","status":"Enum","status_idx":"Integer","requestMessage":"Text","dateGranted":"Date","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event accessgrant-updated

Event topic: elastic-index-auteurlabb_accessgrant-created

Event payload:

{"id":"ID","projectId":"ID","granteeUserId":"ID","grantedByUserId":"ID","status":"Enum","status_idx":"Integer","requestMessage":"Text","dateGranted":"Date","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event accessgrant-deleted

Event topic: elastic-index-auteurlabb_accessgrant-deleted

Event payload:

{"id":"ID","projectId":"ID","granteeUserId":"ID","grantedByUserId":"ID","status":"Enum","status_idx":"Integer","requestMessage":"Text","dateGranted":"Date","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event accessgrant-extended

Event topic: elastic-index-auteurlabb_accessgrant-extended

Event payload:

{
  id: id,
  extends: {
    [extendName]: "Object",
    [extendName + "_count"]: "Number",
  },
}

Route Events

Route events are emitted following the successful execution of a route. While most routes perform CRUD (Create, Read, Update, Delete) operations on data objects, resulting in route events that closely resemble database events, there are distinctions worth noting. A single route execution might trigger multiple CRUD actions and ElasticSearch indexing operations. However, for those primarily concerned with the overarching business logic and its outcomes, listening to the consolidated route event, published once at the conclusion of the route’s execution, is more pertinent.

Moreover, routes often deliver aggregated data beyond the primary database object, catering to specific client needs. For instance, creating a data object via a route might not only return the entity’s data but also route-specific metrics, such as the executing user’s permissions related to the entity. Alternatively, a route might automatically generate default child entities following the creation of a parent object. Consequently, the route event encapsulates a unified dataset encompassing both the parent and its children, in contrast to individual events triggered for each entity created. Therefore, subscribing to route events can offer a richer, more contextually relevant set of information aligned with business logic.

The payload of a route event mirrors the REST response JSON of the route, providing a direct and comprehensive reflection of the data and metadata communicated to the client. This ensures that subscribers to route events receive a payload that encapsulates both the primary data involved and any additional information deemed significant at the business level, facilitating a deeper understanding and integration of the service’s functional outcomes.

Route Event filmproject-created

Event topic : auteurlabb-projectportfolio-service-filmproject-created

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the filmProject data object itself.

The following JSON included in the payload illustrates the fullest representation of the filmProject object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"filmProject","method":"POST","action":"create","appVersion":"Version","rowCount":1,"filmProject":{"id":"ID","title":"String","description":"Text","synopsis":"Text","budget":"Double","cast":"String","genre":"String","projectType":"Enum","projectType_idx":"Integer","ownerUserId":"ID","studioId":"ID","isPublic":"Boolean","approvalStatus":"Enum","approvalStatus_idx":"Integer","mediaUrls":"String","featured":"Boolean","publishedAt":"Date","accessPolicy":"Enum","accessPolicy_idx":"Integer","director":"String","fundingGoal":"Double","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event filmproject-updated

Event topic : auteurlabb-projectportfolio-service-filmproject-updated

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the filmProject data object itself.

The following JSON included in the payload illustrates the fullest representation of the filmProject object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"filmProject","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"filmProject":{"id":"ID","title":"String","description":"Text","synopsis":"Text","budget":"Double","cast":"String","genre":"String","projectType":"Enum","projectType_idx":"Integer","ownerUserId":"ID","studioId":"ID","isPublic":"Boolean","approvalStatus":"Enum","approvalStatus_idx":"Integer","mediaUrls":"String","featured":"Boolean","publishedAt":"Date","accessPolicy":"Enum","accessPolicy_idx":"Integer","director":"String","fundingGoal":"Double","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"ownerUser":{}}

Route Event accessgrant-created

Event topic : auteurlabb-projectportfolio-service-accessgrant-created

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the accessGrant data object itself.

The following JSON included in the payload illustrates the fullest representation of the accessGrant object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"accessGrant","method":"POST","action":"create","appVersion":"Version","rowCount":1,"accessGrant":{"id":"ID","projectId":"ID","granteeUserId":"ID","grantedByUserId":"ID","status":"Enum","status_idx":"Integer","requestMessage":"Text","dateGranted":"Date","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event accessgrant-updated

Event topic : auteurlabb-projectportfolio-service-accessgrant-updated

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the accessGrant data object itself.

The following JSON included in the payload illustrates the fullest representation of the accessGrant object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"accessGrant","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"accessGrant":{"id":"ID","projectId":"ID","granteeUserId":"ID","grantedByUserId":"ID","status":"Enum","status_idx":"Integer","requestMessage":"Text","dateGranted":"Date","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event bookmark-created

Event topic : auteurlabb-projectportfolio-service-bookmark-created

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the projectBookmark data object itself.

The following JSON included in the payload illustrates the fullest representation of the projectBookmark object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"projectBookmark","method":"POST","action":"create","appVersion":"Version","rowCount":1,"projectBookmark":{"id":"ID","projectId":"ID","userId":"ID","createdAtBookmark":"Date","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true}}

Route Event bookmark-deleted

Event topic : auteurlabb-projectportfolio-service-bookmark-deleted

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the projectBookmark data object itself.

The following JSON included in the payload illustrates the fullest representation of the projectBookmark object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"projectBookmark","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"projectBookmark":{"id":"ID","projectId":"ID","userId":"ID","createdAtBookmark":"Date","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":false}}

Route Event investmentoffer-created

Event topic : auteurlabb-projectportfolio-service-investmentoffer-created

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the investmentOffer data object itself.

The following JSON included in the payload illustrates the fullest representation of the investmentOffer object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"investmentOffer","method":"POST","action":"create","appVersion":"Version","rowCount":1,"investmentOffer":{"id":"ID","projectId":"ID","investorUserId":"ID","offerAmount":"Double","message":"Text","status":"Enum","status_idx":"Integer","respondedAt":"Date","responseNote":"Text","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event toinvestmentoffer-responded

Event topic : auteurlabb-projectportfolio-service-toinvestmentoffer-responded

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the investmentOffer data object itself.

The following JSON included in the payload illustrates the fullest representation of the investmentOffer object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"investmentOffer","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"investmentOffer":{"id":"ID","projectId":"ID","investorUserId":"ID","offerAmount":"Double","message":"Text","status":"Enum","status_idx":"Integer","respondedAt":"Date","responseNote":"Text","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event investmentoffer-withdrawn

Event topic : auteurlabb-projectportfolio-service-investmentoffer-withdrawn

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the investmentOffer data object itself.

The following JSON included in the payload illustrates the fullest representation of the investmentOffer object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"investmentOffer","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"investmentOffer":{"id":"ID","projectId":"ID","investorUserId":"ID","offerAmount":"Double","message":"Text","status":"Enum","status_idx":"Integer","respondedAt":"Date","responseNote":"Text","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event user-followed

Event topic : auteurlabb-projectportfolio-service-user-followed

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the userFollow data object itself.

The following JSON included in the payload illustrates the fullest representation of the userFollow object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"userFollow","method":"POST","action":"create","appVersion":"Version","rowCount":1,"userFollow":{"id":"ID","followerUserId":"ID","followingUserId":"ID","followedAt":"Date","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event user-unfollowed

Event topic : auteurlabb-projectportfolio-service-user-unfollowed

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the userFollow data object itself.

The following JSON included in the payload illustrates the fullest representation of the userFollow object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"userFollow","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"userFollow":{"id":"ID","followerUserId":"ID","followingUserId":"ID","followedAt":"Date","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Index Event projectbookmark-created

Event topic: elastic-index-auteurlabb_projectbookmark-created

Event payload:

{"id":"ID","projectId":"ID","userId":"ID","createdAtBookmark":"Date","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event projectbookmark-updated

Event topic: elastic-index-auteurlabb_projectbookmark-created

Event payload:

{"id":"ID","projectId":"ID","userId":"ID","createdAtBookmark":"Date","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event projectbookmark-deleted

Event topic: elastic-index-auteurlabb_projectbookmark-deleted

Event payload:

{"id":"ID","projectId":"ID","userId":"ID","createdAtBookmark":"Date","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event projectbookmark-extended

Event topic: elastic-index-auteurlabb_projectbookmark-extended

Event payload:

{
  id: id,
  extends: {
    [extendName]: "Object",
    [extendName + "_count"]: "Number",
  },
}

Route Events

Route events are emitted following the successful execution of a route. While most routes perform CRUD (Create, Read, Update, Delete) operations on data objects, resulting in route events that closely resemble database events, there are distinctions worth noting. A single route execution might trigger multiple CRUD actions and ElasticSearch indexing operations. However, for those primarily concerned with the overarching business logic and its outcomes, listening to the consolidated route event, published once at the conclusion of the route’s execution, is more pertinent.

Moreover, routes often deliver aggregated data beyond the primary database object, catering to specific client needs. For instance, creating a data object via a route might not only return the entity’s data but also route-specific metrics, such as the executing user’s permissions related to the entity. Alternatively, a route might automatically generate default child entities following the creation of a parent object. Consequently, the route event encapsulates a unified dataset encompassing both the parent and its children, in contrast to individual events triggered for each entity created. Therefore, subscribing to route events can offer a richer, more contextually relevant set of information aligned with business logic.

The payload of a route event mirrors the REST response JSON of the route, providing a direct and comprehensive reflection of the data and metadata communicated to the client. This ensures that subscribers to route events receive a payload that encapsulates both the primary data involved and any additional information deemed significant at the business level, facilitating a deeper understanding and integration of the service’s functional outcomes.

Route Event filmproject-created

Event topic : auteurlabb-projectportfolio-service-filmproject-created

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the filmProject data object itself.

The following JSON included in the payload illustrates the fullest representation of the filmProject object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"filmProject","method":"POST","action":"create","appVersion":"Version","rowCount":1,"filmProject":{"id":"ID","title":"String","description":"Text","synopsis":"Text","budget":"Double","cast":"String","genre":"String","projectType":"Enum","projectType_idx":"Integer","ownerUserId":"ID","studioId":"ID","isPublic":"Boolean","approvalStatus":"Enum","approvalStatus_idx":"Integer","mediaUrls":"String","featured":"Boolean","publishedAt":"Date","accessPolicy":"Enum","accessPolicy_idx":"Integer","director":"String","fundingGoal":"Double","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event filmproject-updated

Event topic : auteurlabb-projectportfolio-service-filmproject-updated

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the filmProject data object itself.

The following JSON included in the payload illustrates the fullest representation of the filmProject object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"filmProject","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"filmProject":{"id":"ID","title":"String","description":"Text","synopsis":"Text","budget":"Double","cast":"String","genre":"String","projectType":"Enum","projectType_idx":"Integer","ownerUserId":"ID","studioId":"ID","isPublic":"Boolean","approvalStatus":"Enum","approvalStatus_idx":"Integer","mediaUrls":"String","featured":"Boolean","publishedAt":"Date","accessPolicy":"Enum","accessPolicy_idx":"Integer","director":"String","fundingGoal":"Double","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"ownerUser":{}}

Route Event accessgrant-created

Event topic : auteurlabb-projectportfolio-service-accessgrant-created

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the accessGrant data object itself.

The following JSON included in the payload illustrates the fullest representation of the accessGrant object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"accessGrant","method":"POST","action":"create","appVersion":"Version","rowCount":1,"accessGrant":{"id":"ID","projectId":"ID","granteeUserId":"ID","grantedByUserId":"ID","status":"Enum","status_idx":"Integer","requestMessage":"Text","dateGranted":"Date","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event accessgrant-updated

Event topic : auteurlabb-projectportfolio-service-accessgrant-updated

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the accessGrant data object itself.

The following JSON included in the payload illustrates the fullest representation of the accessGrant object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"accessGrant","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"accessGrant":{"id":"ID","projectId":"ID","granteeUserId":"ID","grantedByUserId":"ID","status":"Enum","status_idx":"Integer","requestMessage":"Text","dateGranted":"Date","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event bookmark-created

Event topic : auteurlabb-projectportfolio-service-bookmark-created

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the projectBookmark data object itself.

The following JSON included in the payload illustrates the fullest representation of the projectBookmark object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"projectBookmark","method":"POST","action":"create","appVersion":"Version","rowCount":1,"projectBookmark":{"id":"ID","projectId":"ID","userId":"ID","createdAtBookmark":"Date","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true}}

Route Event bookmark-deleted

Event topic : auteurlabb-projectportfolio-service-bookmark-deleted

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the projectBookmark data object itself.

The following JSON included in the payload illustrates the fullest representation of the projectBookmark object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"projectBookmark","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"projectBookmark":{"id":"ID","projectId":"ID","userId":"ID","createdAtBookmark":"Date","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":false}}

Route Event investmentoffer-created

Event topic : auteurlabb-projectportfolio-service-investmentoffer-created

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the investmentOffer data object itself.

The following JSON included in the payload illustrates the fullest representation of the investmentOffer object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"investmentOffer","method":"POST","action":"create","appVersion":"Version","rowCount":1,"investmentOffer":{"id":"ID","projectId":"ID","investorUserId":"ID","offerAmount":"Double","message":"Text","status":"Enum","status_idx":"Integer","respondedAt":"Date","responseNote":"Text","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event toinvestmentoffer-responded

Event topic : auteurlabb-projectportfolio-service-toinvestmentoffer-responded

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the investmentOffer data object itself.

The following JSON included in the payload illustrates the fullest representation of the investmentOffer object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"investmentOffer","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"investmentOffer":{"id":"ID","projectId":"ID","investorUserId":"ID","offerAmount":"Double","message":"Text","status":"Enum","status_idx":"Integer","respondedAt":"Date","responseNote":"Text","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event investmentoffer-withdrawn

Event topic : auteurlabb-projectportfolio-service-investmentoffer-withdrawn

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the investmentOffer data object itself.

The following JSON included in the payload illustrates the fullest representation of the investmentOffer object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"investmentOffer","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"investmentOffer":{"id":"ID","projectId":"ID","investorUserId":"ID","offerAmount":"Double","message":"Text","status":"Enum","status_idx":"Integer","respondedAt":"Date","responseNote":"Text","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event user-followed

Event topic : auteurlabb-projectportfolio-service-user-followed

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the userFollow data object itself.

The following JSON included in the payload illustrates the fullest representation of the userFollow object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"userFollow","method":"POST","action":"create","appVersion":"Version","rowCount":1,"userFollow":{"id":"ID","followerUserId":"ID","followingUserId":"ID","followedAt":"Date","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event user-unfollowed

Event topic : auteurlabb-projectportfolio-service-user-unfollowed

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the userFollow data object itself.

The following JSON included in the payload illustrates the fullest representation of the userFollow object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"userFollow","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"userFollow":{"id":"ID","followerUserId":"ID","followingUserId":"ID","followedAt":"Date","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Index Event investmentoffer-created

Event topic: elastic-index-auteurlabb_investmentoffer-created

Event payload:

{"id":"ID","projectId":"ID","investorUserId":"ID","offerAmount":"Double","message":"Text","status":"Enum","status_idx":"Integer","respondedAt":"Date","responseNote":"Text","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event investmentoffer-updated

Event topic: elastic-index-auteurlabb_investmentoffer-created

Event payload:

{"id":"ID","projectId":"ID","investorUserId":"ID","offerAmount":"Double","message":"Text","status":"Enum","status_idx":"Integer","respondedAt":"Date","responseNote":"Text","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event investmentoffer-deleted

Event topic: elastic-index-auteurlabb_investmentoffer-deleted

Event payload:

{"id":"ID","projectId":"ID","investorUserId":"ID","offerAmount":"Double","message":"Text","status":"Enum","status_idx":"Integer","respondedAt":"Date","responseNote":"Text","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event investmentoffer-extended

Event topic: elastic-index-auteurlabb_investmentoffer-extended

Event payload:

{
  id: id,
  extends: {
    [extendName]: "Object",
    [extendName + "_count"]: "Number",
  },
}

Route Events

Route events are emitted following the successful execution of a route. While most routes perform CRUD (Create, Read, Update, Delete) operations on data objects, resulting in route events that closely resemble database events, there are distinctions worth noting. A single route execution might trigger multiple CRUD actions and ElasticSearch indexing operations. However, for those primarily concerned with the overarching business logic and its outcomes, listening to the consolidated route event, published once at the conclusion of the route’s execution, is more pertinent.

Moreover, routes often deliver aggregated data beyond the primary database object, catering to specific client needs. For instance, creating a data object via a route might not only return the entity’s data but also route-specific metrics, such as the executing user’s permissions related to the entity. Alternatively, a route might automatically generate default child entities following the creation of a parent object. Consequently, the route event encapsulates a unified dataset encompassing both the parent and its children, in contrast to individual events triggered for each entity created. Therefore, subscribing to route events can offer a richer, more contextually relevant set of information aligned with business logic.

The payload of a route event mirrors the REST response JSON of the route, providing a direct and comprehensive reflection of the data and metadata communicated to the client. This ensures that subscribers to route events receive a payload that encapsulates both the primary data involved and any additional information deemed significant at the business level, facilitating a deeper understanding and integration of the service’s functional outcomes.

Route Event filmproject-created

Event topic : auteurlabb-projectportfolio-service-filmproject-created

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the filmProject data object itself.

The following JSON included in the payload illustrates the fullest representation of the filmProject object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"filmProject","method":"POST","action":"create","appVersion":"Version","rowCount":1,"filmProject":{"id":"ID","title":"String","description":"Text","synopsis":"Text","budget":"Double","cast":"String","genre":"String","projectType":"Enum","projectType_idx":"Integer","ownerUserId":"ID","studioId":"ID","isPublic":"Boolean","approvalStatus":"Enum","approvalStatus_idx":"Integer","mediaUrls":"String","featured":"Boolean","publishedAt":"Date","accessPolicy":"Enum","accessPolicy_idx":"Integer","director":"String","fundingGoal":"Double","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event filmproject-updated

Event topic : auteurlabb-projectportfolio-service-filmproject-updated

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the filmProject data object itself.

The following JSON included in the payload illustrates the fullest representation of the filmProject object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"filmProject","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"filmProject":{"id":"ID","title":"String","description":"Text","synopsis":"Text","budget":"Double","cast":"String","genre":"String","projectType":"Enum","projectType_idx":"Integer","ownerUserId":"ID","studioId":"ID","isPublic":"Boolean","approvalStatus":"Enum","approvalStatus_idx":"Integer","mediaUrls":"String","featured":"Boolean","publishedAt":"Date","accessPolicy":"Enum","accessPolicy_idx":"Integer","director":"String","fundingGoal":"Double","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"ownerUser":{}}

Route Event accessgrant-created

Event topic : auteurlabb-projectportfolio-service-accessgrant-created

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the accessGrant data object itself.

The following JSON included in the payload illustrates the fullest representation of the accessGrant object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"accessGrant","method":"POST","action":"create","appVersion":"Version","rowCount":1,"accessGrant":{"id":"ID","projectId":"ID","granteeUserId":"ID","grantedByUserId":"ID","status":"Enum","status_idx":"Integer","requestMessage":"Text","dateGranted":"Date","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event accessgrant-updated

Event topic : auteurlabb-projectportfolio-service-accessgrant-updated

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the accessGrant data object itself.

The following JSON included in the payload illustrates the fullest representation of the accessGrant object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"accessGrant","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"accessGrant":{"id":"ID","projectId":"ID","granteeUserId":"ID","grantedByUserId":"ID","status":"Enum","status_idx":"Integer","requestMessage":"Text","dateGranted":"Date","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event bookmark-created

Event topic : auteurlabb-projectportfolio-service-bookmark-created

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the projectBookmark data object itself.

The following JSON included in the payload illustrates the fullest representation of the projectBookmark object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"projectBookmark","method":"POST","action":"create","appVersion":"Version","rowCount":1,"projectBookmark":{"id":"ID","projectId":"ID","userId":"ID","createdAtBookmark":"Date","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true}}

Route Event bookmark-deleted

Event topic : auteurlabb-projectportfolio-service-bookmark-deleted

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the projectBookmark data object itself.

The following JSON included in the payload illustrates the fullest representation of the projectBookmark object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"projectBookmark","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"projectBookmark":{"id":"ID","projectId":"ID","userId":"ID","createdAtBookmark":"Date","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":false}}

Route Event investmentoffer-created

Event topic : auteurlabb-projectportfolio-service-investmentoffer-created

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the investmentOffer data object itself.

The following JSON included in the payload illustrates the fullest representation of the investmentOffer object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"investmentOffer","method":"POST","action":"create","appVersion":"Version","rowCount":1,"investmentOffer":{"id":"ID","projectId":"ID","investorUserId":"ID","offerAmount":"Double","message":"Text","status":"Enum","status_idx":"Integer","respondedAt":"Date","responseNote":"Text","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event toinvestmentoffer-responded

Event topic : auteurlabb-projectportfolio-service-toinvestmentoffer-responded

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the investmentOffer data object itself.

The following JSON included in the payload illustrates the fullest representation of the investmentOffer object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"investmentOffer","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"investmentOffer":{"id":"ID","projectId":"ID","investorUserId":"ID","offerAmount":"Double","message":"Text","status":"Enum","status_idx":"Integer","respondedAt":"Date","responseNote":"Text","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event investmentoffer-withdrawn

Event topic : auteurlabb-projectportfolio-service-investmentoffer-withdrawn

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the investmentOffer data object itself.

The following JSON included in the payload illustrates the fullest representation of the investmentOffer object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"investmentOffer","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"investmentOffer":{"id":"ID","projectId":"ID","investorUserId":"ID","offerAmount":"Double","message":"Text","status":"Enum","status_idx":"Integer","respondedAt":"Date","responseNote":"Text","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event user-followed

Event topic : auteurlabb-projectportfolio-service-user-followed

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the userFollow data object itself.

The following JSON included in the payload illustrates the fullest representation of the userFollow object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"userFollow","method":"POST","action":"create","appVersion":"Version","rowCount":1,"userFollow":{"id":"ID","followerUserId":"ID","followingUserId":"ID","followedAt":"Date","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event user-unfollowed

Event topic : auteurlabb-projectportfolio-service-user-unfollowed

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the userFollow data object itself.

The following JSON included in the payload illustrates the fullest representation of the userFollow object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"userFollow","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"userFollow":{"id":"ID","followerUserId":"ID","followingUserId":"ID","followedAt":"Date","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Index Event userfollow-created

Event topic: elastic-index-auteurlabb_userfollow-created

Event payload:

{"id":"ID","followerUserId":"ID","followingUserId":"ID","followedAt":"Date","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event userfollow-updated

Event topic: elastic-index-auteurlabb_userfollow-created

Event payload:

{"id":"ID","followerUserId":"ID","followingUserId":"ID","followedAt":"Date","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event userfollow-deleted

Event topic: elastic-index-auteurlabb_userfollow-deleted

Event payload:

{"id":"ID","followerUserId":"ID","followingUserId":"ID","followedAt":"Date","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event userfollow-extended

Event topic: elastic-index-auteurlabb_userfollow-extended

Event payload:

{
  id: id,
  extends: {
    [extendName]: "Object",
    [extendName + "_count"]: "Number",
  },
}

Route Events

Route events are emitted following the successful execution of a route. While most routes perform CRUD (Create, Read, Update, Delete) operations on data objects, resulting in route events that closely resemble database events, there are distinctions worth noting. A single route execution might trigger multiple CRUD actions and ElasticSearch indexing operations. However, for those primarily concerned with the overarching business logic and its outcomes, listening to the consolidated route event, published once at the conclusion of the route’s execution, is more pertinent.

Moreover, routes often deliver aggregated data beyond the primary database object, catering to specific client needs. For instance, creating a data object via a route might not only return the entity’s data but also route-specific metrics, such as the executing user’s permissions related to the entity. Alternatively, a route might automatically generate default child entities following the creation of a parent object. Consequently, the route event encapsulates a unified dataset encompassing both the parent and its children, in contrast to individual events triggered for each entity created. Therefore, subscribing to route events can offer a richer, more contextually relevant set of information aligned with business logic.

The payload of a route event mirrors the REST response JSON of the route, providing a direct and comprehensive reflection of the data and metadata communicated to the client. This ensures that subscribers to route events receive a payload that encapsulates both the primary data involved and any additional information deemed significant at the business level, facilitating a deeper understanding and integration of the service’s functional outcomes.

Route Event filmproject-created

Event topic : auteurlabb-projectportfolio-service-filmproject-created

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the filmProject data object itself.

The following JSON included in the payload illustrates the fullest representation of the filmProject object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"filmProject","method":"POST","action":"create","appVersion":"Version","rowCount":1,"filmProject":{"id":"ID","title":"String","description":"Text","synopsis":"Text","budget":"Double","cast":"String","genre":"String","projectType":"Enum","projectType_idx":"Integer","ownerUserId":"ID","studioId":"ID","isPublic":"Boolean","approvalStatus":"Enum","approvalStatus_idx":"Integer","mediaUrls":"String","featured":"Boolean","publishedAt":"Date","accessPolicy":"Enum","accessPolicy_idx":"Integer","director":"String","fundingGoal":"Double","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event filmproject-updated

Event topic : auteurlabb-projectportfolio-service-filmproject-updated

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the filmProject data object itself.

The following JSON included in the payload illustrates the fullest representation of the filmProject object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"filmProject","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"filmProject":{"id":"ID","title":"String","description":"Text","synopsis":"Text","budget":"Double","cast":"String","genre":"String","projectType":"Enum","projectType_idx":"Integer","ownerUserId":"ID","studioId":"ID","isPublic":"Boolean","approvalStatus":"Enum","approvalStatus_idx":"Integer","mediaUrls":"String","featured":"Boolean","publishedAt":"Date","accessPolicy":"Enum","accessPolicy_idx":"Integer","director":"String","fundingGoal":"Double","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"ownerUser":{}}

Route Event accessgrant-created

Event topic : auteurlabb-projectportfolio-service-accessgrant-created

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the accessGrant data object itself.

The following JSON included in the payload illustrates the fullest representation of the accessGrant object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"accessGrant","method":"POST","action":"create","appVersion":"Version","rowCount":1,"accessGrant":{"id":"ID","projectId":"ID","granteeUserId":"ID","grantedByUserId":"ID","status":"Enum","status_idx":"Integer","requestMessage":"Text","dateGranted":"Date","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event accessgrant-updated

Event topic : auteurlabb-projectportfolio-service-accessgrant-updated

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the accessGrant data object itself.

The following JSON included in the payload illustrates the fullest representation of the accessGrant object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"accessGrant","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"accessGrant":{"id":"ID","projectId":"ID","granteeUserId":"ID","grantedByUserId":"ID","status":"Enum","status_idx":"Integer","requestMessage":"Text","dateGranted":"Date","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event bookmark-created

Event topic : auteurlabb-projectportfolio-service-bookmark-created

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the projectBookmark data object itself.

The following JSON included in the payload illustrates the fullest representation of the projectBookmark object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"projectBookmark","method":"POST","action":"create","appVersion":"Version","rowCount":1,"projectBookmark":{"id":"ID","projectId":"ID","userId":"ID","createdAtBookmark":"Date","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true}}

Route Event bookmark-deleted

Event topic : auteurlabb-projectportfolio-service-bookmark-deleted

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the projectBookmark data object itself.

The following JSON included in the payload illustrates the fullest representation of the projectBookmark object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"projectBookmark","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"projectBookmark":{"id":"ID","projectId":"ID","userId":"ID","createdAtBookmark":"Date","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":false}}

Route Event investmentoffer-created

Event topic : auteurlabb-projectportfolio-service-investmentoffer-created

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the investmentOffer data object itself.

The following JSON included in the payload illustrates the fullest representation of the investmentOffer object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"investmentOffer","method":"POST","action":"create","appVersion":"Version","rowCount":1,"investmentOffer":{"id":"ID","projectId":"ID","investorUserId":"ID","offerAmount":"Double","message":"Text","status":"Enum","status_idx":"Integer","respondedAt":"Date","responseNote":"Text","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event toinvestmentoffer-responded

Event topic : auteurlabb-projectportfolio-service-toinvestmentoffer-responded

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the investmentOffer data object itself.

The following JSON included in the payload illustrates the fullest representation of the investmentOffer object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"investmentOffer","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"investmentOffer":{"id":"ID","projectId":"ID","investorUserId":"ID","offerAmount":"Double","message":"Text","status":"Enum","status_idx":"Integer","respondedAt":"Date","responseNote":"Text","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event investmentoffer-withdrawn

Event topic : auteurlabb-projectportfolio-service-investmentoffer-withdrawn

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the investmentOffer data object itself.

The following JSON included in the payload illustrates the fullest representation of the investmentOffer object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"investmentOffer","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"investmentOffer":{"id":"ID","projectId":"ID","investorUserId":"ID","offerAmount":"Double","message":"Text","status":"Enum","status_idx":"Integer","respondedAt":"Date","responseNote":"Text","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event user-followed

Event topic : auteurlabb-projectportfolio-service-user-followed

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the userFollow data object itself.

The following JSON included in the payload illustrates the fullest representation of the userFollow object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"userFollow","method":"POST","action":"create","appVersion":"Version","rowCount":1,"userFollow":{"id":"ID","followerUserId":"ID","followingUserId":"ID","followedAt":"Date","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event user-unfollowed

Event topic : auteurlabb-projectportfolio-service-user-unfollowed

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the userFollow data object itself.

The following JSON included in the payload illustrates the fullest representation of the userFollow object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"userFollow","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"userFollow":{"id":"ID","followerUserId":"ID","followingUserId":"ID","followedAt":"Date","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Copyright

All sources, documents and other digital materials are copyright of .

About Us

For more information please visit our website: .

. .


Data Objects

Service Design Specification - Object Design for filmProject

Service Design Specification - Object Design for filmProject

auteurlabb-projectportfolio-service documentation

Document Overview

This document outlines the object design for the filmProject model in our application. It includes details about the model’s attributes, relationships, and any specific validation or business logic that applies.

filmProject Data Object

Object Overview

Description: A film project submitted by a filmmaker or studio with all required metadata, visibility, and lifecycle status.

This object represents a core data structure within the service and acts as the blueprint for database interaction, API generation, and business logic enforcement. It is defined using the ObjectSettings pattern, which governs its behavior, access control, caching strategy, and integration points with other systems such as Stripe and Redis.

Core Configuration

Composite Indexes

The index also defines a conflict resolution strategy for duplicate key violations.

When a new record would violate this composite index, the following action will be taken:

On Duplicate: throwError

An error will be thrown, preventing the insertion of conflicting data.

Properties Schema

Display Label Property: title — This property is the default display label for records of this data object. Relation dropdowns and record references in the frontend will show the value of this property as the human-readable label.

Property Type Required Description
title String Yes Project title, unique per owner
description Text Yes Project description (for details page/fulltext search)
synopsis Text No Short synopsis or tagline
budget Double Yes Estimated budget (USD)
cast String No List of major cast members (names)
genre String No Project genres/tags
projectType Enum Yes Origin: filmmaker or studio
ownerUserId ID Yes User ID of project owner (filmmaker/studio admin)
studioId ID No (Optional) User ID of the studio (for studio projects)
isPublic Boolean Yes Project public visibility flag
approvalStatus Enum Yes Project approval/publication workflow status
mediaUrls String No Project demo reel/trailer/cover media URLs
featured Boolean No Platform feature flag (for promoted projects)
publishedAt Date No Publication date
accessPolicy Enum Yes Access policy (open: any authorized user, restricted: need grant)
director String No Director of the film project
fundingGoal Double No Funding goal amount (USD)

Array Properties

cast genre mediaUrls

Array properties can hold multiple values and are indicated by the [] suffix in their type. Avoid using arrays in properties that are used for relations, as they will not work correctly. Note that using connection objects instead of arrays is recommended for relations, as they provide better performance and flexibility.

Default Values

Default values are automatically assigned to properties when a new object is created, if no value is provided in the request body. Since default values are applied on db level, they should be literal values, not expressions.If you want to use expressions, you can use transposed parameters in any business API to set default values dynamically.

Always Create with Default Values

Some of the default values are set to be always used when creating a new object, even if the property value is provided in the request body. It ensures that the property is always initialized with a default value when the object is created.

Constant Properties

projectType ownerUserId studioId

Constant properties are defined to be immutable after creation, meaning they cannot be updated or changed once set. They are typically used for properties that should remain constant throughout the object’s lifecycle. A property is set to be constant if the Allow Update option is set to false.

Auto Update Properties

title description synopsis budget cast genre isPublic approvalStatus mediaUrls featured publishedAt accessPolicy director fundingGoal

An update crud API created with the option Auto Params enabled will automatically update these properties with the provided values in the request body. If you want to update any property in your own business logic not by user input, you can set the Allow Auto Update option to false. These properties will be added to the update API’s body parameters and can be updated by the user if any value is provided in the request body.

Enum Properties

Enum properties are defined with a set of allowed values, ensuring that only valid options can be assigned to them. The enum options value will be stored as strings in the database, but when a data object is created an addtional property with the same name plus an idx suffix will be created, which will hold the index of the selected enum option. You can use the index property to sort by the enum value or when your enum options represent a sequence of values.

Elastic Search Indexing

title description synopsis budget cast genre projectType ownerUserId studioId isPublic approvalStatus mediaUrls featured publishedAt accessPolicy director fundingGoal

Properties that are indexed in Elastic Search will be searchable via the Elastic Search API. While all properties are stored in the elastic search index of the data object, only those marked for Elastic Search indexing will be available for search queries.

Database Indexing

title budget projectType ownerUserId studioId isPublic approvalStatus featured publishedAt accessPolicy fundingGoal

Properties that are indexed in the database will be optimized for query performance, allowing for faster data retrieval. Make a property indexed in the database if you want to use it frequently in query filters or sorting.

Secondary Key Properties

ownerUserId

Secondary key properties are used to create an additional indexed identifiers for the data object, allowing for alternative access patterns. Different than normal indexed properties, secondary keys will act as primary keys and Mindbricks will provide automatic secondary key db utility functions to access the data object by the secondary key.

Relation Properties

ownerUserId studioId

Mindbricks supports relations between data objects, allowing you to define how objects are linked together. You can define relations in the data object properties, which will be used to create foreign key constraints in the database. For complex joins operations, Mindbricks supportsa BFF pattern, where you can view dynamic and static views based on Elastic Search Indexes. Use db level relations for simple one-to-one or one-to-many relationships, and use BFF views for complex joins that require multiple data objects to be joined together.

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

On Delete: Set Null Required: Yes

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

On Delete: Set Null Required: No

Session Data Properties

ownerUserId

Session data properties are used to store data that is specific to the user session, allowing for personalized experiences and temporary data storage. If a property is configured as session data, it will be automatically mapped to the related field in the user session during CRUD operations. Note that session data properties can not be mutated by the user, but only by the system.

This property is also used to store the owner of the session data, allowing for ownership checks and access control.

Filter Properties

title description synopsis budget genre projectType isPublic approvalStatus featured accessPolicy director fundingGoal

Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API’s that have “Auto Params” enabled.


Service Design Specification - Object Design for accessGrant

Service Design Specification - Object Design for accessGrant

auteurlabb-projectportfolio-service documentation

Document Overview

This document outlines the object design for the accessGrant model in our application. It includes details about the model’s attributes, relationships, and any specific validation or business logic that applies.

accessGrant Data Object

Object Overview

Description: Access grants to private projects, allowing selected users to view restricted projects (requested/granted/revoked/denied).

This object represents a core data structure within the service and acts as the blueprint for database interaction, API generation, and business logic enforcement. It is defined using the ObjectSettings pattern, which governs its behavior, access control, caching strategy, and integration points with other systems such as Stripe and Redis.

Core Configuration

Composite Indexes

The index also defines a conflict resolution strategy for duplicate key violations.

When a new record would violate this composite index, the following action will be taken:

On Duplicate: throwError

An error will be thrown, preventing the insertion of conflicting data.

Properties Schema

Property Type Required Description
projectId ID Yes Film project ID for which access is granted/requested
granteeUserId ID Yes ID of user being granted/requesting access
grantedByUserId ID No Who granted/revoked the access (or null for self-request)
status Enum Yes requested (pending); granted (success); revoked; denied
requestMessage Text No Message from requester (for context)
dateGranted Date No Timestamp when access status last updated

Default Values

Default values are automatically assigned to properties when a new object is created, if no value is provided in the request body. Since default values are applied on db level, they should be literal values, not expressions.If you want to use expressions, you can use transposed parameters in any business API to set default values dynamically.

Constant Properties

projectId granteeUserId grantedByUserId

Constant properties are defined to be immutable after creation, meaning they cannot be updated or changed once set. They are typically used for properties that should remain constant throughout the object’s lifecycle. A property is set to be constant if the Allow Update option is set to false.

Auto Update Properties

status requestMessage dateGranted

An update crud API created with the option Auto Params enabled will automatically update these properties with the provided values in the request body. If you want to update any property in your own business logic not by user input, you can set the Allow Auto Update option to false. These properties will be added to the update API’s body parameters and can be updated by the user if any value is provided in the request body.

Enum Properties

Enum properties are defined with a set of allowed values, ensuring that only valid options can be assigned to them. The enum options value will be stored as strings in the database, but when a data object is created an addtional property with the same name plus an idx suffix will be created, which will hold the index of the selected enum option. You can use the index property to sort by the enum value or when your enum options represent a sequence of values.

Elastic Search Indexing

projectId granteeUserId grantedByUserId status dateGranted

Properties that are indexed in Elastic Search will be searchable via the Elastic Search API. While all properties are stored in the elastic search index of the data object, only those marked for Elastic Search indexing will be available for search queries.

Database Indexing

projectId granteeUserId grantedByUserId status dateGranted

Properties that are indexed in the database will be optimized for query performance, allowing for faster data retrieval. Make a property indexed in the database if you want to use it frequently in query filters or sorting.

Secondary Key Properties

projectId granteeUserId

Secondary key properties are used to create an additional indexed identifiers for the data object, allowing for alternative access patterns. Different than normal indexed properties, secondary keys will act as primary keys and Mindbricks will provide automatic secondary key db utility functions to access the data object by the secondary key.

Relation Properties

projectId granteeUserId grantedByUserId

Mindbricks supports relations between data objects, allowing you to define how objects are linked together. You can define relations in the data object properties, which will be used to create foreign key constraints in the database. For complex joins operations, Mindbricks supportsa BFF pattern, where you can view dynamic and static views based on Elastic Search Indexes. Use db level relations for simple one-to-one or one-to-many relationships, and use BFF views for complex joins that require multiple data objects to be joined together.

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

On Delete: Set Null Required: Yes

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

On Delete: Set Null Required: Yes

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

On Delete: Set Null Required: No

Filter Properties

projectId granteeUserId status

Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API’s that have “Auto Params” enabled.


Service Design Specification - Object Design for projectBookmark

Service Design Specification - Object Design for projectBookmark

auteurlabb-projectportfolio-service documentation

Document Overview

This document outlines the object design for the projectBookmark model in our application. It includes details about the model’s attributes, relationships, and any specific validation or business logic that applies.

projectBookmark Data Object

Object Overview

Description: User bookmarks/follows for projects. Each bookmark is per user+project.

This object represents a core data structure within the service and acts as the blueprint for database interaction, API generation, and business logic enforcement. It is defined using the ObjectSettings pattern, which governs its behavior, access control, caching strategy, and integration points with other systems such as Stripe and Redis.

Core Configuration

Composite Indexes

The index also defines a conflict resolution strategy for duplicate key violations.

When a new record would violate this composite index, the following action will be taken:

On Duplicate: throwError

An error will be thrown, preventing the insertion of conflicting data.

Properties Schema

Property Type Required Description
projectId ID Yes The project being bookmarked
userId ID Yes The user who bookmarked this project
createdAtBookmark Date No When bookmark was made

Default Values

Default values are automatically assigned to properties when a new object is created, if no value is provided in the request body. Since default values are applied on db level, they should be literal values, not expressions.If you want to use expressions, you can use transposed parameters in any business API to set default values dynamically.

Constant Properties

projectId userId createdAtBookmark

Constant properties are defined to be immutable after creation, meaning they cannot be updated or changed once set. They are typically used for properties that should remain constant throughout the object’s lifecycle. A property is set to be constant if the Allow Update option is set to false.

Elastic Search Indexing

projectId userId createdAtBookmark

Properties that are indexed in Elastic Search will be searchable via the Elastic Search API. While all properties are stored in the elastic search index of the data object, only those marked for Elastic Search indexing will be available for search queries.

Database Indexing

projectId userId createdAtBookmark

Properties that are indexed in the database will be optimized for query performance, allowing for faster data retrieval. Make a property indexed in the database if you want to use it frequently in query filters or sorting.

Secondary Key Properties

projectId userId

Secondary key properties are used to create an additional indexed identifiers for the data object, allowing for alternative access patterns. Different than normal indexed properties, secondary keys will act as primary keys and Mindbricks will provide automatic secondary key db utility functions to access the data object by the secondary key.

Relation Properties

projectId userId

Mindbricks supports relations between data objects, allowing you to define how objects are linked together. You can define relations in the data object properties, which will be used to create foreign key constraints in the database. For complex joins operations, Mindbricks supportsa BFF pattern, where you can view dynamic and static views based on Elastic Search Indexes. Use db level relations for simple one-to-one or one-to-many relationships, and use BFF views for complex joins that require multiple data objects to be joined together.

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

On Delete: Set Null Required: Yes

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

On Delete: Set Null Required: Yes

Session Data Properties

userId

Session data properties are used to store data that is specific to the user session, allowing for personalized experiences and temporary data storage. If a property is configured as session data, it will be automatically mapped to the related field in the user session during CRUD operations. Note that session data properties can not be mutated by the user, but only by the system.

This property is also used to store the owner of the session data, allowing for ownership checks and access control.

Context Data Properties

createdAtBookmark

Context data properties are used to store data that is specific to the request context, allowing for dynamic data retrieval based on the current request. If a property is configured as context data, it will be automatically mapped to the related field in the request context during CRUD operations.

Formula Properties

createdAtBookmark

Formula properties are used to define calculated fields that derive their values from other properties or external data. These properties are automatically calculated based on the defined formula and can be used for dynamic data retrieval.

Filter Properties

projectId userId

Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API’s that have “Auto Params” enabled.


Service Design Specification - Object Design for investmentOffer

Service Design Specification - Object Design for investmentOffer

auteurlabb-projectportfolio-service documentation

Document Overview

This document outlines the object design for the investmentOffer model in our application. It includes details about the model’s attributes, relationships, and any specific validation or business logic that applies.

investmentOffer Data Object

Object Overview

Description: Tracks investment offers from investors to film projects. Each offer has an amount, optional message, and status workflow (pending/accepted/rejected/withdrawn).

This object represents a core data structure within the service and acts as the blueprint for database interaction, API generation, and business logic enforcement. It is defined using the ObjectSettings pattern, which governs its behavior, access control, caching strategy, and integration points with other systems such as Stripe and Redis.

Core Configuration

Composite Indexes

The index also defines a conflict resolution strategy for duplicate key violations.

When a new record would violate this composite index, the following action will be taken:

On Duplicate: throwError

An error will be thrown, preventing the insertion of conflicting data.

Properties Schema

Property Type Required Description
projectId ID Yes Film project receiving the investment offer
investorUserId ID Yes Investor who made the offer
offerAmount Double Yes Investment amount in USD
message Text No Cover letter or terms from the investor
status Enum No Offer lifecycle status
respondedAt Date No When the project owner responded
responseNote Text No Project owner note on accept/reject

Default Values

Default values are automatically assigned to properties when a new object is created, if no value is provided in the request body. Since default values are applied on db level, they should be literal values, not expressions.If you want to use expressions, you can use transposed parameters in any business API to set default values dynamically.

Always Create with Default Values

Some of the default values are set to be always used when creating a new object, even if the property value is provided in the request body. It ensures that the property is always initialized with a default value when the object is created.

Constant Properties

projectId investorUserId

Constant properties are defined to be immutable after creation, meaning they cannot be updated or changed once set. They are typically used for properties that should remain constant throughout the object’s lifecycle. A property is set to be constant if the Allow Update option is set to false.

Auto Update Properties

offerAmount message status respondedAt responseNote

An update crud API created with the option Auto Params enabled will automatically update these properties with the provided values in the request body. If you want to update any property in your own business logic not by user input, you can set the Allow Auto Update option to false. These properties will be added to the update API’s body parameters and can be updated by the user if any value is provided in the request body.

Enum Properties

Enum properties are defined with a set of allowed values, ensuring that only valid options can be assigned to them. The enum options value will be stored as strings in the database, but when a data object is created an addtional property with the same name plus an idx suffix will be created, which will hold the index of the selected enum option. You can use the index property to sort by the enum value or when your enum options represent a sequence of values.

Elastic Search Indexing

projectId investorUserId offerAmount status

Properties that are indexed in Elastic Search will be searchable via the Elastic Search API. While all properties are stored in the elastic search index of the data object, only those marked for Elastic Search indexing will be available for search queries.

Database Indexing

projectId investorUserId offerAmount status

Properties that are indexed in the database will be optimized for query performance, allowing for faster data retrieval. Make a property indexed in the database if you want to use it frequently in query filters or sorting.

Secondary Key Properties

projectId investorUserId

Secondary key properties are used to create an additional indexed identifiers for the data object, allowing for alternative access patterns. Different than normal indexed properties, secondary keys will act as primary keys and Mindbricks will provide automatic secondary key db utility functions to access the data object by the secondary key.

Relation Properties

projectId investorUserId

Mindbricks supports relations between data objects, allowing you to define how objects are linked together. You can define relations in the data object properties, which will be used to create foreign key constraints in the database. For complex joins operations, Mindbricks supportsa BFF pattern, where you can view dynamic and static views based on Elastic Search Indexes. Use db level relations for simple one-to-one or one-to-many relationships, and use BFF views for complex joins that require multiple data objects to be joined together.

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

On Delete: Set Null Required: Yes

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

On Delete: Set Null Required: Yes

Session Data Properties

investorUserId

Session data properties are used to store data that is specific to the user session, allowing for personalized experiences and temporary data storage. If a property is configured as session data, it will be automatically mapped to the related field in the user session during CRUD operations. Note that session data properties can not be mutated by the user, but only by the system.

This property is also used to store the owner of the session data, allowing for ownership checks and access control.

Filter Properties

projectId investorUserId offerAmount status

Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API’s that have “Auto Params” enabled.


Service Design Specification - Object Design for userFollow

Service Design Specification - Object Design for userFollow

auteurlabb-projectportfolio-service documentation

Document Overview

This document outlines the object design for the userFollow model in our application. It includes details about the model’s attributes, relationships, and any specific validation or business logic that applies.

userFollow Data Object

Object Overview

Description: Tracks user-to-user follow relationships. A follower follows a target user (filmmaker, studio, investor).

This object represents a core data structure within the service and acts as the blueprint for database interaction, API generation, and business logic enforcement. It is defined using the ObjectSettings pattern, which governs its behavior, access control, caching strategy, and integration points with other systems such as Stripe and Redis.

Core Configuration

Composite Indexes

The index also defines a conflict resolution strategy for duplicate key violations.

When a new record would violate this composite index, the following action will be taken:

On Duplicate: throwError

An error will be thrown, preventing the insertion of conflicting data.

Properties Schema

Property Type Required Description
followerUserId ID Yes The user who is following
followingUserId ID Yes The user being followed
followedAt Date No When the follow relationship was created

Default Values

Default values are automatically assigned to properties when a new object is created, if no value is provided in the request body. Since default values are applied on db level, they should be literal values, not expressions.If you want to use expressions, you can use transposed parameters in any business API to set default values dynamically.

Constant Properties

followerUserId followingUserId followedAt

Constant properties are defined to be immutable after creation, meaning they cannot be updated or changed once set. They are typically used for properties that should remain constant throughout the object’s lifecycle. A property is set to be constant if the Allow Update option is set to false.

Elastic Search Indexing

followerUserId followingUserId followedAt

Properties that are indexed in Elastic Search will be searchable via the Elastic Search API. While all properties are stored in the elastic search index of the data object, only those marked for Elastic Search indexing will be available for search queries.

Database Indexing

followerUserId followingUserId followedAt

Properties that are indexed in the database will be optimized for query performance, allowing for faster data retrieval. Make a property indexed in the database if you want to use it frequently in query filters or sorting.

Secondary Key Properties

followerUserId followingUserId

Secondary key properties are used to create an additional indexed identifiers for the data object, allowing for alternative access patterns. Different than normal indexed properties, secondary keys will act as primary keys and Mindbricks will provide automatic secondary key db utility functions to access the data object by the secondary key.

Relation Properties

followerUserId followingUserId

Mindbricks supports relations between data objects, allowing you to define how objects are linked together. You can define relations in the data object properties, which will be used to create foreign key constraints in the database. For complex joins operations, Mindbricks supportsa BFF pattern, where you can view dynamic and static views based on Elastic Search Indexes. Use db level relations for simple one-to-one or one-to-many relationships, and use BFF views for complex joins that require multiple data objects to be joined together.

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

On Delete: Set Null Required: Yes

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

On Delete: Set Null Required: Yes

Session Data Properties

followerUserId

Session data properties are used to store data that is specific to the user session, allowing for personalized experiences and temporary data storage. If a property is configured as session data, it will be automatically mapped to the related field in the user session during CRUD operations. Note that session data properties can not be mutated by the user, but only by the system.

This property is also used to store the owner of the session data, allowing for ownership checks and access control.

Filter Properties

followerUserId followingUserId

Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API’s that have “Auto Params” enabled.


Business APIs

Business API Design Specification - Create Filmproject

Business API Design Specification - Create Filmproject

A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic.

While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized.

This document provides an in-depth explanation of the architectural design of the createFilmProject Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side.

Main Data Object and CRUD Operation

The createFilmProject Business API is designed to handle a create operation on the FilmProject data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

Submit a new film project (by filmmaker/studio). Sets approvalStatus=pending and assigns ownerUserId from session. Studio projects require studioId.

API Frontend Description By The Backend Architect

Used by filmmakers/studios to submit a new project. Standard create form. Approval workflow starts automatically. Owner assigned from session.

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The createFilmProject Business API includes a REST controller that can be triggered via the following route:

/v1/filmprojects

By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the Parameters section.

MCP Tool

REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This createFilmProject Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The createFilmProject Business API has 17 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client.

Business API parameters can be:

Regular Parameters

Name Type Required Default Location Data Path
filmProjectId ID No - body filmProjectId
Description: This id paremeter is used to create the data object with a given specific id. Leave null for automatic id.
title String Yes - body title
Description: Project title, unique per owner
description Text Yes - body description
Description: Project description (for details page/fulltext search)
synopsis Text No - body synopsis
Description: Short synopsis or tagline
budget Double Yes - body budget
Description: Estimated budget (USD)
cast String No - body cast
Description: List of major cast members (names)
genre String No - body genre
Description: Project genres/tags
projectType Enum Yes - body projectType
Description: Origin: filmmaker or studio
ownerUserId ID Yes - session userId
Description: User ID of project owner (filmmaker/studio admin)
studioId ID No - body studioId
Description: (Optional) User ID of the studio (for studio projects)
isPublic Boolean Yes - body isPublic
Description: Project public visibility flag
mediaUrls String No - body mediaUrls
Description: Project demo reel/trailer/cover media URLs
featured Boolean No - body featured
Description: Platform feature flag (for promoted projects)
publishedAt Date No - body publishedAt
Description: Publication date
accessPolicy Enum Yes - body accessPolicy
Description: Access policy (open: any authorized user, restricted: need grant)
director String No - body director
Description: Director of the film project
fundingGoal Double No - body fundingGoal
Description: Funding goal amount (USD)

Parameter Transformations

Some parameters are post-processed using transform scripts after being read from the request but before validation or workflow execution. Only parameters with a transform script are listed below.

No parameters are transformed in this API.

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the createFilmProject Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Data Clause

Defines custom field-value assignments used to modify or augment the default payload for create and update operations. These settings override values derived from the session or parameters if explicitly provided.", Note that a default data clause is always prepared by Mindbricks using data property settings, however any property in the data clause can be override by Data Clause Settings.

Custom Data Clause Override

{
    approvalStatus: runMScript(() => ("pending"), {"path":"services[1].businessLogic[0].dataClause.customData[0].value"}),
    ownerUserId: runMScript(() => (this.session.userId), {"path":"services[1].businessLogic[0].dataClause.customData[1].value"}),
    projectType: runMScript(() => (this.session.roleId == 'studio' ? 'studio' : 'filmmaker'), {"path":"services[1].businessLogic[0].dataClause.customData[2].value"}),
   
}

Actual Data Clause

The business api will use the following data clause. Note that any calculated value will be added to the data clause in the api manager.

{
  id: this.filmProjectId,
  title: this.title,
  description: this.description,
  synopsis: this.synopsis,
  budget: this.budget,
  cast: this.cast,
  genre: this.genre,
  projectType: runMScript(() => (this.session.roleId == 'studio' ? 'studio' : 'filmmaker'), {"path":"services[1].businessLogic[0].dataClause.customData[2].value"}),
  ownerUserId: runMScript(() => (this.session.userId), {"path":"services[1].businessLogic[0].dataClause.customData[1].value"}),
  studioId: this.studioId,
  isPublic: this.isPublic,
  mediaUrls: this.mediaUrls,
  featured: this.featured,
  publishedAt: this.publishedAt,
  accessPolicy: this.accessPolicy,
  director: this.director,
  fundingGoal: this.fundingGoal,
  approvalStatus: runMScript(() => ("pending"), {"path":"services[1].businessLogic[0].dataClause.customData[0].value"}),
  isActive: true,
  _archivedAt: null,
}

Business Logic Workflow

[1] Step : startBusinessApi

Manager initializes context, populates session and request objects, prepares internal structures for parameter handling and workflow execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Manager reads input parameters, normalizes missing values, applies default type casting, and stores them in the API context.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Manager transforms parameters, computes derived values, flattens or remaps arrays/objects, and adjusts formats for downstream processing.


[4] Step : checkParameters

Manager executes built-in validations: required field checks, type enforcement, and basic business rules. Prevents operation if validation fails.


[5] Step : checkBasicAuth

Manager performs authentication and authorization checks: verifies session, user roles, permissions, and tenant restrictions.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildDataClause

Manager constructs the final data object for creation, fills auto-generated fields (IDs, timestamps, owner fields), and ensures schema consistency.

You can use the following settings to change some behavior of this step. dataClause

[7] Step : mainCreateOperation

Manager executes the database insert operation, updates indexes/caches, and triggers internal post-processing like linked default records.


[8] Step : buildOutput

Manager shapes the response: masks sensitive fields, resolves linked references, and formats output according to API contract.


[9] Step : sendResponse

Manager sends the response to the client and finalizes internal tasks like flushing logs or updating session state.


[10] Step : raiseApiEvent

Manager triggers API-level events (Kafka, WebSocket, async workflows) as the final internal step.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The createFilmProject api has got 15 regular client parameters

Parameter Type Required Population
title String true request.body?.[“title”]
description Text true request.body?.[“description”]
synopsis Text false request.body?.[“synopsis”]
budget Double true request.body?.[“budget”]
cast String false request.body?.[“cast”]
genre String false request.body?.[“genre”]
projectType Enum true request.body?.[“projectType”]
studioId ID false request.body?.[“studioId”]
isPublic Boolean true request.body?.[“isPublic”]
mediaUrls String false request.body?.[“mediaUrls”]
featured Boolean false request.body?.[“featured”]
publishedAt Date false request.body?.[“publishedAt”]
accessPolicy Enum true request.body?.[“accessPolicy”]
director String false request.body?.[“director”]
fundingGoal Double false request.body?.[“fundingGoal”]

REST Request

To access the api you can use the REST controller with the path POST /v1/filmprojects

  axios({
    method: 'POST',
    url: '/v1/filmprojects',
    data: {
            title:"String",  
            description:"Text",  
            synopsis:"Text",  
            budget:"Double",  
            cast:"String",  
            genre:"String",  
            projectType:"Enum",  
            studioId:"ID",  
            isPublic:"Boolean",  
            mediaUrls:"String",  
            featured:"Boolean",  
            publishedAt:"Date",  
            accessPolicy:"Enum",  
            director:"String",  
            fundingGoal:"Double",  
    
    },
    params: {
    
        }
  });

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the filmProject object in the respones. However, some properties may be omitted based on the object’s internal logic.

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "filmProject",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"filmProject": {
		"id": "ID",
		"title": "String",
		"description": "Text",
		"synopsis": "Text",
		"budget": "Double",
		"cast": "String",
		"genre": "String",
		"projectType": "Enum",
		"projectType_idx": "Integer",
		"ownerUserId": "ID",
		"studioId": "ID",
		"isPublic": "Boolean",
		"approvalStatus": "Enum",
		"approvalStatus_idx": "Integer",
		"mediaUrls": "String",
		"featured": "Boolean",
		"publishedAt": "Date",
		"accessPolicy": "Enum",
		"accessPolicy_idx": "Integer",
		"director": "String",
		"fundingGoal": "Double",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Business API Design Specification - Update Filmproject

Business API Design Specification - Update Filmproject

A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic.

While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized.

This document provides an in-depth explanation of the architectural design of the updateFilmProject Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side.

Main Data Object and CRUD Operation

The updateFilmProject Business API is designed to handle a update operation on the FilmProject data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

Update a film project. Only the owner or admin can update. Only admin can set approvalStatus=approved/rejected. Owner can withdraw (approvalStatus=withdrawn).

API Frontend Description By The Backend Architect

For editing project details (including withdrawal). ApprovalStatus can only be changed by admin (other than withdrawn by owner). Owner cannot submit direct publish/approve requests; always wait admin.

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The updateFilmProject Business API includes a REST controller that can be triggered via the following route:

/v1/filmprojects/:filmProjectId

By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the Parameters section.

MCP Tool

REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This updateFilmProject Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The updateFilmProject Business API has 15 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client.

Business API parameters can be:

Regular Parameters

Name Type Required Default Location Data Path
filmProjectId ID Yes - urlpath filmProjectId
Description: This id paremeter is used to select the required data object that will be updated
title String No - body title
Description: Project title, unique per owner
description Text No - body description
Description: Project description (for details page/fulltext search)
synopsis Text No - body synopsis
Description: Short synopsis or tagline
budget Double No - body budget
Description: Estimated budget (USD)
cast String No - body cast
Description: List of major cast members (names)
genre String No - body genre
Description: Project genres/tags
isPublic Boolean No - body isPublic
Description: Project public visibility flag
approvalStatus Enum Yes - body approvalStatus
Description: Project approval/publication workflow status
mediaUrls String No - body mediaUrls
Description: Project demo reel/trailer/cover media URLs
featured Boolean No - body featured
Description: Platform feature flag (for promoted projects)
publishedAt Date No - body publishedAt
Description: Publication date
accessPolicy Enum No - body accessPolicy
Description: Access policy (open: any authorized user, restricted: need grant)
director String No - body director
Description: Director of the film project
fundingGoal Double No - body fundingGoal
Description: Funding goal amount (USD)

Parameter Transformations

Some parameters are post-processed using transform scripts after being read from the request but before validation or workflow execution. Only parameters with a transform script are listed below.

No parameters are transformed in this API.

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the updateFilmProject Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks

This Business API enforces ownership of the main data object before executing the operation.


Role and Permission Settings


Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({$and:[{id:this.filmProjectId},{isActive:true}]}), {"path":"services[1].businessLogic[1].whereClause.fullWhereClause"})

Data Clause

Defines custom field-value assignments used to modify or augment the default payload for create and update operations. These settings override values derived from the session or parameters if explicitly provided.", Note that a default data clause is always prepared by Mindbricks using data property settings, however any property in the data clause can be override by Data Clause Settings.

An update data clause populates all update-allowed properties of a data object, however the null properties (that are not provided by client) are ignored in db layer.

Custom Data Clause Override No custom data clause override configured

Actual Data Clause

The business api will use the following data clause. Note that any calculated value will be added to the data clause in the api manager.

{
  title: this.title,
  description: this.description,
  synopsis: this.synopsis,
  budget: this.budget,
  cast: this.cast ? this.cast : 
                 ( this.cast_remove ? sequelize.fn('array_remove', sequelize.col('cast'), this.cast_remove) : (this.cast_append ? sequelize.fn('array_append', sequelize.col('cast'), this.cast_append) : undefined)) ,
  genre: this.genre ? this.genre : 
                 ( this.genre_remove ? sequelize.fn('array_remove', sequelize.col('genre'), this.genre_remove) : (this.genre_append ? sequelize.fn('array_append', sequelize.col('genre'), this.genre_append) : undefined)) ,
  isPublic: this.isPublic,
  approvalStatus: this.approvalStatus,
  mediaUrls: this.mediaUrls ? this.mediaUrls : 
                 ( this.mediaUrls_remove ? sequelize.fn('array_remove', sequelize.col('mediaUrls'), this.mediaUrls_remove) : (this.mediaUrls_append ? sequelize.fn('array_append', sequelize.col('mediaUrls'), this.mediaUrls_append) : undefined)) ,
  featured: this.featured,
  publishedAt: this.publishedAt,
  accessPolicy: this.accessPolicy,
  director: this.director,
  fundingGoal: this.fundingGoal,
}

Business Logic Workflow

[1] Step : startBusinessApi

Manager initializes context, prepares request and session objects, and sets up internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Manager reads parameters from the request or Redis, applies defaults, and writes them into context for downstream milestones.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Manager executes parameter transform scripts and derives any helper values or reshaped payloads into the context.


[4] Step : checkParameters

Manager validates required parameters, checks ID formats (UUID/ObjectId), and ensures all preconditions for update are met.


[5] Action : fetchOwner

Action Type: FetchObjectAction

Fetch project owner details for permission check

class Api {
  async fetchOwner() {
    // Fetch Object on childObject user

    const userQuery = {
      $and: [
        {
          id: runMScript(() => this.filmProject?.ownerUserId, {
            path: "services[1].businessLogic[1].actions.fetchObjectActions[0].matchValue",
          }),
        },
        { isActive: true },
      ],
    };
    const { convertUserQueryToElasticQuery } = require("common");
    const scriptQuery = convertUserQueryToElasticQuery(userQuery);

    const elasticIndex = new ElasticIndexer("user");
    const data = await elasticIndex.getOne(scriptQuery);

    return data
      ? {
          id: data["id"],
          roleId: data["roleId"],
        }
      : null;
  }
}

[6] Step : checkBasicAuth

Manager performs login verification, role, and permission checks, enforcing tenant and access rules before update.

You can use the following settings to change some behavior of this step. authOptions

[7] Step : buildWhereClause

Manager constructs the WHERE clause used to identify the record to update, applying ownership and parent checks if necessary.

You can use the following settings to change some behavior of this step. whereClause

[8] Step : fetchInstance

Manager fetches the existing record from the database and writes it to the context for validation or enrichment.


[9] Action : validateApprovalStatus

Action Type: FunctionCallAction

Ensure only admin can approve/reject; owner can only withdraw.

class Api {
  async validateApprovalStatus() {
    try {
      return runMScript(
        () =>
          (() => {
            const prevStatus = this.filmProject.approvalStatus;
            const newStatus = this.input?.approvalStatus ?? prevStatus;
            const isAdmin = this.session.roleId === "admin";
            // Only admin can approve or reject
            if (
              (newStatus === "approved" || newStatus === "rejected") &&
              !isAdmin
            ) {
              return false;
            }
            // Only owner can withdraw, only from pending/approved
            if (newStatus === "withdrawn") {
              if (
                this.session.userId !== this.filmProject.ownerUserId &&
                !isAdmin
              ) {
                return false;
              }
            }
            // Pending can always be set by owner (i.e. editing reverts to pending)
            return true;
          })(),
        {
          path: "services[1].businessLogic[1].actions.functionCallActions[0].callScript",
        },
      );
    } catch (err) {
      console.error("Error in FunctionCallAction validateApprovalStatus:", err);
      throw err;
    }
  }
}

[10] Action : enforceTransitionRule

Action Type: ValidationAction

Block illegal approvalStatus transitions by non-admins

class Api {
  async enforceTransitionRule() {
    if (this.checkAbsolute()) return true;

    const isValid = runMScript(() => this.isApprovalTransitionValid === true, {
      path: "services[1].businessLogic[1].actions.validationActions[0].validationScript",
    });

    if (!isValid) {
      throw new ForbiddenError(
        "You don&#39;t have permission to change approval status this way.",
      );
    }
    return isValid;
  }
}

[11] Step : checkInstance

Manager performs instance-level validations, including ownership, existence, lock status, or other pre-update checks.


[12] Step : buildDataClause

Manager prepares the data clause for the update, applying transformations or enhancements before persisting.

You can use the following settings to change some behavior of this step. dataClause

[13] Step : mainUpdateOperation

Manager executes the update operation with the WHERE and data clauses. Database-level events are raised if configured.


[14] Step : buildOutput

Manager assembles the response object from the update result, masking fields or injecting additional metadata.


[15] Step : sendResponse

Manager sends the response back to the controller for delivery to the client.


[16] Step : raiseApiEvent

Manager triggers API-level events, sending relevant messages to Kafka or other integrations if configured.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The updateFilmProject api has got 15 regular client parameters

Parameter Type Required Population
filmProjectId ID true request.params?.[“filmProjectId”]
title String false request.body?.[“title”]
description Text false request.body?.[“description”]
synopsis Text false request.body?.[“synopsis”]
budget Double false request.body?.[“budget”]
cast String false request.body?.[“cast”]
genre String false request.body?.[“genre”]
isPublic Boolean false request.body?.[“isPublic”]
approvalStatus Enum true request.body?.[“approvalStatus”]
mediaUrls String false request.body?.[“mediaUrls”]
featured Boolean false request.body?.[“featured”]
publishedAt Date false request.body?.[“publishedAt”]
accessPolicy Enum false request.body?.[“accessPolicy”]
director String false request.body?.[“director”]
fundingGoal Double false request.body?.[“fundingGoal”]

REST Request

To access the api you can use the REST controller with the path PATCH /v1/filmprojects/:filmProjectId

  axios({
    method: 'PATCH',
    url: `/v1/filmprojects/${filmProjectId}`,
    data: {
            title:"String",  
            description:"Text",  
            synopsis:"Text",  
            budget:"Double",  
            cast:"String",  
            genre:"String",  
            isPublic:"Boolean",  
            approvalStatus:"Enum",  
            mediaUrls:"String",  
            featured:"Boolean",  
            publishedAt:"Date",  
            accessPolicy:"Enum",  
            director:"String",  
            fundingGoal:"Double",  
    
    },
    params: {
    
        }
  });

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the filmProject object in the respones. However, some properties may be omitted based on the object’s internal logic.

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "filmProject",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"filmProject": {
		"id": "ID",
		"title": "String",
		"description": "Text",
		"synopsis": "Text",
		"budget": "Double",
		"cast": "String",
		"genre": "String",
		"projectType": "Enum",
		"projectType_idx": "Integer",
		"ownerUserId": "ID",
		"studioId": "ID",
		"isPublic": "Boolean",
		"approvalStatus": "Enum",
		"approvalStatus_idx": "Integer",
		"mediaUrls": "String",
		"featured": "Boolean",
		"publishedAt": "Date",
		"accessPolicy": "Enum",
		"accessPolicy_idx": "Integer",
		"director": "String",
		"fundingGoal": "Double",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	},
	"ownerUser": {
		"roleId": "String"
	}
}

Business API Design Specification - Get Filmproject

Business API Design Specification - Get Filmproject

A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic.

While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized.

This document provides an in-depth explanation of the architectural design of the getFilmProject Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side.

Main Data Object and CRUD Operation

The getFilmProject Business API is designed to handle a get operation on the FilmProject data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

Fetch project details. Accessible by owner, admin, or for public + approved projects. Also for granted investors/users (accessGrant).

API Frontend Description By The Backend Architect

Used to display project details page. Applies access and visibility policy – if project is private, only owner/admin/granted users can see; if public+approved, visible to everyone logged in. User denied access gets 404.

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The getFilmProject Business API includes a REST controller that can be triggered via the following route:

/v1/filmprojects/:filmProjectId

By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the Parameters section.

MCP Tool

REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This getFilmProject Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The getFilmProject Business API has 1 parameter that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client.

Business API parameters can be:

Regular Parameters

Name Type Required Default Location Data Path
filmProjectId ID Yes - urlpath filmProjectId
Description: This id paremeter is used to query the required data object.

Parameter Transformations

Some parameters are post-processed using transform scripts after being read from the request but before validation or workflow execution. Only parameters with a transform script are listed below.

No parameters are transformed in this API.

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the getFilmProject Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Select Clause

Specifies which fields will be selected from the main data object during a get or list operation. Leave blank to select all properties. This applies only to get and list type APIs.",

id,title,description,synopsis,budget,cast,genre,projectType,ownerUserId,studioId,isPublic,approvalStatus,mediaUrls,featured,publishedAt,accessPolicy

Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has a selectBy setting: ‘[’']`

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.


// Addtional Clause Name : allowOnlyAccessible

// condition doWhen 
// No doWhen condtion defined

// condition excludeWhen
// No excludeWhen condtion defined

// clause object
(()=>({$and:[{id:this.filmProjectId},{$or:[{ownerUserId:this.session.userId},{isPublic:true,approvalStatus:"approved"},{ $and:[{accessPolicy:"restricted"},{ownerUserId:this.session.userId}] } ]},{isActive:true}]}))()

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({$and:[{id:this.filmProjectId},(()=>({$and:[{id:this.filmProjectId},{$or:[{ownerUserId:this.session.userId},{isPublic:true,approvalStatus:"approved"},{ $and:[{accessPolicy:"restricted"},{ownerUserId:this.session.userId}] } ]},{isActive:true}]}))(),{isActive:true}]}), {"path":"services[1].businessLogic[2].whereClause.fullWhereClause"})

Get Options

Use these options to set get specific settings.

setAsRead: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed.

No setAsread field-value pair is configured.

Business Logic Workflow

[1] Step : startBusinessApi

Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Extracts parameters from request and Redis, applies defaults, and writes them to context.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Executes parameter transformation scripts, applies type coercion, merges derived values, and reshapes inputs for downstream milestones.


[4] Step : checkParameters

Validates required and custom parameters, enforcing business-specific rules and constraints.


[5] Step : checkBasicAuth

Performs login, role, and permission checks, and applies dynamic object-level access rules.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildWhereClause

Builds the WHERE clause for fetching the object and applies additional scoped filters if configured.

You can use the following settings to change some behavior of this step. whereClause

[7] Step : mainGetOperation

Executes the database fetch, retrieves the object, and stores it in context for enrichment or further checks.

You can use the following settings to change some behavior of this step. selectClause, getOptions

[8] Step : checkInstance

Performs instance-level validations, such as ownership, existence, or access conditions.


[9] Step : buildOutput

Assembles the response from the object, applies masking, formatting, and injects additional metadata if needed.


[10] Step : sendResponse

Delivers the response to the controller for client delivery.


[11] Step : raiseApiEvent

Triggers optional API-level events after workflow completion, sending messages to integrations like Kafka if configured.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The getFilmProject api has got 1 regular client parameter

Parameter Type Required Population
filmProjectId ID true request.params?.[“filmProjectId”]

REST Request

To access the api you can use the REST controller with the path GET /v1/filmprojects/:filmProjectId

  axios({
    method: 'GET',
    url: `/v1/filmprojects/${filmProjectId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the filmProject object in the respones. However, some properties may be omitted based on the object’s internal logic.

This route’s response is constrained to a select list of properties, and therefore does not encompass all attributes of the resource.

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "filmProject",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"filmProject": {
		"ownerUser": {
			"fullname": "String",
			"avatar": "String",
			"roleId": "String"
		},
		"studio": {
			"fullname": "String",
			"avatar": "String",
			"roleId": "String"
		},
		"isActive": true
	}
}

Business API Design Specification - List Filmprojects

Business API Design Specification - List Filmprojects

A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic.

While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized.

This document provides an in-depth explanation of the architectural design of the listFilmProjects Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side.

Main Data Object and CRUD Operation

The listFilmProjects Business API is designed to handle a list operation on the FilmProject data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

List projects (public+approved, owned, or where granted). With filters for search. Results by role: owner/all their projects; normal users see only public+approved; investors/studios see owned or accessible, or public+approved. Filters: genre, budget, approvalStatus, isPublic, featured, projectType, title, description (text search).

API Frontend Description By The Backend Architect

Allows all users to search/browse projects. Only public/approved projects are visible to normal users; owners/investors get private projects to which they’re granted. Search by genre, budget, etc. Use for the main project directory.

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The listFilmProjects Business API includes a REST controller that can be triggered via the following route:

/v1/filmprojects

By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the Parameters section.

MCP Tool

REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This listFilmProjects Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The listFilmProjects Business API does not require any parameters to be provided from the controllers.

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the listFilmProjects Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API is public and can be accessed without login (loginRequired = false).


Ownership Checks


Role and Permission Settings


Select Clause

Specifies which fields will be selected from the main data object during a get or list operation. Leave blank to select all properties. This applies only to get and list type APIs.",

id,title,description,synopsis,budget,cast,genre,projectType,ownerUserId,studioId,isPublic,approvalStatus,mediaUrls,featured,publishedAt,accessPolicy

Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has a fullWhereClause setting :

(()=>{ const userId=this.session && this.session.userId; const role=this.session && this.session.roleId;
if(!userId){ return { isPublic:true, approvalStatus:'approved' }; }
if(role==='admin'){ return {}; }
if(role==='normalUser'){ return { isPublic:true, approvalStatus:'approved' } }
// All other roles: see their own, public+approved, or granted
return { $or:[ { ownerUserId:userId }, { isPublic:true, approvalStatus:'approved' }, { id:{ $in:LIB.listProjectIdsGrantedToUser(userId) } } ] };
})()

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({$and:[(()=>{ const userId=this.session && this.session.userId; const role=this.session && this.session.roleId;
if(!userId){ return { isPublic:true, approvalStatus:'approved' }; }
if(role==='admin'){ return {}; }
if(role==='normalUser'){ return { isPublic:true, approvalStatus:'approved' } }
// All other roles: see their own, public+approved, or granted
return { $or:[ { ownerUserId:userId }, { isPublic:true, approvalStatus:'approved' }, { id:{ $in:LIB.listProjectIdsGrantedToUser(userId) } } ] };
})(),{isActive:true}]}), {"path":"services[1].businessLogic[3].whereClause.fullWhereClause"})

List Options

Defines list-specific options including filtering logic, default sorting, and result customization for APIs that return multiple records.

List Sort By Sort order definitions for the result set. Multiple fields can be provided with direction (asc/desc).

[ publishedAt desc ]

List Group By Grouping definitions for the result set. This is typically used for visual or report-based grouping.

The list is not grouped.

setAsRead: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed.

No setAsread field-value pair is configured.

Permission Filter Optional filter that applies permission constraints dynamically based on session or object roles. So that the list items are filtered by the user’s OBAC or ABAC permissions.

Permission filter is not active at the moment. Follow Mindbricks updates to be able to use it.

Pagination Options

Contains settings to configure pagination behavior for list APIs. Includes options like page size, offset, cursor support, and total count inclusion.

Business Logic Workflow

[1] Step : startBusinessApi

Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Reads request and Redis parameters, applies defaults, and writes them to context for downstream processing.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Transforms and normalizes parameters, derives dependent values, and reshapes inputs for the main list query.


[4] Step : checkParameters

Executes validation logic on required and custom parameters, enforcing business rules and cross-field consistency.


[5] Step : checkBasicAuth

Performs role-based access checks and applies dynamic membership or session-based restrictions.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildWhereClause

Constructs the main query WHERE clause and applies optional filters or scoped access controls.

You can use the following settings to change some behavior of this step. whereClause

[7] Step : mainListOperation

Executes the paginated database query, retrieves the list, and stores results in context for enrichment.

You can use the following settings to change some behavior of this step. selectClause, listOptions, paginationOptions

[8] Step : buildOutput

Assembles the list response, sanitizes sensitive fields, applies transformations, and injects extra context if needed.


[9] Step : sendResponse

Sends the paginated list to the client through the controller.


[10] Step : raiseApiEvent

Triggers optional post-workflow events, such as Kafka messages, logs, or system notifications.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The listFilmProjects api has got no visible parameters.

REST Request

To access the api you can use the REST controller with the path GET /v1/filmprojects

  axios({
    method: 'GET',
    url: '/v1/filmprojects',
    data: {
    
    },
    params: {
    
        }
  });

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the filmProjects object in the respones. However, some properties may be omitted based on the object’s internal logic.

This route’s response is constrained to a select list of properties, and therefore does not encompass all attributes of the resource.

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "filmProjects",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"filmProjects": [
		{
			"ownerUser": [
				{
					"fullname": "String",
					"avatar": "String",
					"roleId": "String"
				},
				{},
				{}
			],
			"isActive": true
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Business API Design Specification - Create Accessgrant

Business API Design Specification - Create Accessgrant

A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic.

While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized.

This document provides an in-depth explanation of the architectural design of the createAccessGrant Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side.

Main Data Object and CRUD Operation

The createAccessGrant Business API is designed to handle a create operation on the AccessGrant data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

Create a new accessGrant. Used for access requests (user) or direct grant (owner/admin).

API Frontend Description By The Backend Architect

Investors request access to private/restricted projects; project owners or admins grant/revoke access to users. Status flows: requested→granted/denied/revoked. Owner can only grant/revoke their own; admins can manage all.

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The createAccessGrant Business API includes a REST controller that can be triggered via the following route:

/v1/accessgrants

By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the Parameters section.

MCP Tool

REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This createAccessGrant Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The createAccessGrant Business API has 7 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client.

Business API parameters can be:

Regular Parameters

Name Type Required Default Location Data Path
accessGrantId ID No - body accessGrantId
Description: This id paremeter is used to create the data object with a given specific id. Leave null for automatic id.
projectId ID Yes - body projectId
Description: Film project ID for which access is granted/requested
granteeUserId ID Yes - body granteeUserId
Description: ID of user being granted/requesting access
grantedByUserId ID No - body grantedByUserId
Description: Who granted/revoked the access (or null for self-request)
status Enum Yes - body status
Description: requested (pending); granted (success); revoked; denied
requestMessage Text No - body requestMessage
Description: Message from requester (for context)
dateGranted Date No - body dateGranted
Description: Timestamp when access status last updated

Parameter Transformations

Some parameters are post-processed using transform scripts after being read from the request but before validation or workflow execution. Only parameters with a transform script are listed below.

No parameters are transformed in this API.

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the createAccessGrant Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Data Clause

Defines custom field-value assignments used to modify or augment the default payload for create and update operations. These settings override values derived from the session or parameters if explicitly provided.", Note that a default data clause is always prepared by Mindbricks using data property settings, however any property in the data clause can be override by Data Clause Settings.

Custom Data Clause Override No custom data clause override configured

Actual Data Clause

The business api will use the following data clause. Note that any calculated value will be added to the data clause in the api manager.

{
  id: this.accessGrantId,
  projectId: this.projectId,
  granteeUserId: this.granteeUserId,
  grantedByUserId: this.grantedByUserId,
  status: this.status,
  requestMessage: this.requestMessage,
  dateGranted: this.dateGranted,
  isActive: true,
  _archivedAt: null,
}

Business Logic Workflow

[1] Step : startBusinessApi

Manager initializes context, populates session and request objects, prepares internal structures for parameter handling and workflow execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Manager reads input parameters, normalizes missing values, applies default type casting, and stores them in the API context.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Manager transforms parameters, computes derived values, flattens or remaps arrays/objects, and adjusts formats for downstream processing.


[4] Step : checkParameters

Manager executes built-in validations: required field checks, type enforcement, and basic business rules. Prevents operation if validation fails.


[5] Step : checkBasicAuth

Manager performs authentication and authorization checks: verifies session, user roles, permissions, and tenant restrictions.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildDataClause

Manager constructs the final data object for creation, fills auto-generated fields (IDs, timestamps, owner fields), and ensures schema consistency.

You can use the following settings to change some behavior of this step. dataClause

[7] Step : mainCreateOperation

Manager executes the database insert operation, updates indexes/caches, and triggers internal post-processing like linked default records.


[8] Step : buildOutput

Manager shapes the response: masks sensitive fields, resolves linked references, and formats output according to API contract.


[9] Step : sendResponse

Manager sends the response to the client and finalizes internal tasks like flushing logs or updating session state.


[10] Step : raiseApiEvent

Manager triggers API-level events (Kafka, WebSocket, async workflows) as the final internal step.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The createAccessGrant api has got 6 regular client parameters

Parameter Type Required Population
projectId ID true request.body?.[“projectId”]
granteeUserId ID true request.body?.[“granteeUserId”]
grantedByUserId ID false request.body?.[“grantedByUserId”]
status Enum true request.body?.[“status”]
requestMessage Text false request.body?.[“requestMessage”]
dateGranted Date false request.body?.[“dateGranted”]

REST Request

To access the api you can use the REST controller with the path POST /v1/accessgrants

  axios({
    method: 'POST',
    url: '/v1/accessgrants',
    data: {
            projectId:"ID",  
            granteeUserId:"ID",  
            grantedByUserId:"ID",  
            status:"Enum",  
            requestMessage:"Text",  
            dateGranted:"Date",  
    
    },
    params: {
    
        }
  });

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the accessGrant object in the respones. However, some properties may be omitted based on the object’s internal logic.

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "accessGrant",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"accessGrant": {
		"id": "ID",
		"projectId": "ID",
		"granteeUserId": "ID",
		"grantedByUserId": "ID",
		"status": "Enum",
		"status_idx": "Integer",
		"requestMessage": "Text",
		"dateGranted": "Date",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Business API Design Specification - Update Accessgrant

Business API Design Specification - Update Accessgrant

A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic.

While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized.

This document provides an in-depth explanation of the architectural design of the updateAccessGrant Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side.

Main Data Object and CRUD Operation

The updateAccessGrant Business API is designed to handle a update operation on the AccessGrant data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

Update status of an access grant. Only admin or project owner can grant, revoke, or deny. User can cancel (delete) their own pending request or see status.

API Frontend Description By The Backend Architect

Used for access management UI. Owners/admins can grant/revoke/deny access grants; requesters can cancel. For status transitions, always log who did it and when. Only valid transitions possible (ex: can’t grant if not owner/admin).

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The updateAccessGrant Business API includes a REST controller that can be triggered via the following route:

/v1/accessgrants/:accessGrantId

By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the Parameters section.

MCP Tool

REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This updateAccessGrant Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The updateAccessGrant Business API has 4 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client.

Business API parameters can be:

Regular Parameters

Name Type Required Default Location Data Path
accessGrantId ID Yes - urlpath accessGrantId
Description: This id paremeter is used to select the required data object that will be updated
status Enum Yes - body status
Description: requested (pending); granted (success); revoked; denied
requestMessage Text No - body requestMessage
Description: Message from requester (for context)
dateGranted Date No - body dateGranted
Description: Timestamp when access status last updated

Parameter Transformations

Some parameters are post-processed using transform scripts after being read from the request but before validation or workflow execution. Only parameters with a transform script are listed below.

No parameters are transformed in this API.

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the updateAccessGrant Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({$and:[{id:this.accessGrantId},{isActive:true}]}), {"path":"services[1].businessLogic[5].whereClause.fullWhereClause"})

Data Clause

Defines custom field-value assignments used to modify or augment the default payload for create and update operations. These settings override values derived from the session or parameters if explicitly provided.", Note that a default data clause is always prepared by Mindbricks using data property settings, however any property in the data clause can be override by Data Clause Settings.

An update data clause populates all update-allowed properties of a data object, however the null properties (that are not provided by client) are ignored in db layer.

Custom Data Clause Override No custom data clause override configured

Actual Data Clause

The business api will use the following data clause. Note that any calculated value will be added to the data clause in the api manager.

{
  status: this.status,
  requestMessage: this.requestMessage,
  dateGranted: this.dateGranted,
}

Business Logic Workflow

[1] Step : startBusinessApi

Manager initializes context, prepares request and session objects, and sets up internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Manager reads parameters from the request or Redis, applies defaults, and writes them into context for downstream milestones.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Manager executes parameter transform scripts and derives any helper values or reshaped payloads into the context.


[4] Step : checkParameters

Manager validates required parameters, checks ID formats (UUID/ObjectId), and ensures all preconditions for update are met.


[5] Action : fetchProject

Action Type: FetchObjectAction

Fetch project to check for ownership/admin of grantor.

class Api {
  async fetchProject() {
    // Fetch Object on childObject filmProject

    const userQuery = {
      $and: [
        {
          id: runMScript(() => this.accessGrant.projectId, {
            path: "services[1].businessLogic[5].actions.fetchObjectActions[0].matchValue",
          }),
        },
        { isActive: true },
      ],
    };
    const { convertUserQueryToSequelizeQuery } = require("common");
    const scriptQuery = convertUserQueryToSequelizeQuery(userQuery);

    // get object from db
    const data = await getFilmProjectByQuery(scriptQuery);

    if (!data) {
      throw new NotFoundError("errMsg_FethcedObjectNotFound:filmProject");
    }

    return data
      ? {
          id: data["id"],
          ownerUserId: data["ownerUserId"],
        }
      : null;
  }
}

[6] Step : checkBasicAuth

Manager performs login verification, role, and permission checks, enforcing tenant and access rules before update.

You can use the following settings to change some behavior of this step. authOptions

[7] Action : validateGrantTransition

Action Type: FunctionCallAction

Only owner or admin can set status=granted/revoked/denied. Requester can only cancel pending request.

class Api {
  async validateGrantTransition() {
    try {
      return runMScript(
        () =>
          (() => {
            const isAdmin = this.session.roleId === "admin";
            const isOwner =
              this.targetProject.ownerUserId === this.session.userId;
            const isRequester =
              this.accessGrant.granteeUserId === this.session.userId;
            const status = this.input?.status;
            if (["granted", "revoked", "denied"].includes(status)) {
              return isAdmin || isOwner;
            }
            if (status === "requested") {
              return isRequester || isAdmin || isOwner;
            }
            return false;
          })(),
        {
          path: "services[1].businessLogic[5].actions.functionCallActions[0].callScript",
        },
      );
    } catch (err) {
      console.error(
        "Error in FunctionCallAction validateGrantTransition:",
        err,
      );
      throw err;
    }
  }
}

[8] Action : enforceGrantTransitionRule

Action Type: ValidationAction

Block illegal grant status changes (non-owner/admin for grant/revoke/deny)

class Api {
  async enforceGrantTransitionRule() {
    if (this.checkAbsolute()) return true;

    const isValid = runMScript(() => this.grantTransitionOk === true, {
      path: "services[1].businessLogic[5].actions.validationActions[0].validationScript",
    });

    if (!isValid) {
      throw new ForbiddenError(
        "You do not have permission to transition grant status in this way.",
      );
    }
    return isValid;
  }
}

[9] Step : buildWhereClause

Manager constructs the WHERE clause used to identify the record to update, applying ownership and parent checks if necessary.

You can use the following settings to change some behavior of this step. whereClause

[10] Step : fetchInstance

Manager fetches the existing record from the database and writes it to the context for validation or enrichment.


[11] Step : checkInstance

Manager performs instance-level validations, including ownership, existence, lock status, or other pre-update checks.


[12] Step : buildDataClause

Manager prepares the data clause for the update, applying transformations or enhancements before persisting.

You can use the following settings to change some behavior of this step. dataClause

[13] Step : mainUpdateOperation

Manager executes the update operation with the WHERE and data clauses. Database-level events are raised if configured.


[14] Step : buildOutput

Manager assembles the response object from the update result, masking fields or injecting additional metadata.


[15] Step : sendResponse

Manager sends the response back to the controller for delivery to the client.


[16] Step : raiseApiEvent

Manager triggers API-level events, sending relevant messages to Kafka or other integrations if configured.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The updateAccessGrant api has got 4 regular client parameters

Parameter Type Required Population
accessGrantId ID true request.params?.[“accessGrantId”]
status Enum true request.body?.[“status”]
requestMessage Text false request.body?.[“requestMessage”]
dateGranted Date false request.body?.[“dateGranted”]

REST Request

To access the api you can use the REST controller with the path PATCH /v1/accessgrants/:accessGrantId

  axios({
    method: 'PATCH',
    url: `/v1/accessgrants/${accessGrantId}`,
    data: {
            status:"Enum",  
            requestMessage:"Text",  
            dateGranted:"Date",  
    
    },
    params: {
    
        }
  });

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the accessGrant object in the respones. However, some properties may be omitted based on the object’s internal logic.

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "accessGrant",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"accessGrant": {
		"id": "ID",
		"projectId": "ID",
		"granteeUserId": "ID",
		"grantedByUserId": "ID",
		"status": "Enum",
		"status_idx": "Integer",
		"requestMessage": "Text",
		"dateGranted": "Date",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Business API Design Specification - Get Accessgrant

Business API Design Specification - Get Accessgrant

A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic.

While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized.

This document provides an in-depth explanation of the architectural design of the getAccessGrant Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side.

Main Data Object and CRUD Operation

The getAccessGrant Business API is designed to handle a get operation on the AccessGrant data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

Get a single accessGrant record by id. Used for grant management UI.

API Frontend Description By The Backend Architect

Shows a single access grant: who, for what project, current status, request message.

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The getAccessGrant Business API includes a REST controller that can be triggered via the following route:

/v1/accessgrants/:accessGrantId

By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the Parameters section.

MCP Tool

REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This getAccessGrant Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The getAccessGrant Business API has 1 parameter that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client.

Business API parameters can be:

Regular Parameters

Name Type Required Default Location Data Path
accessGrantId ID Yes - urlpath accessGrantId
Description: This id paremeter is used to query the required data object.

Parameter Transformations

Some parameters are post-processed using transform scripts after being read from the request but before validation or workflow execution. Only parameters with a transform script are listed below.

No parameters are transformed in this API.

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the getAccessGrant Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Select Clause

Specifies which fields will be selected from the main data object during a get or list operation. Leave blank to select all properties. This applies only to get and list type APIs.",

``

Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({$and:[{id:this.accessGrantId},{isActive:true}]}), {"path":"services[1].businessLogic[6].whereClause.fullWhereClause"})

Get Options

Use these options to set get specific settings.

setAsRead: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed.

No setAsread field-value pair is configured.

Business Logic Workflow

[1] Step : startBusinessApi

Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Extracts parameters from request and Redis, applies defaults, and writes them to context.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Executes parameter transformation scripts, applies type coercion, merges derived values, and reshapes inputs for downstream milestones.


[4] Step : checkParameters

Validates required and custom parameters, enforcing business-specific rules and constraints.


[5] Step : checkBasicAuth

Performs login, role, and permission checks, and applies dynamic object-level access rules.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildWhereClause

Builds the WHERE clause for fetching the object and applies additional scoped filters if configured.

You can use the following settings to change some behavior of this step. whereClause

[7] Step : mainGetOperation

Executes the database fetch, retrieves the object, and stores it in context for enrichment or further checks.

You can use the following settings to change some behavior of this step. selectClause, getOptions

[8] Step : checkInstance

Performs instance-level validations, such as ownership, existence, or access conditions.


[9] Step : buildOutput

Assembles the response from the object, applies masking, formatting, and injects additional metadata if needed.


[10] Step : sendResponse

Delivers the response to the controller for client delivery.


[11] Step : raiseApiEvent

Triggers optional API-level events after workflow completion, sending messages to integrations like Kafka if configured.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The getAccessGrant api has got 1 regular client parameter

Parameter Type Required Population
accessGrantId ID true request.params?.[“accessGrantId”]

REST Request

To access the api you can use the REST controller with the path GET /v1/accessgrants/:accessGrantId

  axios({
    method: 'GET',
    url: `/v1/accessgrants/${accessGrantId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the accessGrant object in the respones. However, some properties may be omitted based on the object’s internal logic.

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "accessGrant",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"accessGrant": {
		"id": "ID",
		"projectId": "ID",
		"granteeUserId": "ID",
		"grantedByUserId": "ID",
		"status": "Enum",
		"status_idx": "Integer",
		"requestMessage": "Text",
		"dateGranted": "Date",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Business API Design Specification - List Accessgrants

Business API Design Specification - List Accessgrants

A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic.

While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized.

This document provides an in-depth explanation of the architectural design of the listAccessGrants Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side.

Main Data Object and CRUD Operation

The listAccessGrants Business API is designed to handle a list operation on the AccessGrant data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

List all accessGrants for a project (owner/admin) or for a user (user’s own requests).

API Frontend Description By The Backend Architect

Used by project owners/admins to see all access requests; by users to see their own requests & statuses. Investors check their granted projects for dashboard; owners manage through this list.

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The listAccessGrants Business API includes a REST controller that can be triggered via the following route:

/v1/accessgrants

By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the Parameters section.

MCP Tool

REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This listAccessGrants Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The listAccessGrants Business API has 3 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client.

Business API parameters can be:

Filter Parameters

The listAccessGrants api supports 3 optional filter parameters for filtering list results using URL query parameters. These parameters are only available for list type APIs.

projectId Filter

Type: ID
Description: Film project ID for which access is granted/requested
Location: Query Parameter

Usage:

Non-Array Property:

Examples:

// Get records with a specific ID
GET /v1/accessgrants?projectId=550e8400-e29b-41d4-a716-446655440000

// Get records with multiple IDs (use multiple parameters)
GET /v1/accessgrants?projectId=550e8400-e29b-41d4-a716-446655440000&projectId=660e8400-e29b-41d4-a716-446655440001

// Get records without this field
GET /v1/accessgrants?projectId=null

granteeUserId Filter

Type: ID
Description: ID of user being granted/requesting access
Location: Query Parameter

Usage:

Non-Array Property:

Examples:

// Get records with a specific ID
GET /v1/accessgrants?granteeUserId=550e8400-e29b-41d4-a716-446655440000

// Get records with multiple IDs (use multiple parameters)
GET /v1/accessgrants?granteeUserId=550e8400-e29b-41d4-a716-446655440000&granteeUserId=660e8400-e29b-41d4-a716-446655440001

// Get records without this field
GET /v1/accessgrants?granteeUserId=null

status Filter

Type: Enum
Description: requested (pending); granted (success); revoked; denied
Location: Query Parameter

Usage:

Examples:

// Get records with specific enum value
GET /v1/accessgrants?status=active

// Get records with multiple enum values (use multiple parameters)
GET /v1/accessgrants?status=active&status=pending

// Get records without this field
GET /v1/accessgrants?status=null

Parameter Transformations

Some parameters are post-processed using transform scripts after being read from the request but before validation or workflow execution. Only parameters with a transform script are listed below.

No parameters are transformed in this API.

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the listAccessGrants Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Select Clause

Specifies which fields will be selected from the main data object during a get or list operation. Leave blank to select all properties. This applies only to get and list type APIs.",

``

Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has a fullWhereClause setting :

(()=>{ const isAdmin = this.session.roleId==='admin';
if(isAdmin){ return {}; }
const userId=this.session.userId;
return { $or: [ { granteeUserId:userId }, { grantedByUserId:userId } ] } })()

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({$and:[(()=>{ const isAdmin = this.session.roleId==='admin';
if(isAdmin){ return {}; }
const userId=this.session.userId;
return { $or: [ { granteeUserId:userId }, { grantedByUserId:userId } ] } })(),{isActive:true}]}), {"path":"services[1].businessLogic[7].whereClause.fullWhereClause"})

List Options

Defines list-specific options including filtering logic, default sorting, and result customization for APIs that return multiple records.

List Sort By Sort order definitions for the result set. Multiple fields can be provided with direction (asc/desc).

[ dateGranted desc ]

List Group By Grouping definitions for the result set. This is typically used for visual or report-based grouping.

The list is not grouped.

setAsRead: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed.

No setAsread field-value pair is configured.

Permission Filter Optional filter that applies permission constraints dynamically based on session or object roles. So that the list items are filtered by the user’s OBAC or ABAC permissions.

Permission filter is not active at the moment. Follow Mindbricks updates to be able to use it.

Pagination Options

Contains settings to configure pagination behavior for list APIs. Includes options like page size, offset, cursor support, and total count inclusion.

Business Logic Workflow

[1] Step : startBusinessApi

Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Reads request and Redis parameters, applies defaults, and writes them to context for downstream processing.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Transforms and normalizes parameters, derives dependent values, and reshapes inputs for the main list query.


[4] Step : checkParameters

Executes validation logic on required and custom parameters, enforcing business rules and cross-field consistency.


[5] Step : checkBasicAuth

Performs role-based access checks and applies dynamic membership or session-based restrictions.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildWhereClause

Constructs the main query WHERE clause and applies optional filters or scoped access controls.

You can use the following settings to change some behavior of this step. whereClause

[7] Step : mainListOperation

Executes the paginated database query, retrieves the list, and stores results in context for enrichment.

You can use the following settings to change some behavior of this step. selectClause, listOptions, paginationOptions

[8] Step : buildOutput

Assembles the list response, sanitizes sensitive fields, applies transformations, and injects extra context if needed.


[9] Step : sendResponse

Sends the paginated list to the client through the controller.


[10] Step : raiseApiEvent

Triggers optional post-workflow events, such as Kafka messages, logs, or system notifications.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The listAccessGrants api has 3 filter parameters available for filtering list results. See the Filter Parameters section above for detailed usage examples.

Filter Parameter Type Array Property Description
projectId ID No Film project ID for which access is granted/requested
granteeUserId ID No ID of user being granted/requesting access
status Enum No requested (pending); granted (success); revoked; denied

REST Request

To access the api you can use the REST controller with the path GET /v1/accessgrants

  axios({
    method: 'GET',
    url: '/v1/accessgrants',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section for usage examples)
        // projectId: '<value>' // Filter by projectId
        // granteeUserId: '<value>' // Filter by granteeUserId
        // status: '<value>' // Filter by status
            }
  });

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the accessGrants object in the respones. However, some properties may be omitted based on the object’s internal logic.

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "accessGrants",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"accessGrants": [
		{
			"id": "ID",
			"projectId": "ID",
			"granteeUserId": "ID",
			"grantedByUserId": "ID",
			"status": "Enum",
			"status_idx": "Integer",
			"requestMessage": "Text",
			"dateGranted": "Date",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID"
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Business API Design Specification - Create Bookmark

Business API Design Specification - Create Bookmark

A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic.

While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized.

This document provides an in-depth explanation of the architectural design of the createBookmark Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side.

Main Data Object and CRUD Operation

The createBookmark Business API is designed to handle a create operation on the ProjectBookmark data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

Add a project bookmark (user/project pair, unique).

API Frontend Description By The Backend Architect

Users bookmark projects for easy retrieval. Only one bookmark per (user, project).

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The createBookmark Business API includes a REST controller that can be triggered via the following route:

/v1/bookmark

By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the Parameters section.

MCP Tool

REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This createBookmark Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The createBookmark Business API has 4 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client.

Business API parameters can be:

Regular Parameters

Name Type Required Default Location Data Path
projectBookmarkId ID No - body projectBookmarkId
Description: This id paremeter is used to create the data object with a given specific id. Leave null for automatic id.
projectId ID Yes - body projectId
Description: The project being bookmarked
userId ID Yes - session userId
Description: The user who bookmarked this project
createdAtBookmark Date No - body createdAtBookmark
Description: When bookmark was made

Parameter Transformations

Some parameters are post-processed using transform scripts after being read from the request but before validation or workflow execution. Only parameters with a transform script are listed below.

No parameters are transformed in this API.

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the createBookmark Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Data Clause

Defines custom field-value assignments used to modify or augment the default payload for create and update operations. These settings override values derived from the session or parameters if explicitly provided.", Note that a default data clause is always prepared by Mindbricks using data property settings, however any property in the data clause can be override by Data Clause Settings.

Custom Data Clause Override No custom data clause override configured

Actual Data Clause

The business api will use the following data clause. Note that any calculated value will be added to the data clause in the api manager.

{
  id: this.projectBookmarkId,
  projectId: this.projectId,
  userId: this.userId,
  createdAtBookmark: this.createdAtBookmark,
}

Business Logic Workflow

[1] Step : startBusinessApi

Manager initializes context, populates session and request objects, prepares internal structures for parameter handling and workflow execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Manager reads input parameters, normalizes missing values, applies default type casting, and stores them in the API context.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Manager transforms parameters, computes derived values, flattens or remaps arrays/objects, and adjusts formats for downstream processing.


[4] Step : checkParameters

Manager executes built-in validations: required field checks, type enforcement, and basic business rules. Prevents operation if validation fails.


[5] Step : checkBasicAuth

Manager performs authentication and authorization checks: verifies session, user roles, permissions, and tenant restrictions.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildDataClause

Manager constructs the final data object for creation, fills auto-generated fields (IDs, timestamps, owner fields), and ensures schema consistency.

You can use the following settings to change some behavior of this step. dataClause

[7] Step : mainCreateOperation

Manager executes the database insert operation, updates indexes/caches, and triggers internal post-processing like linked default records.


[8] Step : buildOutput

Manager shapes the response: masks sensitive fields, resolves linked references, and formats output according to API contract.


[9] Step : sendResponse

Manager sends the response to the client and finalizes internal tasks like flushing logs or updating session state.


[10] Step : raiseApiEvent

Manager triggers API-level events (Kafka, WebSocket, async workflows) as the final internal step.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The createBookmark api has got 1 regular client parameter

Parameter Type Required Population
projectId ID true request.body?.[“projectId”]

REST Request

To access the api you can use the REST controller with the path POST /v1/bookmark

  axios({
    method: 'POST',
    url: '/v1/bookmark',
    data: {
            projectId:"ID",  
    
    },
    params: {
    
        }
  });

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the projectBookmark object in the respones. However, some properties may be omitted based on the object’s internal logic.

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "projectBookmark",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"projectBookmark": {
		"id": "ID",
		"projectId": "ID",
		"userId": "ID",
		"createdAtBookmark": "Date",
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"isActive": true
	}
}

Business API Design Specification - Delete Bookmark

Business API Design Specification - Delete Bookmark

A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic.

While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized.

This document provides an in-depth explanation of the architectural design of the deleteBookmark Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side.

Main Data Object and CRUD Operation

The deleteBookmark Business API is designed to handle a delete operation on the ProjectBookmark data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

Remove a project bookmark (user can only delete their own bookmarks).

API Frontend Description By The Backend Architect

Bookmarks are always per-user: can only remove bookmark if you’re the owner.

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The deleteBookmark Business API includes a REST controller that can be triggered via the following route:

/v1/bookmark/:projectBookmarkId

By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the Parameters section.

MCP Tool

REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This deleteBookmark Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The deleteBookmark Business API has 1 parameter that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client.

Business API parameters can be:

Regular Parameters

Name Type Required Default Location Data Path
projectBookmarkId ID Yes - urlpath projectBookmarkId
Description: This id paremeter is used to select the required data object that will be deleted

Parameter Transformations

Some parameters are post-processed using transform scripts after being read from the request but before validation or workflow execution. Only parameters with a transform script are listed below.

No parameters are transformed in this API.

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the deleteBookmark Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks

This Business API enforces ownership of the main data object before executing the operation.


Role and Permission Settings


Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({id:this.projectBookmarkId}), {"path":"services[1].businessLogic[9].whereClause.fullWhereClause"})

Delete Options

Use these options to set delete specific settings.

useSoftDelete: If true, the record will be marked as deleted (isActive: false) instead of removed. The implementation depends on the data object’s soft delete configuration.

Business Logic Workflow

[1] Step : startBusinessApi

Manager initializes context, prepares request/session objects, and sets up internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Manager reads and normalizes parameters, applies defaults, and stores them in the context for downstream steps.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Manager executes parameter transform scripts, computes derived values, and remaps objects or arrays as needed for later processing.


[4] Step : checkParameters

Manager runs built-in validations including required field checks, type enforcement, and deletion preconditions. Stops execution if validation fails.


[5] Step : checkBasicAuth

Manager validates session, user roles, permissions, and tenant-specific access rules to enforce basic auth restrictions.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildWhereClause

Manager generates the query conditions, applies ownership and parent checks, and ensures the clause is correct for the delete operation.

You can use the following settings to change some behavior of this step. whereClause

[7] Step : fetchInstance

Manager fetches the target record, applies filters from WHERE clause, and writes the instance to the context for further checks.


[8] Step : checkInstance

Manager performs object-level validations such as lock status, soft-delete eligibility, and multi-step approval enforcement.


[9] Step : mainDeleteOperation

Manager executes the delete query, updates related indexes/caches, and handles soft/hard delete logic according to configuration.

You can use the following settings to change some behavior of this step. deleteOptions

[10] Step : buildOutput

Manager shapes the response payload, masks sensitive fields, and formats related cleanup results for output.


[11] Step : sendResponse

Manager delivers the response to the client and finalizes any temporary internal structures.


[12] Step : raiseApiEvent

Manager triggers asynchronous API events, notifies queues or streams, and performs final cleanup for the workflow.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The deleteBookmark api has got 1 regular client parameter

Parameter Type Required Population
projectBookmarkId ID true request.params?.[“projectBookmarkId”]

REST Request

To access the api you can use the REST controller with the path DELETE /v1/bookmark/:projectBookmarkId

  axios({
    method: 'DELETE',
    url: `/v1/bookmark/${projectBookmarkId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the projectBookmark object in the respones. However, some properties may be omitted based on the object’s internal logic.

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "projectBookmark",
	"method": "DELETE",
	"action": "delete",
	"appVersion": "Version",
	"rowCount": 1,
	"projectBookmark": {
		"id": "ID",
		"projectId": "ID",
		"userId": "ID",
		"createdAtBookmark": "Date",
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"isActive": false
	}
}

Business API Design Specification - List Bookmarks

Business API Design Specification - List Bookmarks

A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic.

While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized.

This document provides an in-depth explanation of the architectural design of the listBookmarks Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side.

Main Data Object and CRUD Operation

The listBookmarks Business API is designed to handle a list operation on the ProjectBookmark data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

List a user’s own bookmarks. Only accessible for current user. Used for profile/bookmarks view.

API Frontend Description By The Backend Architect

Used for the user’s My Bookmarks page. Always lists only YOUR bookmarks, never others’.

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The listBookmarks Business API includes a REST controller that can be triggered via the following route:

/v1/bookmarks

By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the Parameters section.

MCP Tool

REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This listBookmarks Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The listBookmarks Business API has 2 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client.

Business API parameters can be:

Filter Parameters

The listBookmarks api supports 2 optional filter parameters for filtering list results using URL query parameters. These parameters are only available for list type APIs.

projectId Filter

Type: ID
Description: The project being bookmarked
Location: Query Parameter

Usage:

Non-Array Property:

Examples:

// Get records with a specific ID
GET /v1/bookmarks?projectId=550e8400-e29b-41d4-a716-446655440000

// Get records with multiple IDs (use multiple parameters)
GET /v1/bookmarks?projectId=550e8400-e29b-41d4-a716-446655440000&projectId=660e8400-e29b-41d4-a716-446655440001

// Get records without this field
GET /v1/bookmarks?projectId=null

userId Filter

Type: ID
Description: The user who bookmarked this project
Location: Query Parameter

Usage:

Non-Array Property:

Examples:

// Get records with a specific ID
GET /v1/bookmarks?userId=550e8400-e29b-41d4-a716-446655440000

// Get records with multiple IDs (use multiple parameters)
GET /v1/bookmarks?userId=550e8400-e29b-41d4-a716-446655440000&userId=660e8400-e29b-41d4-a716-446655440001

// Get records without this field
GET /v1/bookmarks?userId=null

Parameter Transformations

Some parameters are post-processed using transform scripts after being read from the request but before validation or workflow execution. Only parameters with a transform script are listed below.

No parameters are transformed in this API.

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the listBookmarks Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Select Clause

Specifies which fields will be selected from the main data object during a get or list operation. Leave blank to select all properties. This applies only to get and list type APIs.",

``

Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has a fullWhereClause setting :

({userId: this.session.userId})

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => (({userId: this.session.userId})), {"path":"services[1].businessLogic[10].whereClause.fullWhereClause"})

List Options

Defines list-specific options including filtering logic, default sorting, and result customization for APIs that return multiple records.

List Sort By Sort order definitions for the result set. Multiple fields can be provided with direction (asc/desc).

[ createdAtBookmark desc ]

List Group By Grouping definitions for the result set. This is typically used for visual or report-based grouping.

The list is not grouped.

setAsRead: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed.

No setAsread field-value pair is configured.

Permission Filter Optional filter that applies permission constraints dynamically based on session or object roles. So that the list items are filtered by the user’s OBAC or ABAC permissions.

Permission filter is not active at the moment. Follow Mindbricks updates to be able to use it.

Pagination Options

Contains settings to configure pagination behavior for list APIs. Includes options like page size, offset, cursor support, and total count inclusion.

Business Logic Workflow

[1] Step : startBusinessApi

Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Reads request and Redis parameters, applies defaults, and writes them to context for downstream processing.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Transforms and normalizes parameters, derives dependent values, and reshapes inputs for the main list query.


[4] Step : checkParameters

Executes validation logic on required and custom parameters, enforcing business rules and cross-field consistency.


[5] Step : checkBasicAuth

Performs role-based access checks and applies dynamic membership or session-based restrictions.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildWhereClause

Constructs the main query WHERE clause and applies optional filters or scoped access controls.

You can use the following settings to change some behavior of this step. whereClause

[7] Step : mainListOperation

Executes the paginated database query, retrieves the list, and stores results in context for enrichment.

You can use the following settings to change some behavior of this step. selectClause, listOptions, paginationOptions

[8] Step : buildOutput

Assembles the list response, sanitizes sensitive fields, applies transformations, and injects extra context if needed.


[9] Step : sendResponse

Sends the paginated list to the client through the controller.


[10] Step : raiseApiEvent

Triggers optional post-workflow events, such as Kafka messages, logs, or system notifications.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The listBookmarks api has 2 filter parameters available for filtering list results. See the Filter Parameters section above for detailed usage examples.

Filter Parameter Type Array Property Description
projectId ID No The project being bookmarked
userId ID No The user who bookmarked this project

REST Request

To access the api you can use the REST controller with the path GET /v1/bookmarks

  axios({
    method: 'GET',
    url: '/v1/bookmarks',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section for usage examples)
        // projectId: '<value>' // Filter by projectId
        // userId: '<value>' // Filter by userId
            }
  });

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the projectBookmarks object in the respones. However, some properties may be omitted based on the object’s internal logic.

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "projectBookmarks",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"projectBookmarks": [
		{
			"id": "ID",
			"projectId": "ID",
			"userId": "ID",
			"createdAtBookmark": "Date",
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID",
			"isActive": true
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Business API Design Specification - Create Investmentoffer

Business API Design Specification - Create Investmentoffer

A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic.

While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized.

This document provides an in-depth explanation of the architectural design of the createInvestmentOffer Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side.

Main Data Object and CRUD Operation

The createInvestmentOffer Business API is designed to handle a create operation on the InvestmentOffer data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

Investor sends an investment offer to a film project. Status defaults to pending. Only investors can create offers.

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The createInvestmentOffer Business API includes a REST controller that can be triggered via the following route:

/v1/investmentoffers

By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the Parameters section.

MCP Tool

REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This createInvestmentOffer Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The createInvestmentOffer Business API has 7 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client.

Business API parameters can be:

Regular Parameters

Name Type Required Default Location Data Path
investmentOfferId ID No - body investmentOfferId
Description: This id paremeter is used to create the data object with a given specific id. Leave null for automatic id.
projectId ID Yes - body projectId
Description: Film project receiving the investment offer
investorUserId ID Yes - session userId
Description: Investor who made the offer
offerAmount Double Yes - body offerAmount
Description: Investment amount in USD
message Text No - body message
Description: Cover letter or terms from the investor
respondedAt Date No - body respondedAt
Description: When the project owner responded
responseNote Text No - body responseNote
Description: Project owner note on accept/reject

Parameter Transformations

Some parameters are post-processed using transform scripts after being read from the request but before validation or workflow execution. Only parameters with a transform script are listed below.

No parameters are transformed in this API.

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the createInvestmentOffer Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Data Clause

Defines custom field-value assignments used to modify or augment the default payload for create and update operations. These settings override values derived from the session or parameters if explicitly provided.", Note that a default data clause is always prepared by Mindbricks using data property settings, however any property in the data clause can be override by Data Clause Settings.

Custom Data Clause Override No custom data clause override configured

Actual Data Clause

The business api will use the following data clause. Note that any calculated value will be added to the data clause in the api manager.

{
  id: this.investmentOfferId,
  projectId: this.projectId,
  investorUserId: this.investorUserId,
  offerAmount: this.offerAmount,
  message: this.message,
  respondedAt: this.respondedAt,
  responseNote: this.responseNote,
  isActive: true,
  _archivedAt: null,
}

Business Logic Workflow

[1] Step : startBusinessApi

Manager initializes context, populates session and request objects, prepares internal structures for parameter handling and workflow execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Manager reads input parameters, normalizes missing values, applies default type casting, and stores them in the API context.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Manager transforms parameters, computes derived values, flattens or remaps arrays/objects, and adjusts formats for downstream processing.


[4] Step : checkParameters

Manager executes built-in validations: required field checks, type enforcement, and basic business rules. Prevents operation if validation fails.


[5] Step : checkBasicAuth

Manager performs authentication and authorization checks: verifies session, user roles, permissions, and tenant restrictions.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildDataClause

Manager constructs the final data object for creation, fills auto-generated fields (IDs, timestamps, owner fields), and ensures schema consistency.

You can use the following settings to change some behavior of this step. dataClause

[7] Step : mainCreateOperation

Manager executes the database insert operation, updates indexes/caches, and triggers internal post-processing like linked default records.


[8] Step : buildOutput

Manager shapes the response: masks sensitive fields, resolves linked references, and formats output according to API contract.


[9] Step : sendResponse

Manager sends the response to the client and finalizes internal tasks like flushing logs or updating session state.


[10] Step : raiseApiEvent

Manager triggers API-level events (Kafka, WebSocket, async workflows) as the final internal step.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The createInvestmentOffer api has got 5 regular client parameters

Parameter Type Required Population
projectId ID true request.body?.[“projectId”]
offerAmount Double true request.body?.[“offerAmount”]
message Text false request.body?.[“message”]
respondedAt Date false request.body?.[“respondedAt”]
responseNote Text false request.body?.[“responseNote”]

REST Request

To access the api you can use the REST controller with the path POST /v1/investmentoffers

  axios({
    method: 'POST',
    url: '/v1/investmentoffers',
    data: {
            projectId:"ID",  
            offerAmount:"Double",  
            message:"Text",  
            respondedAt:"Date",  
            responseNote:"Text",  
    
    },
    params: {
    
        }
  });

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the investmentOffer object in the respones. However, some properties may be omitted based on the object’s internal logic.

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "investmentOffer",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"investmentOffer": {
		"id": "ID",
		"projectId": "ID",
		"investorUserId": "ID",
		"offerAmount": "Double",
		"message": "Text",
		"status": "Enum",
		"status_idx": "Integer",
		"respondedAt": "Date",
		"responseNote": "Text",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Business API Design Specification - Respond Toinvestmentoffer

Business API Design Specification - Respond Toinvestmentoffer

A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic.

While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized.

This document provides an in-depth explanation of the architectural design of the respondToInvestmentOffer Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side.

Main Data Object and CRUD Operation

The respondToInvestmentOffer Business API is designed to handle a update operation on the InvestmentOffer data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

Project owner accepts or rejects an investment offer. Only the project owner or admin can respond.

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The respondToInvestmentOffer Business API includes a REST controller that can be triggered via the following route:

/v1/respondtoinvestmentoffer/:investmentOfferId

By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the Parameters section.

MCP Tool

REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This respondToInvestmentOffer Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The respondToInvestmentOffer Business API has 6 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client.

Business API parameters can be:

Regular Parameters

Name Type Required Default Location Data Path
investmentOfferId ID Yes - urlpath investmentOfferId
Description: This id paremeter is used to select the required data object that will be updated
offerAmount Double No - body offerAmount
Description: Investment amount in USD
message Text No - body message
Description: Cover letter or terms from the investor
status Enum No - body status
Description: Offer lifecycle status
respondedAt Date No - body respondedAt
Description: When the project owner responded
responseNote Text No - body responseNote
Description: Project owner note on accept/reject

Parameter Transformations

Some parameters are post-processed using transform scripts after being read from the request but before validation or workflow execution. Only parameters with a transform script are listed below.

No parameters are transformed in this API.

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the respondToInvestmentOffer Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({$and:[{id:this.investmentOfferId},{isActive:true}]}), {"path":"services[1].businessLogic[12].whereClause.fullWhereClause"})

Data Clause

Defines custom field-value assignments used to modify or augment the default payload for create and update operations. These settings override values derived from the session or parameters if explicitly provided.", Note that a default data clause is always prepared by Mindbricks using data property settings, however any property in the data clause can be override by Data Clause Settings.

An update data clause populates all update-allowed properties of a data object, however the null properties (that are not provided by client) are ignored in db layer.

Custom Data Clause Override No custom data clause override configured

Actual Data Clause

The business api will use the following data clause. Note that any calculated value will be added to the data clause in the api manager.

{
  offerAmount: this.offerAmount,
  message: this.message,
  status: this.status,
  respondedAt: this.respondedAt,
  responseNote: this.responseNote,
}

Business Logic Workflow

[1] Step : startBusinessApi

Manager initializes context, prepares request and session objects, and sets up internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Manager reads parameters from the request or Redis, applies defaults, and writes them into context for downstream milestones.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Manager executes parameter transform scripts and derives any helper values or reshaped payloads into the context.


[4] Step : checkParameters

Manager validates required parameters, checks ID formats (UUID/ObjectId), and ensures all preconditions for update are met.


[5] Step : checkBasicAuth

Manager performs login verification, role, and permission checks, enforcing tenant and access rules before update.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildWhereClause

Manager constructs the WHERE clause used to identify the record to update, applying ownership and parent checks if necessary.

You can use the following settings to change some behavior of this step. whereClause

[7] Step : fetchInstance

Manager fetches the existing record from the database and writes it to the context for validation or enrichment.


[8] Step : checkInstance

Manager performs instance-level validations, including ownership, existence, lock status, or other pre-update checks.


[9] Step : buildDataClause

Manager prepares the data clause for the update, applying transformations or enhancements before persisting.

You can use the following settings to change some behavior of this step. dataClause

[10] Step : mainUpdateOperation

Manager executes the update operation with the WHERE and data clauses. Database-level events are raised if configured.


[11] Step : buildOutput

Manager assembles the response object from the update result, masking fields or injecting additional metadata.


[12] Step : sendResponse

Manager sends the response back to the controller for delivery to the client.


[13] Step : raiseApiEvent

Manager triggers API-level events, sending relevant messages to Kafka or other integrations if configured.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The respondToInvestmentOffer api has got 6 regular client parameters

Parameter Type Required Population
investmentOfferId ID true request.params?.[“investmentOfferId”]
offerAmount Double false request.body?.[“offerAmount”]
message Text false request.body?.[“message”]
status Enum false request.body?.[“status”]
respondedAt Date false request.body?.[“respondedAt”]
responseNote Text false request.body?.[“responseNote”]

REST Request

To access the api you can use the REST controller with the path PATCH /v1/respondtoinvestmentoffer/:investmentOfferId

  axios({
    method: 'PATCH',
    url: `/v1/respondtoinvestmentoffer/${investmentOfferId}`,
    data: {
            offerAmount:"Double",  
            message:"Text",  
            status:"Enum",  
            respondedAt:"Date",  
            responseNote:"Text",  
    
    },
    params: {
    
        }
  });

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the investmentOffer object in the respones. However, some properties may be omitted based on the object’s internal logic.

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "investmentOffer",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"investmentOffer": {
		"id": "ID",
		"projectId": "ID",
		"investorUserId": "ID",
		"offerAmount": "Double",
		"message": "Text",
		"status": "Enum",
		"status_idx": "Integer",
		"respondedAt": "Date",
		"responseNote": "Text",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Business API Design Specification - List Investmentoffers

Business API Design Specification - List Investmentoffers

A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic.

While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized.

This document provides an in-depth explanation of the architectural design of the listInvestmentOffers Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side.

Main Data Object and CRUD Operation

The listInvestmentOffers Business API is designed to handle a list operation on the InvestmentOffer data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

List investment offers. Admins see all, investors see their own, filmmakers/studios see offers on their projects.

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The listInvestmentOffers Business API includes a REST controller that can be triggered via the following route:

/v1/investmentoffers

By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the Parameters section.

MCP Tool

REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This listInvestmentOffers Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The listInvestmentOffers Business API has 4 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client.

Business API parameters can be:

Filter Parameters

The listInvestmentOffers api supports 4 optional filter parameters for filtering list results using URL query parameters. These parameters are only available for list type APIs.

projectId Filter

Type: ID
Description: Film project receiving the investment offer
Location: Query Parameter

Usage:

Non-Array Property:

Examples:

// Get records with a specific ID
GET /v1/investmentoffers?projectId=550e8400-e29b-41d4-a716-446655440000

// Get records with multiple IDs (use multiple parameters)
GET /v1/investmentoffers?projectId=550e8400-e29b-41d4-a716-446655440000&projectId=660e8400-e29b-41d4-a716-446655440001

// Get records without this field
GET /v1/investmentoffers?projectId=null

investorUserId Filter

Type: ID
Description: Investor who made the offer
Location: Query Parameter

Usage:

Non-Array Property:

Examples:

// Get records with a specific ID
GET /v1/investmentoffers?investorUserId=550e8400-e29b-41d4-a716-446655440000

// Get records with multiple IDs (use multiple parameters)
GET /v1/investmentoffers?investorUserId=550e8400-e29b-41d4-a716-446655440000&investorUserId=660e8400-e29b-41d4-a716-446655440001

// Get records without this field
GET /v1/investmentoffers?investorUserId=null

offerAmount Filter

Type: Double
Description: Investment amount in USD
Location: Query Parameter

Usage:

Non-Array Property:

Range Operators:

Examples:

// Get records with exact value
GET /v1/investmentoffers?offerAmount=25

// Get records with multiple values (use multiple parameters)
GET /v1/investmentoffers?offerAmount=25&offerAmount=30&offerAmount=35

// Get records less than value
GET /v1/investmentoffers?offerAmount=$lt-30

// Get records greater than or equal to value
GET /v1/investmentoffers?offerAmount=$gte-18

// Get records between two values
GET /v1/investmentoffers?offerAmount=$btw-100-500

// Get records without this field
GET /v1/investmentoffers?offerAmount=null

status Filter

Type: Enum
Description: Offer lifecycle status
Location: Query Parameter

Usage:

Examples:

// Get records with specific enum value
GET /v1/investmentoffers?status=active

// Get records with multiple enum values (use multiple parameters)
GET /v1/investmentoffers?status=active&status=pending

// Get records without this field
GET /v1/investmentoffers?status=null

Parameter Transformations

Some parameters are post-processed using transform scripts after being read from the request but before validation or workflow execution. Only parameters with a transform script are listed below.

No parameters are transformed in this API.

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the listInvestmentOffers Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Select Clause

Specifies which fields will be selected from the main data object during a get or list operation. Leave blank to select all properties. This applies only to get and list type APIs.",

``

Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({isActive:true}), {"path":"services[1].businessLogic[13].whereClause.fullWhereClause"})

List Options

Defines list-specific options including filtering logic, default sorting, and result customization for APIs that return multiple records.

List Sort By Sort order definitions for the result set. Multiple fields can be provided with direction (asc/desc).

Specific sort order is not configure, natural order (ascending id) will be used.

List Group By Grouping definitions for the result set. This is typically used for visual or report-based grouping.

The list is not grouped.

setAsRead: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed.

No setAsread field-value pair is configured.

Permission Filter Optional filter that applies permission constraints dynamically based on session or object roles. So that the list items are filtered by the user’s OBAC or ABAC permissions.

Permission filter is not active at the moment. Follow Mindbricks updates to be able to use it.

Pagination Options

Contains settings to configure pagination behavior for list APIs. Includes options like page size, offset, cursor support, and total count inclusion.

Business Logic Workflow

[1] Step : startBusinessApi

Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Reads request and Redis parameters, applies defaults, and writes them to context for downstream processing.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Transforms and normalizes parameters, derives dependent values, and reshapes inputs for the main list query.


[4] Step : checkParameters

Executes validation logic on required and custom parameters, enforcing business rules and cross-field consistency.


[5] Step : checkBasicAuth

Performs role-based access checks and applies dynamic membership or session-based restrictions.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildWhereClause

Constructs the main query WHERE clause and applies optional filters or scoped access controls.

You can use the following settings to change some behavior of this step. whereClause

[7] Step : mainListOperation

Executes the paginated database query, retrieves the list, and stores results in context for enrichment.

You can use the following settings to change some behavior of this step. selectClause, listOptions, paginationOptions

[8] Step : buildOutput

Assembles the list response, sanitizes sensitive fields, applies transformations, and injects extra context if needed.


[9] Step : sendResponse

Sends the paginated list to the client through the controller.


[10] Step : raiseApiEvent

Triggers optional post-workflow events, such as Kafka messages, logs, or system notifications.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The listInvestmentOffers api has 4 filter parameters available for filtering list results. See the Filter Parameters section above for detailed usage examples.

Filter Parameter Type Array Property Description
projectId ID No Film project receiving the investment offer
investorUserId ID No Investor who made the offer
offerAmount Double No Investment amount in USD
status Enum No Offer lifecycle status

REST Request

To access the api you can use the REST controller with the path GET /v1/investmentoffers

  axios({
    method: 'GET',
    url: '/v1/investmentoffers',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section for usage examples)
        // projectId: '<value>' // Filter by projectId
        // investorUserId: '<value>' // Filter by investorUserId
        // offerAmount: '<value>' // Filter by offerAmount
        // status: '<value>' // Filter by status
            }
  });

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the investmentOffers object in the respones. However, some properties may be omitted based on the object’s internal logic.

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "investmentOffers",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"investmentOffers": [
		{
			"id": "ID",
			"projectId": "ID",
			"investorUserId": "ID",
			"offerAmount": "Double",
			"message": "Text",
			"status": "Enum",
			"status_idx": "Integer",
			"respondedAt": "Date",
			"responseNote": "Text",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID"
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Business API Design Specification - Withdraw Investmentoffer

Business API Design Specification - Withdraw Investmentoffer

A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic.

While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized.

This document provides an in-depth explanation of the architectural design of the withdrawInvestmentOffer Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side.

Main Data Object and CRUD Operation

The withdrawInvestmentOffer Business API is designed to handle a update operation on the InvestmentOffer data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

Investor withdraws their own pending offer. Sets status to withdrawn.

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The withdrawInvestmentOffer Business API includes a REST controller that can be triggered via the following route:

/v1/withdrawinvestmentoffer/:investmentOfferId

By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the Parameters section.

MCP Tool

REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This withdrawInvestmentOffer Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The withdrawInvestmentOffer Business API has 6 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client.

Business API parameters can be:

Regular Parameters

Name Type Required Default Location Data Path
investmentOfferId ID Yes - urlpath investmentOfferId
Description: This id paremeter is used to select the required data object that will be updated
offerAmount Double No - body offerAmount
Description: Investment amount in USD
message Text No - body message
Description: Cover letter or terms from the investor
status Enum No - body status
Description: Offer lifecycle status
respondedAt Date No - body respondedAt
Description: When the project owner responded
responseNote Text No - body responseNote
Description: Project owner note on accept/reject

Parameter Transformations

Some parameters are post-processed using transform scripts after being read from the request but before validation or workflow execution. Only parameters with a transform script are listed below.

No parameters are transformed in this API.

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the withdrawInvestmentOffer Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks

This Business API enforces ownership of the main data object before executing the operation.


Role and Permission Settings


Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({$and:[{id:this.investmentOfferId},{isActive:true}]}), {"path":"services[1].businessLogic[14].whereClause.fullWhereClause"})

Data Clause

Defines custom field-value assignments used to modify or augment the default payload for create and update operations. These settings override values derived from the session or parameters if explicitly provided.", Note that a default data clause is always prepared by Mindbricks using data property settings, however any property in the data clause can be override by Data Clause Settings.

An update data clause populates all update-allowed properties of a data object, however the null properties (that are not provided by client) are ignored in db layer.

Custom Data Clause Override No custom data clause override configured

Actual Data Clause

The business api will use the following data clause. Note that any calculated value will be added to the data clause in the api manager.

{
  offerAmount: this.offerAmount,
  message: this.message,
  status: this.status,
  respondedAt: this.respondedAt,
  responseNote: this.responseNote,
}

Business Logic Workflow

[1] Step : startBusinessApi

Manager initializes context, prepares request and session objects, and sets up internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Manager reads parameters from the request or Redis, applies defaults, and writes them into context for downstream milestones.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Manager executes parameter transform scripts and derives any helper values or reshaped payloads into the context.


[4] Step : checkParameters

Manager validates required parameters, checks ID formats (UUID/ObjectId), and ensures all preconditions for update are met.


[5] Step : checkBasicAuth

Manager performs login verification, role, and permission checks, enforcing tenant and access rules before update.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildWhereClause

Manager constructs the WHERE clause used to identify the record to update, applying ownership and parent checks if necessary.

You can use the following settings to change some behavior of this step. whereClause

[7] Step : fetchInstance

Manager fetches the existing record from the database and writes it to the context for validation or enrichment.


[8] Step : checkInstance

Manager performs instance-level validations, including ownership, existence, lock status, or other pre-update checks.


[9] Step : buildDataClause

Manager prepares the data clause for the update, applying transformations or enhancements before persisting.

You can use the following settings to change some behavior of this step. dataClause

[10] Step : mainUpdateOperation

Manager executes the update operation with the WHERE and data clauses. Database-level events are raised if configured.


[11] Step : buildOutput

Manager assembles the response object from the update result, masking fields or injecting additional metadata.


[12] Step : sendResponse

Manager sends the response back to the controller for delivery to the client.


[13] Step : raiseApiEvent

Manager triggers API-level events, sending relevant messages to Kafka or other integrations if configured.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The withdrawInvestmentOffer api has got 6 regular client parameters

Parameter Type Required Population
investmentOfferId ID true request.params?.[“investmentOfferId”]
offerAmount Double false request.body?.[“offerAmount”]
message Text false request.body?.[“message”]
status Enum false request.body?.[“status”]
respondedAt Date false request.body?.[“respondedAt”]
responseNote Text false request.body?.[“responseNote”]

REST Request

To access the api you can use the REST controller with the path PATCH /v1/withdrawinvestmentoffer/:investmentOfferId

  axios({
    method: 'PATCH',
    url: `/v1/withdrawinvestmentoffer/${investmentOfferId}`,
    data: {
            offerAmount:"Double",  
            message:"Text",  
            status:"Enum",  
            respondedAt:"Date",  
            responseNote:"Text",  
    
    },
    params: {
    
        }
  });

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the investmentOffer object in the respones. However, some properties may be omitted based on the object’s internal logic.

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "investmentOffer",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"investmentOffer": {
		"id": "ID",
		"projectId": "ID",
		"investorUserId": "ID",
		"offerAmount": "Double",
		"message": "Text",
		"status": "Enum",
		"status_idx": "Integer",
		"respondedAt": "Date",
		"responseNote": "Text",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Business API Design Specification - Follow User

Business API Design Specification - Follow User

A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic.

While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized.

This document provides an in-depth explanation of the architectural design of the followUser Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side.

Main Data Object and CRUD Operation

The followUser Business API is designed to handle a create operation on the UserFollow data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

Follow a user. Creates a follow relationship between the session user and the target user. Duplicate follows are prevented by composite index.

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The followUser Business API includes a REST controller that can be triggered via the following route:

/v1/followuser

By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the Parameters section.

MCP Tool

REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This followUser Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The followUser Business API has 4 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client.

Business API parameters can be:

Regular Parameters

Name Type Required Default Location Data Path
userFollowId ID No - body userFollowId
Description: This id paremeter is used to create the data object with a given specific id. Leave null for automatic id.
followerUserId ID Yes - session userId
Description: The user who is following
followingUserId ID Yes - body followingUserId
Description: The user being followed
followedAt Date No - body followedAt
Description: When the follow relationship was created

Parameter Transformations

Some parameters are post-processed using transform scripts after being read from the request but before validation or workflow execution. Only parameters with a transform script are listed below.

No parameters are transformed in this API.

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the followUser Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Data Clause

Defines custom field-value assignments used to modify or augment the default payload for create and update operations. These settings override values derived from the session or parameters if explicitly provided.", Note that a default data clause is always prepared by Mindbricks using data property settings, however any property in the data clause can be override by Data Clause Settings.

Custom Data Clause Override No custom data clause override configured

Actual Data Clause

The business api will use the following data clause. Note that any calculated value will be added to the data clause in the api manager.

{
  id: this.userFollowId,
  followerUserId: this.followerUserId,
  followingUserId: this.followingUserId,
  followedAt: this.followedAt,
  isActive: true,
  _archivedAt: null,
}

Business Logic Workflow

[1] Step : startBusinessApi

Manager initializes context, populates session and request objects, prepares internal structures for parameter handling and workflow execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Manager reads input parameters, normalizes missing values, applies default type casting, and stores them in the API context.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Manager transforms parameters, computes derived values, flattens or remaps arrays/objects, and adjusts formats for downstream processing.


[4] Step : checkParameters

Manager executes built-in validations: required field checks, type enforcement, and basic business rules. Prevents operation if validation fails.


[5] Step : checkBasicAuth

Manager performs authentication and authorization checks: verifies session, user roles, permissions, and tenant restrictions.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildDataClause

Manager constructs the final data object for creation, fills auto-generated fields (IDs, timestamps, owner fields), and ensures schema consistency.

You can use the following settings to change some behavior of this step. dataClause

[7] Step : mainCreateOperation

Manager executes the database insert operation, updates indexes/caches, and triggers internal post-processing like linked default records.


[8] Step : buildOutput

Manager shapes the response: masks sensitive fields, resolves linked references, and formats output according to API contract.


[9] Step : sendResponse

Manager sends the response to the client and finalizes internal tasks like flushing logs or updating session state.


[10] Step : raiseApiEvent

Manager triggers API-level events (Kafka, WebSocket, async workflows) as the final internal step.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The followUser api has got 2 regular client parameters

Parameter Type Required Population
followingUserId ID true request.body?.[“followingUserId”]
followedAt Date false request.body?.[“followedAt”]

REST Request

To access the api you can use the REST controller with the path POST /v1/followuser

  axios({
    method: 'POST',
    url: '/v1/followuser',
    data: {
            followingUserId:"ID",  
            followedAt:"Date",  
    
    },
    params: {
    
        }
  });

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the userFollow object in the respones. However, some properties may be omitted based on the object’s internal logic.

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "userFollow",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"userFollow": {
		"id": "ID",
		"followerUserId": "ID",
		"followingUserId": "ID",
		"followedAt": "Date",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Business API Design Specification - Unfollow User

Business API Design Specification - Unfollow User

A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic.

While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized.

This document provides an in-depth explanation of the architectural design of the unfollowUser Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side.

Main Data Object and CRUD Operation

The unfollowUser Business API is designed to handle a delete operation on the UserFollow data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

Unfollow a user. Removes the follow relationship. Only the follower (owner) can unfollow.

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The unfollowUser Business API includes a REST controller that can be triggered via the following route:

/v1/unfollowuser/:userFollowId

By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the Parameters section.

MCP Tool

REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This unfollowUser Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The unfollowUser Business API has 1 parameter that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client.

Business API parameters can be:

Regular Parameters

Name Type Required Default Location Data Path
userFollowId ID Yes - urlpath userFollowId
Description: This id paremeter is used to select the required data object that will be deleted

Parameter Transformations

Some parameters are post-processed using transform scripts after being read from the request but before validation or workflow execution. Only parameters with a transform script are listed below.

No parameters are transformed in this API.

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the unfollowUser Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks

This Business API enforces ownership of the main data object before executing the operation.


Role and Permission Settings


Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({$and:[{id:this.userFollowId},{isActive:true}]}), {"path":"services[1].businessLogic[16].whereClause.fullWhereClause"})

Delete Options

Use these options to set delete specific settings.

useSoftDelete: If true, the record will be marked as deleted (isActive: false) instead of removed. The implementation depends on the data object’s soft delete configuration.

Business Logic Workflow

[1] Step : startBusinessApi

Manager initializes context, prepares request/session objects, and sets up internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Manager reads and normalizes parameters, applies defaults, and stores them in the context for downstream steps.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Manager executes parameter transform scripts, computes derived values, and remaps objects or arrays as needed for later processing.


[4] Step : checkParameters

Manager runs built-in validations including required field checks, type enforcement, and deletion preconditions. Stops execution if validation fails.


[5] Step : checkBasicAuth

Manager validates session, user roles, permissions, and tenant-specific access rules to enforce basic auth restrictions.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildWhereClause

Manager generates the query conditions, applies ownership and parent checks, and ensures the clause is correct for the delete operation.

You can use the following settings to change some behavior of this step. whereClause

[7] Step : fetchInstance

Manager fetches the target record, applies filters from WHERE clause, and writes the instance to the context for further checks.


[8] Step : checkInstance

Manager performs object-level validations such as lock status, soft-delete eligibility, and multi-step approval enforcement.


[9] Step : mainDeleteOperation

Manager executes the delete query, updates related indexes/caches, and handles soft/hard delete logic according to configuration.

You can use the following settings to change some behavior of this step. deleteOptions

[10] Step : buildOutput

Manager shapes the response payload, masks sensitive fields, and formats related cleanup results for output.


[11] Step : sendResponse

Manager delivers the response to the client and finalizes any temporary internal structures.


[12] Step : raiseApiEvent

Manager triggers asynchronous API events, notifies queues or streams, and performs final cleanup for the workflow.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The unfollowUser api has got 1 regular client parameter

Parameter Type Required Population
userFollowId ID true request.params?.[“userFollowId”]

REST Request

To access the api you can use the REST controller with the path DELETE /v1/unfollowuser/:userFollowId

  axios({
    method: 'DELETE',
    url: `/v1/unfollowuser/${userFollowId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the userFollow object in the respones. However, some properties may be omitted based on the object’s internal logic.

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "userFollow",
	"method": "DELETE",
	"action": "delete",
	"appVersion": "Version",
	"rowCount": 1,
	"userFollow": {
		"id": "ID",
		"followerUserId": "ID",
		"followingUserId": "ID",
		"followedAt": "Date",
		"isActive": false,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Business API Design Specification - List Userfollows

Business API Design Specification - List Userfollows

A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic.

While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized.

This document provides an in-depth explanation of the architectural design of the listUserFollows Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side.

Main Data Object and CRUD Operation

The listUserFollows Business API is designed to handle a list operation on the UserFollow data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

List follow relationships. Filter by followerUserId to get who a user follows, or by followingUserId to get a user’s followers.

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The listUserFollows Business API includes a REST controller that can be triggered via the following route:

/v1/userfollows

By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the Parameters section.

MCP Tool

REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This listUserFollows Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The listUserFollows Business API has 2 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client.

Business API parameters can be:

Filter Parameters

The listUserFollows api supports 2 optional filter parameters for filtering list results using URL query parameters. These parameters are only available for list type APIs.

followerUserId Filter

Type: ID
Description: The user who is following
Location: Query Parameter

Usage:

Non-Array Property:

Examples:

// Get records with a specific ID
GET /v1/userfollows?followerUserId=550e8400-e29b-41d4-a716-446655440000

// Get records with multiple IDs (use multiple parameters)
GET /v1/userfollows?followerUserId=550e8400-e29b-41d4-a716-446655440000&followerUserId=660e8400-e29b-41d4-a716-446655440001

// Get records without this field
GET /v1/userfollows?followerUserId=null

followingUserId Filter

Type: ID
Description: The user being followed
Location: Query Parameter

Usage:

Non-Array Property:

Examples:

// Get records with a specific ID
GET /v1/userfollows?followingUserId=550e8400-e29b-41d4-a716-446655440000

// Get records with multiple IDs (use multiple parameters)
GET /v1/userfollows?followingUserId=550e8400-e29b-41d4-a716-446655440000&followingUserId=660e8400-e29b-41d4-a716-446655440001

// Get records without this field
GET /v1/userfollows?followingUserId=null

Parameter Transformations

Some parameters are post-processed using transform scripts after being read from the request but before validation or workflow execution. Only parameters with a transform script are listed below.

No parameters are transformed in this API.

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the listUserFollows Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Select Clause

Specifies which fields will be selected from the main data object during a get or list operation. Leave blank to select all properties. This applies only to get and list type APIs.",

``

Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({isActive:true}), {"path":"services[1].businessLogic[17].whereClause.fullWhereClause"})

List Options

Defines list-specific options including filtering logic, default sorting, and result customization for APIs that return multiple records.

List Sort By Sort order definitions for the result set. Multiple fields can be provided with direction (asc/desc).

Specific sort order is not configure, natural order (ascending id) will be used.

List Group By Grouping definitions for the result set. This is typically used for visual or report-based grouping.

The list is not grouped.

setAsRead: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed.

No setAsread field-value pair is configured.

Permission Filter Optional filter that applies permission constraints dynamically based on session or object roles. So that the list items are filtered by the user’s OBAC or ABAC permissions.

Permission filter is not active at the moment. Follow Mindbricks updates to be able to use it.

Pagination Options

Contains settings to configure pagination behavior for list APIs. Includes options like page size, offset, cursor support, and total count inclusion.

Business Logic Workflow

[1] Step : startBusinessApi

Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Reads request and Redis parameters, applies defaults, and writes them to context for downstream processing.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Transforms and normalizes parameters, derives dependent values, and reshapes inputs for the main list query.


[4] Step : checkParameters

Executes validation logic on required and custom parameters, enforcing business rules and cross-field consistency.


[5] Step : checkBasicAuth

Performs role-based access checks and applies dynamic membership or session-based restrictions.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildWhereClause

Constructs the main query WHERE clause and applies optional filters or scoped access controls.

You can use the following settings to change some behavior of this step. whereClause

[7] Step : mainListOperation

Executes the paginated database query, retrieves the list, and stores results in context for enrichment.

You can use the following settings to change some behavior of this step. selectClause, listOptions, paginationOptions

[8] Step : buildOutput

Assembles the list response, sanitizes sensitive fields, applies transformations, and injects extra context if needed.


[9] Step : sendResponse

Sends the paginated list to the client through the controller.


[10] Step : raiseApiEvent

Triggers optional post-workflow events, such as Kafka messages, logs, or system notifications.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The listUserFollows api has 2 filter parameters available for filtering list results. See the Filter Parameters section above for detailed usage examples.

Filter Parameter Type Array Property Description
followerUserId ID No The user who is following
followingUserId ID No The user being followed

REST Request

To access the api you can use the REST controller with the path GET /v1/userfollows

  axios({
    method: 'GET',
    url: '/v1/userfollows',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section for usage examples)
        // followerUserId: '<value>' // Filter by followerUserId
        // followingUserId: '<value>' // Filter by followingUserId
            }
  });

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the userFollows object in the respones. However, some properties may be omitted based on the object’s internal logic.

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "userFollows",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"userFollows": [
		{
			"id": "ID",
			"followerUserId": "ID",
			"followingUserId": "ID",
			"followedAt": "Date",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID"
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Service Library - projectPortfolio

Service Library - projectPortfolio

This document provides a complete reference of the custom code library for the projectPortfolio service. It includes all library functions, edge functions with their REST endpoints, templates, and assets.

Library Functions

Library functions are reusable modules available to all business APIs and other custom code within the service via require("lib/<moduleName>").

isUserGrantedAccess.js

const { fetchRemoteObjectByMQuery } = require('serviceCommon');
module.exports = async function isUserGrantedAccess(projectId, userId) {
  if(!projectId || !userId) return false;
  const grant = await fetchRemoteObjectByMQuery('accessGrant', { projectId, granteeUserId: userId, status: 'granted' });
  return !!grant;
};

listProjectIdsGrantedToUser.js

const { fetchRemoteListByMQuery } = require('serviceCommon');
module.exports = async function listProjectIdsGrantedToUser(userId) {
  if(!userId) return [];
  const grants = await fetchRemoteListByMQuery('accessGrant', { granteeUserId: userId, status: 'granted' }, 0, 1000);
  return grants.map(g=>g.projectId);
};

This document was generated from the service library configuration and should be kept in sync with design changes.


MessagingCenter Service

Service Design Specification

Service Design Specification

auteurlabb-messagingcenter-service documentation Version: 1.0.15

Scope

This document provides a structured architectural overview of the messagingCenter microservice, detailing its configuration, data model, authorization logic, business rules, and API design. It has been automatically generated based on the service definition within Mindbricks, ensuring that the information reflects the source of truth used during code generation and deployment.

The document is intended to serve multiple audiences:

Note for Frontend Developers: While this document is valuable for understanding business logic and data interactions, please refer to the Service API Documentation for endpoint-level specifications and integration details.

Note for Backend Developers: Since the code for this service is automatically generated by Mindbricks, you typically won’t need to implement or modify it manually. However, this document is especially valuable when you’re building other services—whether within Mindbricks or externally—that need to interact with or depend on this service. It provides a clear reference to the service’s data contracts, business rules, and API structure, helping ensure compatibility and correct integration.

MessagingCenter Service Settings

Facilitates secure messaging between filmmakers, studios, and investors, enabling message threads, moderation, and notifications for industry collaborations.

Service Overview

This service is configured to listen for HTTP requests on port 3002, serving both the main API interface and default administrative endpoints.

The following routes are available by default:

The service uses a PostgreSQL database for data storage, with the database name set to auteurlabb-messagingcenter-service.

This service is accessible via the following environment-specific URLs:

Authentication & Security

This service requires user authentication for access. It supports both JWT and RSA-based authentication mechanisms, ensuring secure user sessions and data integrity. If a crud route also is configured to require login, it will check a valid JWT token in the request query/header/bearer/cookie. If the token is valid, it will extract the user information from the token and make the fetched session data available in the request context.

Service Data Objects

The service uses a PostgreSQL database for data storage, with the database name set to auteurlabb-messagingcenter-service.

Data deletion is managed using a soft delete strategy. Instead of removing records from the database, they are flagged as inactive by setting the isActive field to false.

Object Name Description Public Access
messageThread A thread (private or group) representing a conversation among platform users, optionally linked to a film project accessPrivate
message A message sent in a thread between platform users, with moderation and delivery tracking. accessPrivate

messageThread Data Object

Object Overview

Description: A thread (private or group) representing a conversation among platform users, optionally linked to a film project

This object represents a core data structure within the service and acts as the blueprint for database interaction, API generation, and business logic enforcement. It is defined using the ObjectSettings pattern, which governs its behavior, access control, caching strategy, and integration points with other systems such as Stripe and Redis.

Core Configuration

Composite Indexes

The index also defines a conflict resolution strategy for duplicate key violations.

When a new record would violate this composite index, the following action will be taken:

On Duplicate: throwError

An error will be thrown, preventing the insertion of conflicting data.

Properties Schema

Property Type Required Description
participantIds ID Yes IDs of all participants in the thread (must be 2+ for group, exactly 2 for 1-1)
subject String No Optional subject for the thread, required for group or flagged; for 1-on-1 may be null/empty.
relatedProjectId ID No (Optional) The project this thread is about.
isGroup Boolean Yes True if thread is a group chat, false if private 1-to-1 message.
createdBy ID Yes User who created the thread.
lastMessageAt Date Yes Timestamp of the last message in this thread (used for sorting).
threadStatus Enum Yes Status of the thread: active, archived, flagged.

Array Properties

participantIds

Array properties can hold multiple values and are indicated by the [] suffix in their type. Avoid using arrays in properties that are used for relations, as they will not work correctly. Note that using connection objects instead of arrays is recommended for relations, as they provide better performance and flexibility.

Default Values

Default values are automatically assigned to properties when a new object is created, if no value is provided in the request body. Since default values are applied on db level, they should be literal values, not expressions.If you want to use expressions, you can use transposed parameters in any business API to set default values dynamically.

Constant Properties

createdBy

Constant properties are defined to be immutable after creation, meaning they cannot be updated or changed once set. They are typically used for properties that should remain constant throughout the object’s lifecycle. A property is set to be constant if the Allow Update option is set to false.

Auto Update Properties

participantIds subject relatedProjectId isGroup lastMessageAt threadStatus

An update crud API created with the option Auto Params enabled will automatically update these properties with the provided values in the request body. If you want to update any property in your own business logic not by user input, you can set the Allow Auto Update option to false. These properties will be added to the update API’s body parameters and can be updated by the user if any value is provided in the request body.

Enum Properties

Enum properties are defined with a set of allowed values, ensuring that only valid options can be assigned to them. The enum options value will be stored as strings in the database, but when a data object is created an addtional property with the same name plus an idx suffix will be created, which will hold the index of the selected enum option. You can use the index property to sort by the enum value or when your enum options represent a sequence of values.

Elastic Search Indexing

participantIds relatedProjectId isGroup createdBy lastMessageAt threadStatus

Properties that are indexed in Elastic Search will be searchable via the Elastic Search API. While all properties are stored in the elastic search index of the data object, only those marked for Elastic Search indexing will be available for search queries.

Database Indexing

participantIds relatedProjectId isGroup createdBy lastMessageAt threadStatus

Properties that are indexed in the database will be optimized for query performance, allowing for faster data retrieval. Make a property indexed in the database if you want to use it frequently in query filters or sorting.

Relation Properties

participantIds relatedProjectId createdBy

Mindbricks supports relations between data objects, allowing you to define how objects are linked together. You can define relations in the data object properties, which will be used to create foreign key constraints in the database. For complex joins operations, Mindbricks supportsa BFF pattern, where you can view dynamic and static views based on Elastic Search Indexes. Use db level relations for simple one-to-one or one-to-many relationships, and use BFF views for complex joins that require multiple data objects to be joined together.

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

On Delete: Set Null Required: Yes

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

On Delete: Set Null Required: No

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

On Delete: Set Null Required: Yes

Session Data Properties

createdBy

Session data properties are used to store data that is specific to the user session, allowing for personalized experiences and temporary data storage. If a property is configured as session data, it will be automatically mapped to the related field in the user session during CRUD operations. Note that session data properties can not be mutated by the user, but only by the system.

This property is also used to store the owner of the session data, allowing for ownership checks and access control.

Filter Properties

participantIds relatedProjectId threadStatus

Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API’s that have “Auto Params” enabled.

message Data Object

Object Overview

Description: A message sent in a thread between platform users, with moderation and delivery tracking.

This object represents a core data structure within the service and acts as the blueprint for database interaction, API generation, and business logic enforcement. It is defined using the ObjectSettings pattern, which governs its behavior, access control, caching strategy, and integration points with other systems such as Stripe and Redis.

Core Configuration

Composite Indexes

The index also defines a conflict resolution strategy for duplicate key violations.

When a new record would violate this composite index, the following action will be taken:

On Duplicate: doInsert

The new record will be inserted without checking for duplicates. This means that the composite index is designed for search purposes only.

Properties Schema

Property Type Required Description
threadId ID Yes The parent thread of this message.
senderId ID Yes User ID of the sender.
content Text Yes The actual message content (body).
sentAt Date Yes When the message was sent.
readByIds ID No User IDs who have read the message (for read receipts).
moderationStatus Enum Yes Moderation status: normal (default), flagged (pending review), or removed by admin/moderation.
flaggedReason String No Reason for message being flagged (set by admin or reporting workflow).
adminAction String No Admin/moderator action/note taken regarding this message (set only by admin).

Array Properties

readByIds

Array properties can hold multiple values and are indicated by the [] suffix in their type. Avoid using arrays in properties that are used for relations, as they will not work correctly. Note that using connection objects instead of arrays is recommended for relations, as they provide better performance and flexibility.

Default Values

Default values are automatically assigned to properties when a new object is created, if no value is provided in the request body. Since default values are applied on db level, they should be literal values, not expressions.If you want to use expressions, you can use transposed parameters in any business API to set default values dynamically.

Constant Properties

threadId senderId sentAt

Constant properties are defined to be immutable after creation, meaning they cannot be updated or changed once set. They are typically used for properties that should remain constant throughout the object’s lifecycle. A property is set to be constant if the Allow Update option is set to false.

Auto Update Properties

content readByIds moderationStatus flaggedReason adminAction

An update crud API created with the option Auto Params enabled will automatically update these properties with the provided values in the request body. If you want to update any property in your own business logic not by user input, you can set the Allow Auto Update option to false. These properties will be added to the update API’s body parameters and can be updated by the user if any value is provided in the request body.

Enum Properties

Enum properties are defined with a set of allowed values, ensuring that only valid options can be assigned to them. The enum options value will be stored as strings in the database, but when a data object is created an addtional property with the same name plus an idx suffix will be created, which will hold the index of the selected enum option. You can use the index property to sort by the enum value or when your enum options represent a sequence of values.

Elastic Search Indexing

threadId senderId sentAt readByIds moderationStatus

Properties that are indexed in Elastic Search will be searchable via the Elastic Search API. While all properties are stored in the elastic search index of the data object, only those marked for Elastic Search indexing will be available for search queries.

Database Indexing

threadId senderId sentAt moderationStatus

Properties that are indexed in the database will be optimized for query performance, allowing for faster data retrieval. Make a property indexed in the database if you want to use it frequently in query filters or sorting.

Relation Properties

threadId senderId readByIds

Mindbricks supports relations between data objects, allowing you to define how objects are linked together. You can define relations in the data object properties, which will be used to create foreign key constraints in the database. For complex joins operations, Mindbricks supportsa BFF pattern, where you can view dynamic and static views based on Elastic Search Indexes. Use db level relations for simple one-to-one or one-to-many relationships, and use BFF views for complex joins that require multiple data objects to be joined together.

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

On Delete: Set Null Required: Yes

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

On Delete: Set Null Required: Yes

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

On Delete: Set Null Required: No

Session Data Properties

senderId

Session data properties are used to store data that is specific to the user session, allowing for personalized experiences and temporary data storage. If a property is configured as session data, it will be automatically mapped to the related field in the user session during CRUD operations. Note that session data properties can not be mutated by the user, but only by the system.

This property is also used to store the owner of the session data, allowing for ownership checks and access control.

Formula Properties

sentAt

Formula properties are used to define calculated fields that derive their values from other properties or external data. These properties are automatically calculated based on the defined formula and can be used for dynamic data retrieval.

Filter Properties

threadId moderationStatus

Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API’s that have “Auto Params” enabled.

Business Logic

messagingCenter has got 9 Business APIs to manage its internal and crud logic. For the details of each business API refer to its chapter.

Service Library

Functions

validateParticipantsCount.js

module.exports = function validateParticipantsCount(participantIds,isGroup) {
  if (!Array.isArray(participantIds)) return false;
  const uniqueCount = new Set(participantIds).size;
  if (isGroup) {
    return uniqueCount >= 2;
  } else {
    return uniqueCount === 2;
  }
};

isThreadAccessibleByUser.js

module.exports = function isThreadAccessibleByUser(threadOrThreadCtx,session) {
  if(!threadOrThreadCtx||!session||!session.userId) return false;
  if(['superAdmin','admin'].includes(session.roleId)) return true;
  if(Array.isArray(threadOrThreadCtx.participantIds))
    return threadOrThreadCtx.participantIds.includes(session.userId);
  return false;
};

canUpdateThread.js

module.exports = function canUpdateThread(apiContext,session,thread) {
  if(!session||!thread) return false;
  if(['superAdmin','admin'].includes(session.roleId)) return true;
  if(thread.createdBy===session.userId) return true;
  if(Array.isArray(thread.participantIds)&&thread.participantIds.includes(session.userId)){
    // Only allow subject/threadStatus update for participants
    return true;
  }
  return false;
};

isMessageSendAllowed.js

module.exports = function isMessageSendAllowed(userId,thread) {
  if(!thread||!userId) return false;
  if(Array.isArray(thread.participantIds)){
    return thread.participantIds.includes(userId);
  }
  return false;
};

canUpdateMessage.js

module.exports = function canUpdateMessage(session,msgInstance,updateInput) {
  if(!session||!msgInstance) return false;
  const isAdmin = ['superAdmin','admin'].includes(session.roleId);
  const upFields = Object.keys(updateInput||{});
  // Only admin can update moderationStatus, flaggedReason, adminAction
  if(
    upFields.some(f=>['moderationStatus','flaggedReason','adminAction'].includes(f))
    && !isAdmin
  )return false;
  // Only sender can update content if not flagged/removed
  if(upFields.includes('content')) {
    if(msgInstance.senderId===session.userId && ['normal'].includes(msgInstance.moderationStatus)){
      return true;
    }
    return false;
  }
  return isAdmin; // allow if admin
};

canDeleteMessage.js

module.exports = function canDeleteMessage(session,msgInstance) {
  if(!session||!msgInstance) return false;
  if(['superAdmin','admin'].includes(session.roleId)) return true;
  if(msgInstance.senderId===session.userId && ['normal'].includes(msgInstance.moderationStatus)){
    return true;
  }
  return false;
};

This document was generated from the service architecture definition and should be kept in sync with implementation changes.


REST API GUIDE

REST API GUIDE

auteurlabb-messagingcenter-service

Version: 1.0.15

Facilitates secure messaging between filmmakers, studios, and investors, enabling message threads, moderation, and notifications for industry collaborations.

Architectural Design Credit and Contact Information

The architectural design of this microservice is credited to . For inquiries, feedback, or further information regarding the architecture, please direct your communication to:

Email:

We encourage open communication and welcome any questions or discussions related to the architectural aspects of this microservice.

Documentation Scope

Welcome to the official documentation for the MessagingCenter Service’s REST API. This document is designed to provide a comprehensive guide to interfacing with our MessagingCenter Service exclusively through RESTful API endpoints.

Intended Audience

This documentation is intended for developers and integrators who are looking to interact with the MessagingCenter Service via HTTP requests for purposes such as creating, updating, deleting and querying MessagingCenter objects.

Overview

Within these pages, you will find detailed information on how to effectively utilize the REST API, including authentication methods, request and response formats, endpoint descriptions, and examples of common use cases.

Beyond REST It’s important to note that the MessagingCenter Service also supports alternative methods of interaction, such as gRPC and messaging via a Message Broker. These communication methods are beyond the scope of this document. For information regarding these protocols, please refer to their respective documentation.

Authentication And Authorization

To ensure secure access to the MessagingCenter service’s protected endpoints, a project-wide access token is required. This token serves as the primary method for authenticating requests to our service. However, it’s important to note that access control varies across different routes:

Protected API: Certain API (routes) require specific authorization levels. Access to these routes is contingent upon the possession of a valid access token that meets the route-specific authorization criteria. Unauthorized requests to these routes will be rejected.

**Public API **: The service also includes public API (routes) that are accessible without authentication. These public endpoints are designed for open access and do not require an access token.

Token Locations

When including your access token in a request, ensure it is placed in one of the following specified locations. The service will sequentially search these locations for the token, utilizing the first one it encounters.

Location Token Name / Param Name
Query access_token
Authorization Header Bearer
Header auteurlabb-access-token
Cookie auteurlabb-access-token

Please ensure the token is correctly placed in one of these locations, using the appropriate label as indicated. The service prioritizes these locations in the order listed, processing the first token it successfully identifies.

Api Definitions

This section outlines the API endpoints available within the MessagingCenter service. Each endpoint can receive parameters through various methods, meticulously described in the following definitions. It’s important to understand the flexibility in how parameters can be included in requests to effectively interact with the MessagingCenter service.

This service is configured to listen for HTTP requests on port 3002, serving both the main API interface and default administrative endpoints.

The following routes are available by default:

This service is accessible via the following environment-specific URLs:

Parameter Inclusion Methods: Parameters can be incorporated into API requests in several ways, each with its designated location. Understanding these methods is crucial for correctly constructing your requests:

Query Parameters: Included directly in the URL’s query string.

Path Parameters: Embedded within the URL’s path.

Body Parameters: Sent within the JSON body of the request.

Session Parameters: Automatically read from the session object. This method is used for parameters that are intrinsic to the user’s session, such as userId. When using an API that involves session parameters, you can omit these from your request. The service will automatically bind them to the API layer, provided that a session is associated with your request.

Note on Session Parameters: Session parameters represent a unique method of parameter inclusion, relying on the context of the user’s session. A common example of a session parameter is userId, which the service automatically associates with your request when a session exists. This feature ensures seamless integration of user-specific data without manual input for each request.

By adhering to the specified parameter inclusion methods, you can effectively utilize the MessagingCenter service’s API endpoints. For detailed information on each endpoint, including required parameters and their accepted locations, refer to the individual API definitions below.

Common Parameters

The MessagingCenter service’s business API support several common parameters designed to modify and enhance the behavior of API requests. These parameters are not individually listed in the API route definitions to avoid repetition. Instead, refer to this section to understand how to leverage these common behaviors across different routes. Note that all common parameters should be included in the query part of the URL.

Supported Common Parameters:

By utilizing these common parameters, you can tailor the behavior of API requests to suit your specific requirements, ensuring optimal performance and usability of the MessagingCenter service.

Error Response

If a request encounters an issue, whether due to a logical fault or a technical problem, the service responds with a standardized JSON error structure. The HTTP status code within this response indicates the nature of the error, utilizing commonly recognized codes for clarity:

Each error response is structured to provide meaningful insight into the problem, assisting in diagnosing and resolving issues efficiently.

{
  "result": "ERR",
  "status": 400,
  "message": "errMsg_organizationIdisNotAValidID",
  "errCode": 400,
  "date": "2024-03-19T12:13:54.124Z",
  "detail": "String"
}

Object Structure of a Successfull Response

When the MessagingCenter service processes requests successfully, it wraps the requested resource(s) within a JSON envelope. This envelope not only contains the data but also includes essential metadata, such as configuration details and pagination information, to enrich the response and provide context to the client.

Key Characteristics of the Response Envelope:

Design Considerations: The structure of a API’s response data is meticulously crafted during the service’s architectural planning. This design ensures that responses adequately reflect the intended data relationships and service logic, providing clients with rich and meaningful information.

Brief Data: Certain API’s return a condensed version of the object data, intentionally selecting only specific fields deemed useful for that request. In such instances, the API documentation will detail the properties included in the response, guiding developers on what to expect.

API Response Structure

The API utilizes a standardized JSON envelope to encapsulate responses. This envelope is designed to consistently deliver both the requested data and essential metadata, ensuring that clients can efficiently interpret and utilize the response.

HTTP Status Codes:

Success Response Format:

For successful operations, the response includes a "status": "OK" property, signaling the successful execution of the request. The structure of a successful response is outlined below:

{
  "status":"OK",
  "statusCode": 200,   
  "elapsedMs":126,
  "ssoTime":120,
  "source": "db",
  "cacheKey": "hexCode",
  "userId": "ID",
  "sessionId": "ID",
  "requestId": "ID",
  "dataName":"products",
  "method":"GET",
  "action":"list",
  "appVersion":"Version",
  "rowCount":3
  "products":[{},{},{}],
  "paging": {
    "pageNumber":1, 
    "pageRowCount":25, 
    "totalRowCount":3,
    "pageCount":1
  },
  "filters": [],
  "uiPermissions": []
}

Handling Errors:

For details on handling error scenarios and understanding the structure of error responses, please refer to the “Error Response” section provided earlier in this documentation. It outlines how error conditions are communicated, including the use of HTTP status codes and standardized JSON structures for error messages.

Resources

MessagingCenter service provides the following resources which are stored in its own database as a data object. Note that a resource for an api access is a data object for the service.

MessageThread resource

Resource Definition : A thread (private or group) representing a conversation among platform users, optionally linked to a film project MessageThread Resource Properties

Name Type Required Default Definition
participantIds ID IDs of all participants in the thread (must be 2+ for group, exactly 2 for 1-1)
subject String Optional subject for the thread, required for group or flagged; for 1-on-1 may be null/empty.
relatedProjectId ID (Optional) The project this thread is about.
isGroup Boolean True if thread is a group chat, false if private 1-to-1 message.
createdBy ID User who created the thread.
lastMessageAt Date Timestamp of the last message in this thread (used for sorting).
threadStatus Enum Status of the thread: active, archived, flagged.

Enum Properties

Enum properties are represented as strings in the database. The values are mapped to their corresponding names in the application layer.

threadStatus Enum Property

Property Definition : Status of the thread: active, archived, flagged.Enum Options

Name Value Index
active "active"" 0
archived "archived"" 1
flagged "flagged"" 2

Message resource

Resource Definition : A message sent in a thread between platform users, with moderation and delivery tracking. Message Resource Properties

Name Type Required Default Definition
threadId ID The parent thread of this message.
senderId ID User ID of the sender.
content Text The actual message content (body).
sentAt Date When the message was sent.
readByIds ID User IDs who have read the message (for read receipts).
moderationStatus Enum Moderation status: normal (default), flagged (pending review), or removed by admin/moderation.
flaggedReason String Reason for message being flagged (set by admin or reporting workflow).
adminAction String Admin/moderator action/note taken regarding this message (set only by admin).

Enum Properties

Enum properties are represented as strings in the database. The values are mapped to their corresponding names in the application layer.

moderationStatus Enum Property

Property Definition : Moderation status: normal (default), flagged (pending review), or removed by admin/moderation.Enum Options

Name Value Index
normal "normal"" 0
flagged "flagged"" 1
removed "removed"" 2

Business Api

Create Messagethread API

[Default create API] — This is the designated default create API for the messageThread data object. Frontend generators and AI agents should use this API for standard CRUD operations. Create a new message thread (private or group). Can optionally link to a film project. Enforces participants count and role access.

API Frontend Description By The Backend Architect

For users to start a new conversation (private or group chat) with one or more participants (including themselves); optionally link the thread to a project, set subject (required for group/flagged threads only), subject can be empty for 1-to-1; lastMessageAt auto-set to creation time.

Rest Route

The createMessageThread API REST controller can be triggered via the following route:

/v1/messagethreads

Rest Request Parameters

The createMessageThread api has got 6 regular request parameters

Parameter Type Required Population
participantIds ID true request.body?.[“participantIds”]
subject String false request.body?.[“subject”]
relatedProjectId ID false request.body?.[“relatedProjectId”]
isGroup Boolean true request.body?.[“isGroup”]
lastMessageAt Date true request.body?.[“lastMessageAt”]
threadStatus Enum true request.body?.[“threadStatus”]
participantIds : IDs of all participants in the thread (must be 2+ for group, exactly 2 for 1-1)
subject : Optional subject for the thread, required for group or flagged; for 1-on-1 may be null/empty.
relatedProjectId : (Optional) The project this thread is about.
isGroup : True if thread is a group chat, false if private 1-to-1 message.
lastMessageAt : Timestamp of the last message in this thread (used for sorting).
threadStatus : Status of the thread: active, archived, flagged.

REST Request To access the api you can use the REST controller with the path POST /v1/messagethreads

  axios({
    method: 'POST',
    url: '/v1/messagethreads',
    data: {
            participantIds:"ID",  
            subject:"String",  
            relatedProjectId:"ID",  
            isGroup:"Boolean",  
            lastMessageAt:"Date",  
            threadStatus:"Enum",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "messageThread",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"messageThread": {
		"id": "ID",
		"participantIds": "ID",
		"subject": "String",
		"relatedProjectId": "ID",
		"isGroup": "Boolean",
		"createdBy": "ID",
		"lastMessageAt": "Date",
		"threadStatus": "Enum",
		"threadStatus_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"lastMessage": [
			{
				"senderId": "ID",
				"content": "Text",
				"sentAt": "Date",
				"moderationStatus": "Enum",
				"moderationStatus_idx": "Integer"
			},
			{},
			{}
		],
		"relatedProject": {
			"title": "String",
			"projectType": "Enum",
			"projectType_idx": "Integer",
			"ownerUserId": "ID",
			"isPublic": "Boolean",
			"approvalStatus": "Enum",
			"approvalStatus_idx": "Integer"
		}
	}
}

Get Messagethread API

[Default get API] — This is the designated default get API for the messageThread data object. Frontend generators and AI agents should use this API for standard CRUD operations. Fetch a message thread and last message; only participants or admin may retrieve.

API Frontend Description By The Backend Architect

For thread detail/conversation load: returns thread and its related context (last message, project info). Enforces access: only participants and admins.

Rest Route

The getMessageThread API REST controller can be triggered via the following route:

/v1/messagethreads/:messageThreadId

Rest Request Parameters

The getMessageThread api has got 1 regular request parameter

Parameter Type Required Population
messageThreadId ID true request.params?.[“messageThreadId”]
messageThreadId : This id paremeter is used to query the required data object.

REST Request To access the api you can use the REST controller with the path GET /v1/messagethreads/:messageThreadId

  axios({
    method: 'GET',
    url: `/v1/messagethreads/${messageThreadId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "messageThread",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"messageThread": {
		"id": "ID",
		"participantIds": "ID",
		"subject": "String",
		"relatedProjectId": "ID",
		"isGroup": "Boolean",
		"createdBy": "ID",
		"lastMessageAt": "Date",
		"threadStatus": "Enum",
		"threadStatus_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"lastMessage": [
			{
				"senderId": "ID",
				"content": "Text",
				"sentAt": "Date",
				"moderationStatus": "Enum",
				"moderationStatus_idx": "Integer"
			},
			{},
			{}
		],
		"relatedProject": {
			"title": "String",
			"projectType": "Enum",
			"projectType_idx": "Integer",
			"ownerUserId": "ID",
			"isPublic": "Boolean",
			"approvalStatus": "Enum",
			"approvalStatus_idx": "Integer"
		}
	}
}

List Messagethreads API

[Default list API] — This is the designated default list API for the messageThread data object. Frontend generators and AI agents should use this API for standard CRUD operations. List threads for current user (participantIds contains session userId), or all threads for admin. Filters: by project, thread status, participant, search by subject. Sorted by lastMessageAt desc.

API Frontend Description By The Backend Architect

Returns conversation list for chat inbox. By default lists threads where session user is a participant, with last message for display. Admins can filter/status for moderation, filter by related project for context. Supports pagination.

Rest Route

The listMessageThreads API REST controller can be triggered via the following route:

/v1/messagethreads

Rest Request Parameters

Filter Parameters

The listMessageThreads api supports 4 optional filter parameters for filtering list results:

participantId (ID array): IDs of all participants in the thread (must be 2+ for group, exactly 2 for 1-1)

participantId_op (String): Operator for filtering array property “participantIds”. Use “contains” to check if array contains the value, or “overlap” to check if arrays have common elements.

relatedProjectId (ID): (Optional) The project this thread is about.

threadStatus (Enum): Status of the thread: active, archived, flagged.

REST Request To access the api you can use the REST controller with the path GET /v1/messagethreads

  axios({
    method: 'GET',
    url: '/v1/messagethreads',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section above)
        // participantId: '<value>' // Filter by participantId
        // participantId_op: '<value>' // Filter by participantId_op
        // relatedProjectId: '<value>' // Filter by relatedProjectId
        // threadStatus: '<value>' // Filter by threadStatus
            }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "messageThreads",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"messageThreads": [
		{
			"id": "ID",
			"participantIds": "ID",
			"subject": "String",
			"relatedProjectId": "ID",
			"isGroup": "Boolean",
			"createdBy": "ID",
			"lastMessageAt": "Date",
			"threadStatus": "Enum",
			"threadStatus_idx": "Integer",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID",
			"lastMessage": [
				{
					"senderId": "ID",
					"content": "Text",
					"sentAt": "Date",
					"moderationStatus": "Enum",
					"moderationStatus_idx": "Integer"
				},
				{},
				{}
			],
			"relatedProject": [
				{
					"title": "String",
					"projectType": "Enum",
					"projectType_idx": "Integer",
					"ownerUserId": "ID",
					"isPublic": "Boolean",
					"approvalStatus": "Enum",
					"approvalStatus_idx": "Integer"
				},
				{},
				{}
			]
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Update Messagethread API

[Default update API] — This is the designated default update API for the messageThread data object. Frontend generators and AI agents should use this API for standard CRUD operations. Update thread (subject, status, participants for group). Only thread creator, participants (for subject/archival), or admin can update. Only admin can set status=flagged.

API Frontend Description By The Backend Architect

Allows editing of thread subject, status (archival/flag for moderation), or for admin actions; participants cannot update thread participants unless admin/group owner. All updates are logged for audit. Only admin may set flagged status.

Rest Route

The updateMessageThread API REST controller can be triggered via the following route:

/v1/messagethreads/:messageThreadId

Rest Request Parameters

The updateMessageThread api has got 7 regular request parameters

Parameter Type Required Population
messageThreadId ID true request.params?.[“messageThreadId”]
participantIds ID false request.body?.[“participantIds”]
subject String false request.body?.[“subject”]
relatedProjectId ID false request.body?.[“relatedProjectId”]
isGroup Boolean false request.body?.[“isGroup”]
lastMessageAt Date false request.body?.[“lastMessageAt”]
threadStatus Enum false request.body?.[“threadStatus”]
messageThreadId : This id paremeter is used to select the required data object that will be updated
participantIds : IDs of all participants in the thread (must be 2+ for group, exactly 2 for 1-1)
subject : Optional subject for the thread, required for group or flagged; for 1-on-1 may be null/empty.
relatedProjectId : (Optional) The project this thread is about.
isGroup : True if thread is a group chat, false if private 1-to-1 message.
lastMessageAt : Timestamp of the last message in this thread (used for sorting).
threadStatus : Status of the thread: active, archived, flagged.

REST Request To access the api you can use the REST controller with the path PATCH /v1/messagethreads/:messageThreadId

  axios({
    method: 'PATCH',
    url: `/v1/messagethreads/${messageThreadId}`,
    data: {
            participantIds:"ID",  
            subject:"String",  
            relatedProjectId:"ID",  
            isGroup:"Boolean",  
            lastMessageAt:"Date",  
            threadStatus:"Enum",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "messageThread",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"messageThread": {
		"id": "ID",
		"participantIds": "ID",
		"subject": "String",
		"relatedProjectId": "ID",
		"isGroup": "Boolean",
		"createdBy": "ID",
		"lastMessageAt": "Date",
		"threadStatus": "Enum",
		"threadStatus_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Create Message API

[Default create API] — This is the designated default create API for the message data object. Frontend generators and AI agents should use this API for standard CRUD operations. Send a message (post) in a thread. Only thread participants allowed. Thread lastMessageAt is updated.

API Frontend Description By The Backend Architect

Sends a message in an existing conversation (thread). Access check: only participants may send. Sets senderId, sentAt. Notifies via events. Supports message content, moderation default = normal. Marks thread lastMessageAt for inbox sort.

Rest Route

The createMessage API REST controller can be triggered via the following route:

/v1/messages

Rest Request Parameters

The createMessage api has got 6 regular request parameters

Parameter Type Required Population
threadId ID true request.body?.[“threadId”]
content Text true request.body?.[“content”]
readByIds ID false request.body?.[“readByIds”]
moderationStatus Enum true request.body?.[“moderationStatus”]
flaggedReason String false request.body?.[“flaggedReason”]
adminAction String false request.body?.[“adminAction”]
threadId : The parent thread of this message.
content : The actual message content (body).
readByIds : User IDs who have read the message (for read receipts).
moderationStatus : Moderation status: normal (default), flagged (pending review), or removed by admin/moderation.
flaggedReason : Reason for message being flagged (set by admin or reporting workflow).
adminAction : Admin/moderator action/note taken regarding this message (set only by admin).

REST Request To access the api you can use the REST controller with the path POST /v1/messages

  axios({
    method: 'POST',
    url: '/v1/messages',
    data: {
            threadId:"ID",  
            content:"Text",  
            readByIds:"ID",  
            moderationStatus:"Enum",  
            flaggedReason:"String",  
            adminAction:"String",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "message",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"message": {
		"id": "ID",
		"threadId": "ID",
		"senderId": "ID",
		"content": "Text",
		"sentAt": "Date",
		"readByIds": "ID",
		"moderationStatus": "Enum",
		"moderationStatus_idx": "Integer",
		"flaggedReason": "String",
		"adminAction": "String",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Get Message API

[Default get API] — This is the designated default get API for the message data object. Frontend generators and AI agents should use this API for standard CRUD operations. Fetch a single message, thread participant or admin only.

API Frontend Description By The Backend Architect

Load message (for thread/conversation display or moderation). Only allowed for participant or admin/superAdmin.

Rest Route

The getMessage API REST controller can be triggered via the following route:

/v1/messages/:messageId

Rest Request Parameters

The getMessage api has got 1 regular request parameter

Parameter Type Required Population
messageId ID true request.params?.[“messageId”]
messageId : This id paremeter is used to query the required data object.

REST Request To access the api you can use the REST controller with the path GET /v1/messages/:messageId

  axios({
    method: 'GET',
    url: `/v1/messages/${messageId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "message",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"message": {
		"id": "ID",
		"threadId": "ID",
		"senderId": "ID",
		"content": "Text",
		"sentAt": "Date",
		"readByIds": "ID",
		"moderationStatus": "Enum",
		"moderationStatus_idx": "Integer",
		"flaggedReason": "String",
		"adminAction": "String",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"thread": {
			"participantIds": "ID",
			"subject": "String",
			"relatedProjectId": "ID",
			"threadStatus": "Enum",
			"threadStatus_idx": "Integer"
		}
	}
}

List Messages API

[Default list API] — This is the designated default list API for the message data object. Frontend generators and AI agents should use this API for standard CRUD operations. List messages for a thread (or per filter by participant/project/moderation). Participant or admin only.

API Frontend Description By The Backend Architect

Conversation message list for a given thread, or admin-moderated message audit. Enables filter/sort/paginate (newest last). Only participant of the thread or admin can list.

Rest Route

The listMessages API REST controller can be triggered via the following route:

/v1/messages

Rest Request Parameters

Filter Parameters

The listMessages api supports 2 optional filter parameters for filtering list results:

threadId (ID): The parent thread of this message.

moderationStatus (Enum): Moderation status: normal (default), flagged (pending review), or removed by admin/moderation.

REST Request To access the api you can use the REST controller with the path GET /v1/messages

  axios({
    method: 'GET',
    url: '/v1/messages',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section above)
        // threadId: '<value>' // Filter by threadId
        // moderationStatus: '<value>' // Filter by moderationStatus
            }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "messages",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"messages": [
		{
			"id": "ID",
			"threadId": "ID",
			"senderId": "ID",
			"content": "Text",
			"sentAt": "Date",
			"readByIds": "ID",
			"moderationStatus": "Enum",
			"moderationStatus_idx": "Integer",
			"flaggedReason": "String",
			"adminAction": "String",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID",
			"thread": [
				{
					"participantIds": "ID",
					"subject": "String",
					"relatedProjectId": "ID",
					"threadStatus": "Enum",
					"threadStatus_idx": "Integer"
				},
				{},
				{}
			]
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Update Message API

[Default update API] — This is the designated default update API for the message data object. Frontend generators and AI agents should use this API for standard CRUD operations. Update a message’s content (by sender & only before flagged/removed) or moderation fields (admin only).

API Frontend Description By The Backend Architect

Sender may edit own message content if not yet flagged/removed and within allowed time window (if desired). Only admin may set moderationStatus, flaggedReason, adminAction fields.

Rest Route

The updateMessage API REST controller can be triggered via the following route:

/v1/messages/:messageId

Rest Request Parameters

The updateMessage api has got 6 regular request parameters

Parameter Type Required Population
messageId ID true request.params?.[“messageId”]
content Text false request.body?.[“content”]
readByIds ID false request.body?.[“readByIds”]
moderationStatus Enum false request.body?.[“moderationStatus”]
flaggedReason String false request.body?.[“flaggedReason”]
adminAction String false request.body?.[“adminAction”]
messageId : This id paremeter is used to select the required data object that will be updated
content : The actual message content (body).
readByIds : User IDs who have read the message (for read receipts).
moderationStatus : Moderation status: normal (default), flagged (pending review), or removed by admin/moderation.
flaggedReason : Reason for message being flagged (set by admin or reporting workflow).
adminAction : Admin/moderator action/note taken regarding this message (set only by admin).

REST Request To access the api you can use the REST controller with the path PATCH /v1/messages/:messageId

  axios({
    method: 'PATCH',
    url: `/v1/messages/${messageId}`,
    data: {
            content:"Text",  
            readByIds:"ID",  
            moderationStatus:"Enum",  
            flaggedReason:"String",  
            adminAction:"String",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "message",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"message": {
		"id": "ID",
		"threadId": "ID",
		"senderId": "ID",
		"content": "Text",
		"sentAt": "Date",
		"readByIds": "ID",
		"moderationStatus": "Enum",
		"moderationStatus_idx": "Integer",
		"flaggedReason": "String",
		"adminAction": "String",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Delete Message API

[Default delete API] — This is the designated default delete API for the message data object. Frontend generators and AI agents should use this API for standard CRUD operations. Delete message (by sender - if unflagged, or admin at any time).

API Frontend Description By The Backend Architect

Sender may remove their own unflagged/unmoderated message; admin may remove (hard/soft) any message (for moderation cleanup). All deletes are soft by default (isActive=false).

Rest Route

The deleteMessage API REST controller can be triggered via the following route:

/v1/messages/:messageId

Rest Request Parameters

The deleteMessage api has got 1 regular request parameter

Parameter Type Required Population
messageId ID true request.params?.[“messageId”]
messageId : This id paremeter is used to select the required data object that will be deleted

REST Request To access the api you can use the REST controller with the path DELETE /v1/messages/:messageId

  axios({
    method: 'DELETE',
    url: `/v1/messages/${messageId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "message",
	"method": "DELETE",
	"action": "delete",
	"appVersion": "Version",
	"rowCount": 1,
	"message": {
		"id": "ID",
		"threadId": "ID",
		"senderId": "ID",
		"content": "Text",
		"sentAt": "Date",
		"readByIds": "ID",
		"moderationStatus": "Enum",
		"moderationStatus_idx": "Integer",
		"flaggedReason": "String",
		"adminAction": "String",
		"isActive": false,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Authentication Specific Routes

Common Routes

Route: currentuser

Route Definition: Retrieves the currently authenticated user’s session information.

Route Type: sessionInfo

Access Route: GET /currentuser

Parameters

This route does not require any request parameters.

Behavior

// Sample GET /currentuser call
axios.get("/currentuser", {
  headers: {
    "Authorization": "Bearer your-jwt-token"
  }
});

Success Response Returns the session object, including user-related data and token information.

{
  "sessionId": "9cf23fa8-07d4-4e7c-80a6-ec6d6ac96bb9",
  "userId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38",
  "email": "user@example.com",
  "fullname": "John Doe",
  "roleId": "user",
  "tenantId": "abc123",
  "accessToken": "jwt-token-string",
  ...
}

Error Response 401 Unauthorized: No active session found.

{
  "status": "ERR",
  "message": "No login found"
}

Notes

Route: permissions

*Route Definition*: Retrieves all effective permission records assigned to the currently authenticated user.

*Route Type*: permissionFetch

Access Route: GET /permissions

Parameters

This route does not require any request parameters.

Behavior

// Sample GET /permissions call
axios.get("/permissions", {
  headers: {
    "Authorization": "Bearer your-jwt-token"
  }
});

Success Response

Returns an array of permission objects.

[
  {
    "id": "perm1",
    "permissionName": "adminPanel.access",
    "roleId": "admin",
    "subjectUserId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38",
    "subjectUserGroupId": null,
    "objectId": null,
    "canDo": true,
    "tenantCodename": "store123"
  },
  {
    "id": "perm2",
    "permissionName": "orders.manage",
    "roleId": null,
    "subjectUserId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38",
    "subjectUserGroupId": null,
    "objectId": null,
    "canDo": true,
    "tenantCodename": "store123"
  }
]

Each object reflects a single permission grant, aligned with the givenPermissions model:

Error Responses

{
  "status": "ERR",
  "message": "No login found"
}

Notes

Tip: Applications can cache permission results client-side or server-side, but should occasionally refresh by calling this endpoint, especially after login or permission-changing operations.

Route: permissions/:permissionName

Route Definition: Checks whether the current user has access to a specific permission, and provides a list of scoped object exceptions or inclusions.

Route Type: permissionScopeCheck

Access Route: GET /permissions/:permissionName

Parameters

Parameter Type Required Population
permissionName String Yes request.params.permissionName

Behavior

// Sample GET /permissions/orders.manage
axios.get("/permissions/orders.manage", {
  headers: {
    "Authorization": "Bearer your-jwt-token"
  }
});

Success Response

{
  "canDo": true,
  "exceptions": [
    "a1f2e3d4-xxxx-yyyy-zzzz-object1",
    "b2c3d4e5-xxxx-yyyy-zzzz-object2"
  ]
}

Copyright

All sources, documents and other digital materials are copyright of .

About Us

For more information please visit our website: .

. .


EVENT GUIDE

EVENT GUIDE

auteurlabb-messagingcenter-service

Facilitates secure messaging between filmmakers, studios, and investors, enabling message threads, moderation, and notifications for industry collaborations.

Architectural Design Credit and Contact Information

The architectural design of this microservice is credited to . For inquiries, feedback, or further information regarding the architecture, please direct your communication to:

Email:

We encourage open communication and welcome any questions or discussions related to the architectural aspects of this microservice.

Documentation Scope

Welcome to the official documentation for the MessagingCenter Service Event descriptions. This guide is dedicated to detailing how to subscribe to and listen for state changes within the MessagingCenter Service, offering an exclusive focus on event subscription mechanisms.

Intended Audience

This documentation is aimed at developers and integrators looking to monitor MessagingCenter Service state changes. It is especially relevant for those wishing to implement or enhance business logic based on interactions with MessagingCenter objects.

Overview

This section provides detailed instructions on monitoring service events, covering payload structures and demonstrating typical use cases through examples.

Authentication and Authorization

Access to the MessagingCenter service’s events is facilitated through the project’s Kafka server, which is not accessible to the public. Subscription to a Kafka topic requires being on the same network and possessing valid Kafka user credentials. This document presupposes that readers have existing access to the Kafka server.

Additionally, the service offers a public subscription option via REST for real-time data management in frontend applications, secured through REST API authentication and authorization mechanisms. To subscribe to service events via the REST API, please consult the Realtime REST API Guide.

Database Events

Database events are triggered at the database layer, automatically and atomically, in response to any modifications at the data level. These events serve to notify subscribers about the creation, update, or deletion of objects within the database, distinct from any overarching business logic.

Listening to database events is particularly beneficial for those focused on tracking changes at the database level. A typical use case for subscribing to database events is to replicate the data store of one service within another service’s scope, ensuring data consistency and syncronization across services.

For example, while a business operation such as “approve membership” might generate a high-level business event like membership-approved, the underlying database changes could involve multiple state updates to different entities. These might be published as separate events, such as dbevent-member-updated and dbevent-user-updated, reflecting the granular changes at the database level.

Such detailed eventing provides a robust foundation for building responsive, data-driven applications, enabling fine-grained observability and reaction to the dynamics of the data landscape. It also facilitates the architectural pattern of event sourcing, where state changes are captured as a sequence of events, allowing for high-fidelity data replication and history replay for analytical or auditing purposes.

DbEvent messageThread-created

Event topic: auteurlabb-messagingcenter-service-dbevent-messagethread-created

This event is triggered upon the creation of a messageThread data object in the database. The event payload encompasses the newly created data, encapsulated within the root of the paylod.

Event payload:

{"id":"ID","participantIds":"ID","subject":"String","relatedProjectId":"ID","isGroup":"Boolean","createdBy":"ID","lastMessageAt":"Date","threadStatus":"Enum","threadStatus_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

DbEvent messageThread-updated

Event topic: auteurlabb-messagingcenter-service-dbevent-messagethread-updated

Activation of this event follows the update of a messageThread data object. The payload contains the updated information under the messageThread attribute, along with the original data prior to update, labeled as old_messageThread and also you can find the old and new versions of updated-only portion of the data…

Event payload:

{
old_messageThread:{"id":"ID","participantIds":"ID","subject":"String","relatedProjectId":"ID","isGroup":"Boolean","createdBy":"ID","lastMessageAt":"Date","threadStatus":"Enum","threadStatus_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},
messageThread:{"id":"ID","participantIds":"ID","subject":"String","relatedProjectId":"ID","isGroup":"Boolean","createdBy":"ID","lastMessageAt":"Date","threadStatus":"Enum","threadStatus_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},
oldDataValues,
newDataValues
}

DbEvent messageThread-deleted

Event topic: auteurlabb-messagingcenter-service-dbevent-messagethread-deleted

This event announces the deletion of a messageThread data object, covering both hard deletions (permanent removal) and soft deletions (where the isActive attribute is set to false). Regardless of the deletion type, the event payload will present the data as it was immediately before deletion, highlighting an isActive status of false for soft deletions.

Event payload:

{"id":"ID","participantIds":"ID","subject":"String","relatedProjectId":"ID","isGroup":"Boolean","createdBy":"ID","lastMessageAt":"Date","threadStatus":"Enum","threadStatus_idx":"Integer","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

DbEvent message-created

Event topic: auteurlabb-messagingcenter-service-dbevent-message-created

This event is triggered upon the creation of a message data object in the database. The event payload encompasses the newly created data, encapsulated within the root of the paylod.

Event payload:

{"id":"ID","threadId":"ID","senderId":"ID","content":"Text","sentAt":"Date","readByIds":"ID","moderationStatus":"Enum","moderationStatus_idx":"Integer","flaggedReason":"String","adminAction":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

DbEvent message-updated

Event topic: auteurlabb-messagingcenter-service-dbevent-message-updated

Activation of this event follows the update of a message data object. The payload contains the updated information under the message attribute, along with the original data prior to update, labeled as old_message and also you can find the old and new versions of updated-only portion of the data…

Event payload:

{
old_message:{"id":"ID","threadId":"ID","senderId":"ID","content":"Text","sentAt":"Date","readByIds":"ID","moderationStatus":"Enum","moderationStatus_idx":"Integer","flaggedReason":"String","adminAction":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},
message:{"id":"ID","threadId":"ID","senderId":"ID","content":"Text","sentAt":"Date","readByIds":"ID","moderationStatus":"Enum","moderationStatus_idx":"Integer","flaggedReason":"String","adminAction":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},
oldDataValues,
newDataValues
}

DbEvent message-deleted

Event topic: auteurlabb-messagingcenter-service-dbevent-message-deleted

This event announces the deletion of a message data object, covering both hard deletions (permanent removal) and soft deletions (where the isActive attribute is set to false). Regardless of the deletion type, the event payload will present the data as it was immediately before deletion, highlighting an isActive status of false for soft deletions.

Event payload:

{"id":"ID","threadId":"ID","senderId":"ID","content":"Text","sentAt":"Date","readByIds":"ID","moderationStatus":"Enum","moderationStatus_idx":"Integer","flaggedReason":"String","adminAction":"String","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

ElasticSearch Index Events

Within the MessagingCenter service, most data objects are mirrored in ElasticSearch indices, ensuring these indices remain syncronized with their database counterparts through creation, updates, and deletions. These indices serve dual purposes: they act as a data source for external services and furnish aggregated data tailored to enhance frontend user experiences. Consequently, an ElasticSearch index might encapsulate data in its original form or aggregate additional information from other data objects.

These aggregations can include both one-to-one and one-to-many relationships not only with database objects within the same service but also across different services. This capability allows developers to access comprehensive, aggregated data efficiently. By subscribing to ElasticSearch index events, developers are notified when an index is updated and can directly obtain the aggregated entity within the event payload, bypassing the need for separate ElasticSearch queries.

It’s noteworthy that some services may augment another service’s index by appending to the entity’s extends object. In such scenarios, an *-extended event will contain only the newly added data. Should you require the complete dataset, you would need to retrieve the full ElasticSearch index entity using the provided ID.

This approach to indexing and event handling facilitates a modular, interconnected architecture where services can seamlessly integrate and react to changes, enriching the overall data ecosystem and enabling more dynamic, responsive applications.

Index Event messagethread-created

Event topic: elastic-index-auteurlabb_messagethread-created

Event payload:

{"id":"ID","participantIds":"ID","subject":"String","relatedProjectId":"ID","isGroup":"Boolean","createdBy":"ID","lastMessageAt":"Date","threadStatus":"Enum","threadStatus_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event messagethread-updated

Event topic: elastic-index-auteurlabb_messagethread-created

Event payload:

{"id":"ID","participantIds":"ID","subject":"String","relatedProjectId":"ID","isGroup":"Boolean","createdBy":"ID","lastMessageAt":"Date","threadStatus":"Enum","threadStatus_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event messagethread-deleted

Event topic: elastic-index-auteurlabb_messagethread-deleted

Event payload:

{"id":"ID","participantIds":"ID","subject":"String","relatedProjectId":"ID","isGroup":"Boolean","createdBy":"ID","lastMessageAt":"Date","threadStatus":"Enum","threadStatus_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event messagethread-extended

Event topic: elastic-index-auteurlabb_messagethread-extended

Event payload:

{
  id: id,
  extends: {
    [extendName]: "Object",
    [extendName + "_count"]: "Number",
  },
}

Route Events

Route events are emitted following the successful execution of a route. While most routes perform CRUD (Create, Read, Update, Delete) operations on data objects, resulting in route events that closely resemble database events, there are distinctions worth noting. A single route execution might trigger multiple CRUD actions and ElasticSearch indexing operations. However, for those primarily concerned with the overarching business logic and its outcomes, listening to the consolidated route event, published once at the conclusion of the route’s execution, is more pertinent.

Moreover, routes often deliver aggregated data beyond the primary database object, catering to specific client needs. For instance, creating a data object via a route might not only return the entity’s data but also route-specific metrics, such as the executing user’s permissions related to the entity. Alternatively, a route might automatically generate default child entities following the creation of a parent object. Consequently, the route event encapsulates a unified dataset encompassing both the parent and its children, in contrast to individual events triggered for each entity created. Therefore, subscribing to route events can offer a richer, more contextually relevant set of information aligned with business logic.

The payload of a route event mirrors the REST response JSON of the route, providing a direct and comprehensive reflection of the data and metadata communicated to the client. This ensures that subscribers to route events receive a payload that encapsulates both the primary data involved and any additional information deemed significant at the business level, facilitating a deeper understanding and integration of the service’s functional outcomes.

Route Event messagethread-created

Event topic : auteurlabb-messagingcenter-service-messagethread-created

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the messageThread data object itself.

The following JSON included in the payload illustrates the fullest representation of the messageThread object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"messageThread","method":"POST","action":"create","appVersion":"Version","rowCount":1,"messageThread":{"id":"ID","participantIds":"ID","subject":"String","relatedProjectId":"ID","isGroup":"Boolean","createdBy":"ID","lastMessageAt":"Date","threadStatus":"Enum","threadStatus_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","lastMessage":[{"senderId":"ID","content":"Text","sentAt":"Date","moderationStatus":"Enum","moderationStatus_idx":"Integer"},{},{}],"relatedProject":{"title":"String","projectType":"Enum","projectType_idx":"Integer","ownerUserId":"ID","isPublic":"Boolean","approvalStatus":"Enum","approvalStatus_idx":"Integer"}}}

Route Event messagethread-retrived

Event topic : auteurlabb-messagingcenter-service-messagethread-retrived

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the messageThread data object itself.

The following JSON included in the payload illustrates the fullest representation of the messageThread object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"messageThread","method":"GET","action":"get","appVersion":"Version","rowCount":1,"messageThread":{"id":"ID","participantIds":"ID","subject":"String","relatedProjectId":"ID","isGroup":"Boolean","createdBy":"ID","lastMessageAt":"Date","threadStatus":"Enum","threadStatus_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","lastMessage":[{"senderId":"ID","content":"Text","sentAt":"Date","moderationStatus":"Enum","moderationStatus_idx":"Integer"},{},{}],"relatedProject":{"title":"String","projectType":"Enum","projectType_idx":"Integer","ownerUserId":"ID","isPublic":"Boolean","approvalStatus":"Enum","approvalStatus_idx":"Integer"}}}

Route Event messagethreads-listed

Event topic : auteurlabb-messagingcenter-service-messagethreads-listed

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the messageThreads data object itself.

The following JSON included in the payload illustrates the fullest representation of the messageThreads object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"messageThreads","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","messageThreads":[{"id":"ID","participantIds":"ID","subject":"String","relatedProjectId":"ID","isGroup":"Boolean","createdBy":"ID","lastMessageAt":"Date","threadStatus":"Enum","threadStatus_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","lastMessage":[{"senderId":"ID","content":"Text","sentAt":"Date","moderationStatus":"Enum","moderationStatus_idx":"Integer"},{},{}],"relatedProject":[{"title":"String","projectType":"Enum","projectType_idx":"Integer","ownerUserId":"ID","isPublic":"Boolean","approvalStatus":"Enum","approvalStatus_idx":"Integer"},{},{}]},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]}

Route Event messagethread-updated

Event topic : auteurlabb-messagingcenter-service-messagethread-updated

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the messageThread data object itself.

The following JSON included in the payload illustrates the fullest representation of the messageThread object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"messageThread","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"messageThread":{"id":"ID","participantIds":"ID","subject":"String","relatedProjectId":"ID","isGroup":"Boolean","createdBy":"ID","lastMessageAt":"Date","threadStatus":"Enum","threadStatus_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event message-created

Event topic : auteurlabb-messagingcenter-service-message-created

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the message data object itself.

The following JSON included in the payload illustrates the fullest representation of the message object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"message","method":"POST","action":"create","appVersion":"Version","rowCount":1,"message":{"id":"ID","threadId":"ID","senderId":"ID","content":"Text","sentAt":"Date","readByIds":"ID","moderationStatus":"Enum","moderationStatus_idx":"Integer","flaggedReason":"String","adminAction":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event message-retrived

Event topic : auteurlabb-messagingcenter-service-message-retrived

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the message data object itself.

The following JSON included in the payload illustrates the fullest representation of the message object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"message","method":"GET","action":"get","appVersion":"Version","rowCount":1,"message":{"id":"ID","threadId":"ID","senderId":"ID","content":"Text","sentAt":"Date","readByIds":"ID","moderationStatus":"Enum","moderationStatus_idx":"Integer","flaggedReason":"String","adminAction":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","thread":{"participantIds":"ID","subject":"String","relatedProjectId":"ID","threadStatus":"Enum","threadStatus_idx":"Integer"}}}

Route Event messages-listed

Event topic : auteurlabb-messagingcenter-service-messages-listed

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the messages data object itself.

The following JSON included in the payload illustrates the fullest representation of the messages object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"messages","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","messages":[{"id":"ID","threadId":"ID","senderId":"ID","content":"Text","sentAt":"Date","readByIds":"ID","moderationStatus":"Enum","moderationStatus_idx":"Integer","flaggedReason":"String","adminAction":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","thread":[{"participantIds":"ID","subject":"String","relatedProjectId":"ID","threadStatus":"Enum","threadStatus_idx":"Integer"},{},{}]},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]}

Route Event message-updated

Event topic : auteurlabb-messagingcenter-service-message-updated

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the message data object itself.

The following JSON included in the payload illustrates the fullest representation of the message object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"message","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"message":{"id":"ID","threadId":"ID","senderId":"ID","content":"Text","sentAt":"Date","readByIds":"ID","moderationStatus":"Enum","moderationStatus_idx":"Integer","flaggedReason":"String","adminAction":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event message-deleted

Event topic : auteurlabb-messagingcenter-service-message-deleted

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the message data object itself.

The following JSON included in the payload illustrates the fullest representation of the message object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"message","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"message":{"id":"ID","threadId":"ID","senderId":"ID","content":"Text","sentAt":"Date","readByIds":"ID","moderationStatus":"Enum","moderationStatus_idx":"Integer","flaggedReason":"String","adminAction":"String","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Index Event message-created

Event topic: elastic-index-auteurlabb_message-created

Event payload:

{"id":"ID","threadId":"ID","senderId":"ID","content":"Text","sentAt":"Date","readByIds":"ID","moderationStatus":"Enum","moderationStatus_idx":"Integer","flaggedReason":"String","adminAction":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event message-updated

Event topic: elastic-index-auteurlabb_message-created

Event payload:

{"id":"ID","threadId":"ID","senderId":"ID","content":"Text","sentAt":"Date","readByIds":"ID","moderationStatus":"Enum","moderationStatus_idx":"Integer","flaggedReason":"String","adminAction":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event message-deleted

Event topic: elastic-index-auteurlabb_message-deleted

Event payload:

{"id":"ID","threadId":"ID","senderId":"ID","content":"Text","sentAt":"Date","readByIds":"ID","moderationStatus":"Enum","moderationStatus_idx":"Integer","flaggedReason":"String","adminAction":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event message-extended

Event topic: elastic-index-auteurlabb_message-extended

Event payload:

{
  id: id,
  extends: {
    [extendName]: "Object",
    [extendName + "_count"]: "Number",
  },
}

Route Events

Route events are emitted following the successful execution of a route. While most routes perform CRUD (Create, Read, Update, Delete) operations on data objects, resulting in route events that closely resemble database events, there are distinctions worth noting. A single route execution might trigger multiple CRUD actions and ElasticSearch indexing operations. However, for those primarily concerned with the overarching business logic and its outcomes, listening to the consolidated route event, published once at the conclusion of the route’s execution, is more pertinent.

Moreover, routes often deliver aggregated data beyond the primary database object, catering to specific client needs. For instance, creating a data object via a route might not only return the entity’s data but also route-specific metrics, such as the executing user’s permissions related to the entity. Alternatively, a route might automatically generate default child entities following the creation of a parent object. Consequently, the route event encapsulates a unified dataset encompassing both the parent and its children, in contrast to individual events triggered for each entity created. Therefore, subscribing to route events can offer a richer, more contextually relevant set of information aligned with business logic.

The payload of a route event mirrors the REST response JSON of the route, providing a direct and comprehensive reflection of the data and metadata communicated to the client. This ensures that subscribers to route events receive a payload that encapsulates both the primary data involved and any additional information deemed significant at the business level, facilitating a deeper understanding and integration of the service’s functional outcomes.

Route Event messagethread-created

Event topic : auteurlabb-messagingcenter-service-messagethread-created

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the messageThread data object itself.

The following JSON included in the payload illustrates the fullest representation of the messageThread object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"messageThread","method":"POST","action":"create","appVersion":"Version","rowCount":1,"messageThread":{"id":"ID","participantIds":"ID","subject":"String","relatedProjectId":"ID","isGroup":"Boolean","createdBy":"ID","lastMessageAt":"Date","threadStatus":"Enum","threadStatus_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","lastMessage":[{"senderId":"ID","content":"Text","sentAt":"Date","moderationStatus":"Enum","moderationStatus_idx":"Integer"},{},{}],"relatedProject":{"title":"String","projectType":"Enum","projectType_idx":"Integer","ownerUserId":"ID","isPublic":"Boolean","approvalStatus":"Enum","approvalStatus_idx":"Integer"}}}

Route Event messagethread-retrived

Event topic : auteurlabb-messagingcenter-service-messagethread-retrived

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the messageThread data object itself.

The following JSON included in the payload illustrates the fullest representation of the messageThread object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"messageThread","method":"GET","action":"get","appVersion":"Version","rowCount":1,"messageThread":{"id":"ID","participantIds":"ID","subject":"String","relatedProjectId":"ID","isGroup":"Boolean","createdBy":"ID","lastMessageAt":"Date","threadStatus":"Enum","threadStatus_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","lastMessage":[{"senderId":"ID","content":"Text","sentAt":"Date","moderationStatus":"Enum","moderationStatus_idx":"Integer"},{},{}],"relatedProject":{"title":"String","projectType":"Enum","projectType_idx":"Integer","ownerUserId":"ID","isPublic":"Boolean","approvalStatus":"Enum","approvalStatus_idx":"Integer"}}}

Route Event messagethreads-listed

Event topic : auteurlabb-messagingcenter-service-messagethreads-listed

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the messageThreads data object itself.

The following JSON included in the payload illustrates the fullest representation of the messageThreads object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"messageThreads","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","messageThreads":[{"id":"ID","participantIds":"ID","subject":"String","relatedProjectId":"ID","isGroup":"Boolean","createdBy":"ID","lastMessageAt":"Date","threadStatus":"Enum","threadStatus_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","lastMessage":[{"senderId":"ID","content":"Text","sentAt":"Date","moderationStatus":"Enum","moderationStatus_idx":"Integer"},{},{}],"relatedProject":[{"title":"String","projectType":"Enum","projectType_idx":"Integer","ownerUserId":"ID","isPublic":"Boolean","approvalStatus":"Enum","approvalStatus_idx":"Integer"},{},{}]},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]}

Route Event messagethread-updated

Event topic : auteurlabb-messagingcenter-service-messagethread-updated

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the messageThread data object itself.

The following JSON included in the payload illustrates the fullest representation of the messageThread object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"messageThread","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"messageThread":{"id":"ID","participantIds":"ID","subject":"String","relatedProjectId":"ID","isGroup":"Boolean","createdBy":"ID","lastMessageAt":"Date","threadStatus":"Enum","threadStatus_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event message-created

Event topic : auteurlabb-messagingcenter-service-message-created

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the message data object itself.

The following JSON included in the payload illustrates the fullest representation of the message object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"message","method":"POST","action":"create","appVersion":"Version","rowCount":1,"message":{"id":"ID","threadId":"ID","senderId":"ID","content":"Text","sentAt":"Date","readByIds":"ID","moderationStatus":"Enum","moderationStatus_idx":"Integer","flaggedReason":"String","adminAction":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event message-retrived

Event topic : auteurlabb-messagingcenter-service-message-retrived

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the message data object itself.

The following JSON included in the payload illustrates the fullest representation of the message object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"message","method":"GET","action":"get","appVersion":"Version","rowCount":1,"message":{"id":"ID","threadId":"ID","senderId":"ID","content":"Text","sentAt":"Date","readByIds":"ID","moderationStatus":"Enum","moderationStatus_idx":"Integer","flaggedReason":"String","adminAction":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","thread":{"participantIds":"ID","subject":"String","relatedProjectId":"ID","threadStatus":"Enum","threadStatus_idx":"Integer"}}}

Route Event messages-listed

Event topic : auteurlabb-messagingcenter-service-messages-listed

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the messages data object itself.

The following JSON included in the payload illustrates the fullest representation of the messages object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"messages","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","messages":[{"id":"ID","threadId":"ID","senderId":"ID","content":"Text","sentAt":"Date","readByIds":"ID","moderationStatus":"Enum","moderationStatus_idx":"Integer","flaggedReason":"String","adminAction":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","thread":[{"participantIds":"ID","subject":"String","relatedProjectId":"ID","threadStatus":"Enum","threadStatus_idx":"Integer"},{},{}]},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]}

Route Event message-updated

Event topic : auteurlabb-messagingcenter-service-message-updated

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the message data object itself.

The following JSON included in the payload illustrates the fullest representation of the message object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"message","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"message":{"id":"ID","threadId":"ID","senderId":"ID","content":"Text","sentAt":"Date","readByIds":"ID","moderationStatus":"Enum","moderationStatus_idx":"Integer","flaggedReason":"String","adminAction":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event message-deleted

Event topic : auteurlabb-messagingcenter-service-message-deleted

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the message data object itself.

The following JSON included in the payload illustrates the fullest representation of the message object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"message","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"message":{"id":"ID","threadId":"ID","senderId":"ID","content":"Text","sentAt":"Date","readByIds":"ID","moderationStatus":"Enum","moderationStatus_idx":"Integer","flaggedReason":"String","adminAction":"String","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Copyright

All sources, documents and other digital materials are copyright of .

About Us

For more information please visit our website: .

. .


Data Objects

Service Design Specification - Object Design for messageThread

Service Design Specification - Object Design for messageThread

auteurlabb-messagingcenter-service documentation

Document Overview

This document outlines the object design for the messageThread model in our application. It includes details about the model’s attributes, relationships, and any specific validation or business logic that applies.

messageThread Data Object

Object Overview

Description: A thread (private or group) representing a conversation among platform users, optionally linked to a film project

This object represents a core data structure within the service and acts as the blueprint for database interaction, API generation, and business logic enforcement. It is defined using the ObjectSettings pattern, which governs its behavior, access control, caching strategy, and integration points with other systems such as Stripe and Redis.

Core Configuration

Composite Indexes

The index also defines a conflict resolution strategy for duplicate key violations.

When a new record would violate this composite index, the following action will be taken:

On Duplicate: throwError

An error will be thrown, preventing the insertion of conflicting data.

Properties Schema

Property Type Required Description
participantIds ID Yes IDs of all participants in the thread (must be 2+ for group, exactly 2 for 1-1)
subject String No Optional subject for the thread, required for group or flagged; for 1-on-1 may be null/empty.
relatedProjectId ID No (Optional) The project this thread is about.
isGroup Boolean Yes True if thread is a group chat, false if private 1-to-1 message.
createdBy ID Yes User who created the thread.
lastMessageAt Date Yes Timestamp of the last message in this thread (used for sorting).
threadStatus Enum Yes Status of the thread: active, archived, flagged.

Array Properties

participantIds

Array properties can hold multiple values and are indicated by the [] suffix in their type. Avoid using arrays in properties that are used for relations, as they will not work correctly. Note that using connection objects instead of arrays is recommended for relations, as they provide better performance and flexibility.

Default Values

Default values are automatically assigned to properties when a new object is created, if no value is provided in the request body. Since default values are applied on db level, they should be literal values, not expressions.If you want to use expressions, you can use transposed parameters in any business API to set default values dynamically.

Constant Properties

createdBy

Constant properties are defined to be immutable after creation, meaning they cannot be updated or changed once set. They are typically used for properties that should remain constant throughout the object’s lifecycle. A property is set to be constant if the Allow Update option is set to false.

Auto Update Properties

participantIds subject relatedProjectId isGroup lastMessageAt threadStatus

An update crud API created with the option Auto Params enabled will automatically update these properties with the provided values in the request body. If you want to update any property in your own business logic not by user input, you can set the Allow Auto Update option to false. These properties will be added to the update API’s body parameters and can be updated by the user if any value is provided in the request body.

Enum Properties

Enum properties are defined with a set of allowed values, ensuring that only valid options can be assigned to them. The enum options value will be stored as strings in the database, but when a data object is created an addtional property with the same name plus an idx suffix will be created, which will hold the index of the selected enum option. You can use the index property to sort by the enum value or when your enum options represent a sequence of values.

Elastic Search Indexing

participantIds relatedProjectId isGroup createdBy lastMessageAt threadStatus

Properties that are indexed in Elastic Search will be searchable via the Elastic Search API. While all properties are stored in the elastic search index of the data object, only those marked for Elastic Search indexing will be available for search queries.

Database Indexing

participantIds relatedProjectId isGroup createdBy lastMessageAt threadStatus

Properties that are indexed in the database will be optimized for query performance, allowing for faster data retrieval. Make a property indexed in the database if you want to use it frequently in query filters or sorting.

Relation Properties

participantIds relatedProjectId createdBy

Mindbricks supports relations between data objects, allowing you to define how objects are linked together. You can define relations in the data object properties, which will be used to create foreign key constraints in the database. For complex joins operations, Mindbricks supportsa BFF pattern, where you can view dynamic and static views based on Elastic Search Indexes. Use db level relations for simple one-to-one or one-to-many relationships, and use BFF views for complex joins that require multiple data objects to be joined together.

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

On Delete: Set Null Required: Yes

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

On Delete: Set Null Required: No

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

On Delete: Set Null Required: Yes

Session Data Properties

createdBy

Session data properties are used to store data that is specific to the user session, allowing for personalized experiences and temporary data storage. If a property is configured as session data, it will be automatically mapped to the related field in the user session during CRUD operations. Note that session data properties can not be mutated by the user, but only by the system.

This property is also used to store the owner of the session data, allowing for ownership checks and access control.

Filter Properties

participantIds relatedProjectId threadStatus

Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API’s that have “Auto Params” enabled.


Service Design Specification - Object Design for message

Service Design Specification - Object Design for message

auteurlabb-messagingcenter-service documentation

Document Overview

This document outlines the object design for the message model in our application. It includes details about the model’s attributes, relationships, and any specific validation or business logic that applies.

message Data Object

Object Overview

Description: A message sent in a thread between platform users, with moderation and delivery tracking.

This object represents a core data structure within the service and acts as the blueprint for database interaction, API generation, and business logic enforcement. It is defined using the ObjectSettings pattern, which governs its behavior, access control, caching strategy, and integration points with other systems such as Stripe and Redis.

Core Configuration

Composite Indexes

The index also defines a conflict resolution strategy for duplicate key violations.

When a new record would violate this composite index, the following action will be taken:

On Duplicate: doInsert

The new record will be inserted without checking for duplicates. This means that the composite index is designed for search purposes only.

Properties Schema

Property Type Required Description
threadId ID Yes The parent thread of this message.
senderId ID Yes User ID of the sender.
content Text Yes The actual message content (body).
sentAt Date Yes When the message was sent.
readByIds ID No User IDs who have read the message (for read receipts).
moderationStatus Enum Yes Moderation status: normal (default), flagged (pending review), or removed by admin/moderation.
flaggedReason String No Reason for message being flagged (set by admin or reporting workflow).
adminAction String No Admin/moderator action/note taken regarding this message (set only by admin).

Array Properties

readByIds

Array properties can hold multiple values and are indicated by the [] suffix in their type. Avoid using arrays in properties that are used for relations, as they will not work correctly. Note that using connection objects instead of arrays is recommended for relations, as they provide better performance and flexibility.

Default Values

Default values are automatically assigned to properties when a new object is created, if no value is provided in the request body. Since default values are applied on db level, they should be literal values, not expressions.If you want to use expressions, you can use transposed parameters in any business API to set default values dynamically.

Constant Properties

threadId senderId sentAt

Constant properties are defined to be immutable after creation, meaning they cannot be updated or changed once set. They are typically used for properties that should remain constant throughout the object’s lifecycle. A property is set to be constant if the Allow Update option is set to false.

Auto Update Properties

content readByIds moderationStatus flaggedReason adminAction

An update crud API created with the option Auto Params enabled will automatically update these properties with the provided values in the request body. If you want to update any property in your own business logic not by user input, you can set the Allow Auto Update option to false. These properties will be added to the update API’s body parameters and can be updated by the user if any value is provided in the request body.

Enum Properties

Enum properties are defined with a set of allowed values, ensuring that only valid options can be assigned to them. The enum options value will be stored as strings in the database, but when a data object is created an addtional property with the same name plus an idx suffix will be created, which will hold the index of the selected enum option. You can use the index property to sort by the enum value or when your enum options represent a sequence of values.

Elastic Search Indexing

threadId senderId sentAt readByIds moderationStatus

Properties that are indexed in Elastic Search will be searchable via the Elastic Search API. While all properties are stored in the elastic search index of the data object, only those marked for Elastic Search indexing will be available for search queries.

Database Indexing

threadId senderId sentAt moderationStatus

Properties that are indexed in the database will be optimized for query performance, allowing for faster data retrieval. Make a property indexed in the database if you want to use it frequently in query filters or sorting.

Relation Properties

threadId senderId readByIds

Mindbricks supports relations between data objects, allowing you to define how objects are linked together. You can define relations in the data object properties, which will be used to create foreign key constraints in the database. For complex joins operations, Mindbricks supportsa BFF pattern, where you can view dynamic and static views based on Elastic Search Indexes. Use db level relations for simple one-to-one or one-to-many relationships, and use BFF views for complex joins that require multiple data objects to be joined together.

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

On Delete: Set Null Required: Yes

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

On Delete: Set Null Required: Yes

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

On Delete: Set Null Required: No

Session Data Properties

senderId

Session data properties are used to store data that is specific to the user session, allowing for personalized experiences and temporary data storage. If a property is configured as session data, it will be automatically mapped to the related field in the user session during CRUD operations. Note that session data properties can not be mutated by the user, but only by the system.

This property is also used to store the owner of the session data, allowing for ownership checks and access control.

Formula Properties

sentAt

Formula properties are used to define calculated fields that derive their values from other properties or external data. These properties are automatically calculated based on the defined formula and can be used for dynamic data retrieval.

Filter Properties

threadId moderationStatus

Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API’s that have “Auto Params” enabled.


Business APIs

Business API Design Specification - Create Messagethread

Business API Design Specification - Create Messagethread

A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic.

While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized.

This document provides an in-depth explanation of the architectural design of the createMessageThread Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side.

Main Data Object and CRUD Operation

The createMessageThread Business API is designed to handle a create operation on the MessageThread data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

Create a new message thread (private or group). Can optionally link to a film project. Enforces participants count and role access.

API Frontend Description By The Backend Architect

For users to start a new conversation (private or group chat) with one or more participants (including themselves); optionally link the thread to a project, set subject (required for group/flagged threads only), subject can be empty for 1-to-1; lastMessageAt auto-set to creation time.

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The createMessageThread Business API includes a REST controller that can be triggered via the following route:

/v1/messagethreads

By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the Parameters section.

MCP Tool

REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This createMessageThread Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The createMessageThread Business API has 8 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client.

Business API parameters can be:

Regular Parameters

Name Type Required Default Location Data Path
messageThreadId ID No - body messageThreadId
Description: This id paremeter is used to create the data object with a given specific id. Leave null for automatic id.
participantIds ID Yes - body participantIds
Description: IDs of all participants in the thread (must be 2+ for group, exactly 2 for 1-1)
subject String No - body subject
Description: Optional subject for the thread, required for group or flagged; for 1-on-1 may be null/empty.
relatedProjectId ID No - body relatedProjectId
Description: (Optional) The project this thread is about.
isGroup Boolean Yes - body isGroup
Description: True if thread is a group chat, false if private 1-to-1 message.
createdBy ID Yes - session userId
Description: User who created the thread.
lastMessageAt Date Yes - body lastMessageAt
Description: Timestamp of the last message in this thread (used for sorting).
threadStatus Enum Yes - body threadStatus
Description: Status of the thread: active, archived, flagged.

Parameter Transformations

Some parameters are post-processed using transform scripts after being read from the request but before validation or workflow execution. Only parameters with a transform script are listed below.

No parameters are transformed in this API.

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the createMessageThread Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Data Clause

Defines custom field-value assignments used to modify or augment the default payload for create and update operations. These settings override values derived from the session or parameters if explicitly provided.", Note that a default data clause is always prepared by Mindbricks using data property settings, however any property in the data clause can be override by Data Clause Settings.

Custom Data Clause Override No custom data clause override configured

Actual Data Clause

The business api will use the following data clause. Note that any calculated value will be added to the data clause in the api manager.

{
  id: this.messageThreadId,
  participantIds: this.participantIds,
  subject: this.subject,
  relatedProjectId: this.relatedProjectId,
  isGroup: this.isGroup,
  createdBy: this.createdBy,
  lastMessageAt: this.lastMessageAt,
  threadStatus: this.threadStatus,
  isActive: true,
  _archivedAt: null,
}

Business Logic Workflow

[1] Step : startBusinessApi

Manager initializes context, populates session and request objects, prepares internal structures for parameter handling and workflow execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Manager reads input parameters, normalizes missing values, applies default type casting, and stores them in the API context.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Action : validateParticipantsCount

Action Type: FunctionCallAction

Validates participants: if isGroup - minimum 2; else exactly 2.

class Api {
  async validateParticipantsCount() {
    try {
      return runMScript(
        () => LIB.validateParticipantsCount(this.participantIds, this.isGroup),
        {
          path: "services[2].businessLogic[0].actions.functionCallActions[0].callScript",
        },
      );
    } catch (err) {
      console.error(
        "Error in FunctionCallAction validateParticipantsCount:",
        err,
      );
      throw err;
    }
  }
}

[4] Step : transposeParameters

Manager transforms parameters, computes derived values, flattens or remaps arrays/objects, and adjusts formats for downstream processing.


[5] Step : checkParameters

Manager executes built-in validations: required field checks, type enforcement, and basic business rules. Prevents operation if validation fails.


[6] Action : enforceParticipantRules

Action Type: ValidationAction

Thread must have at least two unique participants. For private, exactly two.

class Api {
  async enforceParticipantRules() {
    const isValid = runMScript(() => this.isParticipantsValid === true, {
      path: "services[2].businessLogic[0].actions.validationActions[0].validationScript",
    });

    if (!isValid) {
      throw new BadRequestError(
        "Invalid participant count: must be at least 2 for group or exactly 2 for private.",
      );
    }
    return isValid;
  }
}

[7] Step : checkBasicAuth

Manager performs authentication and authorization checks: verifies session, user roles, permissions, and tenant restrictions.

You can use the following settings to change some behavior of this step. authOptions

[8] Step : buildDataClause

Manager constructs the final data object for creation, fills auto-generated fields (IDs, timestamps, owner fields), and ensures schema consistency.

You can use the following settings to change some behavior of this step. dataClause

[9] Action : setInitialLastMessageAt

Action Type: AddToContextAction

Sets lastMessageAt to now.

class Api {
  async setInitialLastMessageAt() {
    try {
      this["lastMessageAt"] = runMScript(() => new Date(), {
        path: "services[2].businessLogic[0].actions.addToContextActions[0].context[0].contextValue",
      });

      return true;
    } catch (error) {
      console.error("AddToContextAction error:", error);
      throw error;
    }
  }
}

[10] Step : mainCreateOperation

Manager executes the database insert operation, updates indexes/caches, and triggers internal post-processing like linked default records.


[11] Step : buildOutput

Manager shapes the response: masks sensitive fields, resolves linked references, and formats output according to API contract.


[12] Step : sendResponse

Manager sends the response to the client and finalizes internal tasks like flushing logs or updating session state.


[13] Step : raiseApiEvent

Manager triggers API-level events (Kafka, WebSocket, async workflows) as the final internal step.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The createMessageThread api has got 6 regular client parameters

Parameter Type Required Population
participantIds ID true request.body?.[“participantIds”]
subject String false request.body?.[“subject”]
relatedProjectId ID false request.body?.[“relatedProjectId”]
isGroup Boolean true request.body?.[“isGroup”]
lastMessageAt Date true request.body?.[“lastMessageAt”]
threadStatus Enum true request.body?.[“threadStatus”]

REST Request

To access the api you can use the REST controller with the path POST /v1/messagethreads

  axios({
    method: 'POST',
    url: '/v1/messagethreads',
    data: {
            participantIds:"ID",  
            subject:"String",  
            relatedProjectId:"ID",  
            isGroup:"Boolean",  
            lastMessageAt:"Date",  
            threadStatus:"Enum",  
    
    },
    params: {
    
        }
  });

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the messageThread object in the respones. However, some properties may be omitted based on the object’s internal logic.

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "messageThread",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"messageThread": {
		"id": "ID",
		"participantIds": "ID",
		"subject": "String",
		"relatedProjectId": "ID",
		"isGroup": "Boolean",
		"createdBy": "ID",
		"lastMessageAt": "Date",
		"threadStatus": "Enum",
		"threadStatus_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"lastMessage": [
			{
				"senderId": "ID",
				"content": "Text",
				"sentAt": "Date",
				"moderationStatus": "Enum",
				"moderationStatus_idx": "Integer"
			},
			{},
			{}
		],
		"relatedProject": {
			"title": "String",
			"projectType": "Enum",
			"projectType_idx": "Integer",
			"ownerUserId": "ID",
			"isPublic": "Boolean",
			"approvalStatus": "Enum",
			"approvalStatus_idx": "Integer"
		}
	}
}

Business API Design Specification - Get Messagethread

Business API Design Specification - Get Messagethread

A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic.

While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized.

This document provides an in-depth explanation of the architectural design of the getMessageThread Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side.

Main Data Object and CRUD Operation

The getMessageThread Business API is designed to handle a get operation on the MessageThread data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

Fetch a message thread and last message; only participants or admin may retrieve.

API Frontend Description By The Backend Architect

For thread detail/conversation load: returns thread and its related context (last message, project info). Enforces access: only participants and admins.

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The getMessageThread Business API includes a REST controller that can be triggered via the following route:

/v1/messagethreads/:messageThreadId

By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the Parameters section.

MCP Tool

REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This getMessageThread Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The getMessageThread Business API has 1 parameter that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client.

Business API parameters can be:

Regular Parameters

Name Type Required Default Location Data Path
messageThreadId ID Yes - urlpath messageThreadId
Description: This id paremeter is used to query the required data object.

Parameter Transformations

Some parameters are post-processed using transform scripts after being read from the request but before validation or workflow execution. Only parameters with a transform script are listed below.

No parameters are transformed in this API.

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the getMessageThread Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Select Clause

Specifies which fields will be selected from the main data object during a get or list operation. Leave blank to select all properties. This applies only to get and list type APIs.",

``

Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({$and:[{id:this.messageThreadId},{isActive:true}]}), {"path":"services[2].businessLogic[1].whereClause.fullWhereClause"})

Get Options

Use these options to set get specific settings.

setAsRead: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed.

No setAsread field-value pair is configured.

Business Logic Workflow

[1] Step : startBusinessApi

Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Action : accessCheckThreadParticipantOrAdmin

Action Type: FunctionCallAction

Only participants or admin/superAdmin may fetch the thread.

class Api {
  async accessCheckThreadParticipantOrAdmin() {
    try {
      return runMScript(
        () => LIB.isThreadAccessibleByUser(this, this.session),
        {
          path: "services[2].businessLogic[1].actions.functionCallActions[0].callScript",
        },
      );
    } catch (err) {
      console.error(
        "Error in FunctionCallAction accessCheckThreadParticipantOrAdmin:",
        err,
      );
      throw err;
    }
  }
}

[3] Step : readParameters

Extracts parameters from request and Redis, applies defaults, and writes them to context.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[4] Step : transposeParameters

Executes parameter transformation scripts, applies type coercion, merges derived values, and reshapes inputs for downstream milestones.


[5] Step : checkParameters

Validates required and custom parameters, enforcing business-specific rules and constraints.


[6] Action : enforceThreadAccess

Action Type: ValidationAction

Must be participant or admin/superAdmin to access this thread.

class Api {
  async enforceThreadAccess() {
    if (this.checkAbsolute()) return true;

    const isValid = runMScript(() => this.isAllowed === true, {
      path: "services[2].businessLogic[1].actions.validationActions[0].validationScript",
    });

    if (!isValid) {
      throw new ForbiddenError(
        "Forbidden: only thread participants or admins may access this thread.",
      );
    }
    return isValid;
  }
}

[7] Step : checkBasicAuth

Performs login, role, and permission checks, and applies dynamic object-level access rules.

You can use the following settings to change some behavior of this step. authOptions

[8] Step : buildWhereClause

Builds the WHERE clause for fetching the object and applies additional scoped filters if configured.

You can use the following settings to change some behavior of this step. whereClause

[9] Step : mainGetOperation

Executes the database fetch, retrieves the object, and stores it in context for enrichment or further checks.

You can use the following settings to change some behavior of this step. selectClause, getOptions

[10] Step : checkInstance

Performs instance-level validations, such as ownership, existence, or access conditions.


[11] Step : buildOutput

Assembles the response from the object, applies masking, formatting, and injects additional metadata if needed.


[12] Step : sendResponse

Delivers the response to the controller for client delivery.


[13] Step : raiseApiEvent

Triggers optional API-level events after workflow completion, sending messages to integrations like Kafka if configured.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The getMessageThread api has got 1 regular client parameter

Parameter Type Required Population
messageThreadId ID true request.params?.[“messageThreadId”]

REST Request

To access the api you can use the REST controller with the path GET /v1/messagethreads/:messageThreadId

  axios({
    method: 'GET',
    url: `/v1/messagethreads/${messageThreadId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the messageThread object in the respones. However, some properties may be omitted based on the object’s internal logic.

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "messageThread",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"messageThread": {
		"id": "ID",
		"participantIds": "ID",
		"subject": "String",
		"relatedProjectId": "ID",
		"isGroup": "Boolean",
		"createdBy": "ID",
		"lastMessageAt": "Date",
		"threadStatus": "Enum",
		"threadStatus_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"lastMessage": [
			{
				"senderId": "ID",
				"content": "Text",
				"sentAt": "Date",
				"moderationStatus": "Enum",
				"moderationStatus_idx": "Integer"
			},
			{},
			{}
		],
		"relatedProject": {
			"title": "String",
			"projectType": "Enum",
			"projectType_idx": "Integer",
			"ownerUserId": "ID",
			"isPublic": "Boolean",
			"approvalStatus": "Enum",
			"approvalStatus_idx": "Integer"
		}
	}
}

Business API Design Specification - List Messagethreads

Business API Design Specification - List Messagethreads

A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic.

While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized.

This document provides an in-depth explanation of the architectural design of the listMessageThreads Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side.

Main Data Object and CRUD Operation

The listMessageThreads Business API is designed to handle a list operation on the MessageThread data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

List threads for current user (participantIds contains session userId), or all threads for admin. Filters: by project, thread status, participant, search by subject. Sorted by lastMessageAt desc.

API Frontend Description By The Backend Architect

Returns conversation list for chat inbox. By default lists threads where session user is a participant, with last message for display. Admins can filter/status for moderation, filter by related project for context. Supports pagination.

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The listMessageThreads Business API includes a REST controller that can be triggered via the following route:

/v1/messagethreads

By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the Parameters section.

MCP Tool

REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This listMessageThreads Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The listMessageThreads Business API has 4 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client.

Business API parameters can be:

Filter Parameters

The listMessageThreads api supports 4 optional filter parameters for filtering list results using URL query parameters. These parameters are only available for list type APIs.

participantId Filter

Type: ID (Array Property)
Description: IDs of all participants in the thread (must be 2+ for group, exactly 2 for 1-1)
Location: Query Parameter

Usage:

Non-Array Property:

Examples:

// Get records with a specific ID
GET /v1/messagethreads?participantId=550e8400-e29b-41d4-a716-446655440000

// Get records with multiple IDs (use multiple parameters)
GET /v1/messagethreads?participantId=550e8400-e29b-41d4-a716-446655440000&participantId=660e8400-e29b-41d4-a716-446655440001

// Get records without this field
GET /v1/messagethreads?participantId=null

Array Property:

Examples:

// Check if array contains a specific ID (default)
GET /v1/messagethreads?participantId=123&participantId_op=contains

// Check if arrays have overlapping IDs (use multiple parameters)
GET /v1/messagethreads?participantId=123&participantId=456&participantId_op=overlap

participantId_op Filter

Type: String
Description: Operator for filtering array property “participantIds”. Use “contains” to check if array contains the value, or “overlap” to check if arrays have common elements.
Location: Query Parameter

Usage:

Non-Array Property (Case-Insensitive Partial Matching):

Examples:

// Find records with "john" in the field (case-insensitive partial match)
GET /v1/messagethreads?participantId_op=john
// Matches: "John", "Johnny", "johnson", "McJohn", etc.

// Find records with multiple values (use multiple parameters)
GET /v1/messagethreads?participantId_op=laptop&participantId_op=phone&participantId_op=tablet
// Matches records containing "laptop", "phone", or "tablet" anywhere in the field

// Find records without this field
GET /v1/messagethreads?participantId_op=null

relatedProjectId Filter

Type: ID
Description: (Optional) The project this thread is about.
Location: Query Parameter

Usage:

Non-Array Property:

Examples:

// Get records with a specific ID
GET /v1/messagethreads?relatedProjectId=550e8400-e29b-41d4-a716-446655440000

// Get records with multiple IDs (use multiple parameters)
GET /v1/messagethreads?relatedProjectId=550e8400-e29b-41d4-a716-446655440000&relatedProjectId=660e8400-e29b-41d4-a716-446655440001

// Get records without this field
GET /v1/messagethreads?relatedProjectId=null

threadStatus Filter

Type: Enum
Description: Status of the thread: active, archived, flagged.
Location: Query Parameter

Usage:

Examples:

// Get records with specific enum value
GET /v1/messagethreads?threadStatus=active

// Get records with multiple enum values (use multiple parameters)
GET /v1/messagethreads?threadStatus=active&threadStatus=pending

// Get records without this field
GET /v1/messagethreads?threadStatus=null

Parameter Transformations

Some parameters are post-processed using transform scripts after being read from the request but before validation or workflow execution. Only parameters with a transform script are listed below.

No parameters are transformed in this API.

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the listMessageThreads Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Select Clause

Specifies which fields will be selected from the main data object during a get or list operation. Leave blank to select all properties. This applies only to get and list type APIs.",

``

Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has a fullWhereClause setting :

this.session.roleId==='superAdmin'||this.session.roleId==='admin' ? { isActive: true } : {participantIds: { $overlap: [this.session.userId] }}

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({$and:[this.session.roleId==='superAdmin'||this.session.roleId==='admin' ? { isActive: true } : {participantIds: { $overlap: [this.session.userId] }},{isActive:true}]}), {"path":"services[2].businessLogic[2].whereClause.fullWhereClause"})

List Options

Defines list-specific options including filtering logic, default sorting, and result customization for APIs that return multiple records.

List Sort By Sort order definitions for the result set. Multiple fields can be provided with direction (asc/desc).

[ lastMessageAt desc ]

List Group By Grouping definitions for the result set. This is typically used for visual or report-based grouping.

The list is not grouped.

setAsRead: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed.

No setAsread field-value pair is configured.

Permission Filter Optional filter that applies permission constraints dynamically based on session or object roles. So that the list items are filtered by the user’s OBAC or ABAC permissions.

Permission filter is not active at the moment. Follow Mindbricks updates to be able to use it.

Pagination Options

Contains settings to configure pagination behavior for list APIs. Includes options like page size, offset, cursor support, and total count inclusion.

Business Logic Workflow

[1] Step : startBusinessApi

Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Reads request and Redis parameters, applies defaults, and writes them to context for downstream processing.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Transforms and normalizes parameters, derives dependent values, and reshapes inputs for the main list query.


[4] Step : checkParameters

Executes validation logic on required and custom parameters, enforcing business rules and cross-field consistency.


[5] Step : checkBasicAuth

Performs role-based access checks and applies dynamic membership or session-based restrictions.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildWhereClause

Constructs the main query WHERE clause and applies optional filters or scoped access controls.

You can use the following settings to change some behavior of this step. whereClause

[7] Step : mainListOperation

Executes the paginated database query, retrieves the list, and stores results in context for enrichment.

You can use the following settings to change some behavior of this step. selectClause, listOptions, paginationOptions

[8] Step : buildOutput

Assembles the list response, sanitizes sensitive fields, applies transformations, and injects extra context if needed.


[9] Step : sendResponse

Sends the paginated list to the client through the controller.


[10] Step : raiseApiEvent

Triggers optional post-workflow events, such as Kafka messages, logs, or system notifications.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The listMessageThreads api has 4 filter parameters available for filtering list results. See the Filter Parameters section above for detailed usage examples.

Filter Parameter Type Array Property Description
participantId ID Yes IDs of all participants in the thread (must be 2+ for group, exactly 2 for 1-1)
participantId_op String No Operator for filtering array property “participantIds”. Use “contains” to check if array contains the value, or “overlap” to check if arrays have common elements.
relatedProjectId ID No (Optional) The project this thread is about.
threadStatus Enum No Status of the thread: active, archived, flagged.

REST Request

To access the api you can use the REST controller with the path GET /v1/messagethreads

  axios({
    method: 'GET',
    url: '/v1/messagethreads',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section for usage examples)
        // participantId: '<value>' // Filter by participantId
        // participantId_op: '<value>' // Filter by participantId_op
        // relatedProjectId: '<value>' // Filter by relatedProjectId
        // threadStatus: '<value>' // Filter by threadStatus
            }
  });

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the messageThreads object in the respones. However, some properties may be omitted based on the object’s internal logic.

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "messageThreads",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"messageThreads": [
		{
			"id": "ID",
			"participantIds": "ID",
			"subject": "String",
			"relatedProjectId": "ID",
			"isGroup": "Boolean",
			"createdBy": "ID",
			"lastMessageAt": "Date",
			"threadStatus": "Enum",
			"threadStatus_idx": "Integer",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID",
			"lastMessage": [
				{
					"senderId": "ID",
					"content": "Text",
					"sentAt": "Date",
					"moderationStatus": "Enum",
					"moderationStatus_idx": "Integer"
				},
				{},
				{}
			],
			"relatedProject": [
				{
					"title": "String",
					"projectType": "Enum",
					"projectType_idx": "Integer",
					"ownerUserId": "ID",
					"isPublic": "Boolean",
					"approvalStatus": "Enum",
					"approvalStatus_idx": "Integer"
				},
				{},
				{}
			]
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Business API Design Specification - Update Messagethread

Business API Design Specification - Update Messagethread

A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic.

While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized.

This document provides an in-depth explanation of the architectural design of the updateMessageThread Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side.

Main Data Object and CRUD Operation

The updateMessageThread Business API is designed to handle a update operation on the MessageThread data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

Update thread (subject, status, participants for group). Only thread creator, participants (for subject/archival), or admin can update. Only admin can set status=flagged.

API Frontend Description By The Backend Architect

Allows editing of thread subject, status (archival/flag for moderation), or for admin actions; participants cannot update thread participants unless admin/group owner. All updates are logged for audit. Only admin may set flagged status.

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The updateMessageThread Business API includes a REST controller that can be triggered via the following route:

/v1/messagethreads/:messageThreadId

By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the Parameters section.

MCP Tool

REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This updateMessageThread Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The updateMessageThread Business API has 7 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client.

Business API parameters can be:

Regular Parameters

Name Type Required Default Location Data Path
messageThreadId ID Yes - urlpath messageThreadId
Description: This id paremeter is used to select the required data object that will be updated
participantIds ID No - body participantIds
Description: IDs of all participants in the thread (must be 2+ for group, exactly 2 for 1-1)
subject String No - body subject
Description: Optional subject for the thread, required for group or flagged; for 1-on-1 may be null/empty.
relatedProjectId ID No - body relatedProjectId
Description: (Optional) The project this thread is about.
isGroup Boolean No - body isGroup
Description: True if thread is a group chat, false if private 1-to-1 message.
lastMessageAt Date No - body lastMessageAt
Description: Timestamp of the last message in this thread (used for sorting).
threadStatus Enum No - body threadStatus
Description: Status of the thread: active, archived, flagged.

Parameter Transformations

Some parameters are post-processed using transform scripts after being read from the request but before validation or workflow execution. Only parameters with a transform script are listed below.

No parameters are transformed in this API.

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the updateMessageThread Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({$and:[{id:this.messageThreadId},{isActive:true}]}), {"path":"services[2].businessLogic[3].whereClause.fullWhereClause"})

Data Clause

Defines custom field-value assignments used to modify or augment the default payload for create and update operations. These settings override values derived from the session or parameters if explicitly provided.", Note that a default data clause is always prepared by Mindbricks using data property settings, however any property in the data clause can be override by Data Clause Settings.

An update data clause populates all update-allowed properties of a data object, however the null properties (that are not provided by client) are ignored in db layer.

Custom Data Clause Override No custom data clause override configured

Actual Data Clause

The business api will use the following data clause. Note that any calculated value will be added to the data clause in the api manager.

{
  participantIds: this.participantIds ? this.participantIds : 
                 ( this.participantIds_remove ? sequelize.fn('array_remove', sequelize.col('participantIds'), this.participantIds_remove) : (this.participantIds_append ? sequelize.fn('array_append', sequelize.col('participantIds'), this.participantIds_append) : undefined)) ,
  subject: this.subject,
  relatedProjectId: this.relatedProjectId,
  isGroup: this.isGroup,
  lastMessageAt: this.lastMessageAt,
  threadStatus: this.threadStatus,
}

Business Logic Workflow

[1] Step : startBusinessApi

Manager initializes context, prepares request and session objects, and sets up internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Action : threadUpdatePermissionCheck

Action Type: FunctionCallAction

Checks that user is thread creator, admin, or participant for certain fields; only admin allowed to set flagged.

class Api {
  async threadUpdatePermissionCheck() {
    try {
      return runMScript(
        () => LIB.canUpdateThread(this, this.session, this.thread),
        {
          path: "services[2].businessLogic[3].actions.functionCallActions[0].callScript",
        },
      );
    } catch (err) {
      console.error(
        "Error in FunctionCallAction threadUpdatePermissionCheck:",
        err,
      );
      throw err;
    }
  }
}

[3] Step : readParameters

Manager reads parameters from the request or Redis, applies defaults, and writes them into context for downstream milestones.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[4] Step : transposeParameters

Manager executes parameter transform scripts and derives any helper values or reshaped payloads into the context.


[5] Step : checkParameters

Manager validates required parameters, checks ID formats (UUID/ObjectId), and ensures all preconditions for update are met.


[6] Action : enforceThreadUpdateAccess

Action Type: ValidationAction

Only allowed updater may modify thread.

class Api {
  async enforceThreadUpdateAccess() {
    if (this.checkAbsolute()) return true;

    const isValid = runMScript(() => this.canUpdate === true, {
      path: "services[2].businessLogic[3].actions.validationActions[0].validationScript",
    });

    if (!isValid) {
      throw new ForbiddenError(
        "Forbidden: you are not permitted to update thread.",
      );
    }
    return isValid;
  }
}

[7] Step : checkBasicAuth

Manager performs login verification, role, and permission checks, enforcing tenant and access rules before update.

You can use the following settings to change some behavior of this step. authOptions

[8] Step : buildWhereClause

Manager constructs the WHERE clause used to identify the record to update, applying ownership and parent checks if necessary.

You can use the following settings to change some behavior of this step. whereClause

[9] Step : fetchInstance

Manager fetches the existing record from the database and writes it to the context for validation or enrichment.


[10] Step : checkInstance

Manager performs instance-level validations, including ownership, existence, lock status, or other pre-update checks.


[11] Step : buildDataClause

Manager prepares the data clause for the update, applying transformations or enhancements before persisting.

You can use the following settings to change some behavior of this step. dataClause

[12] Step : mainUpdateOperation

Manager executes the update operation with the WHERE and data clauses. Database-level events are raised if configured.


[13] Step : buildOutput

Manager assembles the response object from the update result, masking fields or injecting additional metadata.


[14] Step : sendResponse

Manager sends the response back to the controller for delivery to the client.


[15] Step : raiseApiEvent

Manager triggers API-level events, sending relevant messages to Kafka or other integrations if configured.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The updateMessageThread api has got 7 regular client parameters

Parameter Type Required Population
messageThreadId ID true request.params?.[“messageThreadId”]
participantIds ID false request.body?.[“participantIds”]
subject String false request.body?.[“subject”]
relatedProjectId ID false request.body?.[“relatedProjectId”]
isGroup Boolean false request.body?.[“isGroup”]
lastMessageAt Date false request.body?.[“lastMessageAt”]
threadStatus Enum false request.body?.[“threadStatus”]

REST Request

To access the api you can use the REST controller with the path PATCH /v1/messagethreads/:messageThreadId

  axios({
    method: 'PATCH',
    url: `/v1/messagethreads/${messageThreadId}`,
    data: {
            participantIds:"ID",  
            subject:"String",  
            relatedProjectId:"ID",  
            isGroup:"Boolean",  
            lastMessageAt:"Date",  
            threadStatus:"Enum",  
    
    },
    params: {
    
        }
  });

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the messageThread object in the respones. However, some properties may be omitted based on the object’s internal logic.

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "messageThread",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"messageThread": {
		"id": "ID",
		"participantIds": "ID",
		"subject": "String",
		"relatedProjectId": "ID",
		"isGroup": "Boolean",
		"createdBy": "ID",
		"lastMessageAt": "Date",
		"threadStatus": "Enum",
		"threadStatus_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Business API Design Specification - Create Message

Business API Design Specification - Create Message

A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic.

While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized.

This document provides an in-depth explanation of the architectural design of the createMessage Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side.

Main Data Object and CRUD Operation

The createMessage Business API is designed to handle a create operation on the Message data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

Send a message (post) in a thread. Only thread participants allowed. Thread lastMessageAt is updated.

API Frontend Description By The Backend Architect

Sends a message in an existing conversation (thread). Access check: only participants may send. Sets senderId, sentAt. Notifies via events. Supports message content, moderation default = normal. Marks thread lastMessageAt for inbox sort.

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The createMessage Business API includes a REST controller that can be triggered via the following route:

/v1/messages

By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the Parameters section.

MCP Tool

REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This createMessage Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The createMessage Business API has 9 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client.

Business API parameters can be:

Regular Parameters

Name Type Required Default Location Data Path
messageId ID No - body messageId
Description: This id paremeter is used to create the data object with a given specific id. Leave null for automatic id.
threadId ID Yes - body threadId
Description: The parent thread of this message.
senderId ID Yes - session userId
Description: User ID of the sender.
content Text Yes - body content
Description: The actual message content (body).
sentAt Date Yes - body sentAt
Description: When the message was sent.
readByIds ID No - body readByIds
Description: User IDs who have read the message (for read receipts).
moderationStatus Enum Yes - body moderationStatus
Description: Moderation status: normal (default), flagged (pending review), or removed by admin/moderation.
flaggedReason String No - body flaggedReason
Description: Reason for message being flagged (set by admin or reporting workflow).
adminAction String No - body adminAction
Description: Admin/moderator action/note taken regarding this message (set only by admin).

Parameter Transformations

Some parameters are post-processed using transform scripts after being read from the request but before validation or workflow execution. Only parameters with a transform script are listed below.

No parameters are transformed in this API.

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the createMessage Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Data Clause

Defines custom field-value assignments used to modify or augment the default payload for create and update operations. These settings override values derived from the session or parameters if explicitly provided.", Note that a default data clause is always prepared by Mindbricks using data property settings, however any property in the data clause can be override by Data Clause Settings.

Custom Data Clause Override No custom data clause override configured

Actual Data Clause

The business api will use the following data clause. Note that any calculated value will be added to the data clause in the api manager.

{
  id: this.messageId,
  threadId: this.threadId,
  senderId: this.senderId,
  content: this.content,
  sentAt: this.sentAt,
  readByIds: this.readByIds,
  moderationStatus: this.moderationStatus,
  flaggedReason: this.flaggedReason,
  adminAction: this.adminAction,
  isActive: true,
  _archivedAt: null,
}

Business Logic Workflow

[1] Step : startBusinessApi

Manager initializes context, populates session and request objects, prepares internal structures for parameter handling and workflow execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Action : fetchThreadForMessage

Action Type: FetchObjectAction

Fetches thread for access check/update.

class Api {
  async fetchThreadForMessage() {
    // Fetch Object on childObject messageThread

    const userQuery = {
      $and: [
        {
          id: runMScript(() => this.messageThreadId, {
            path: "services[2].businessLogic[4].actions.fetchObjectActions[0].matchValue",
          }),
        },
        { isActive: true },
      ],
    };
    const { convertUserQueryToSequelizeQuery } = require("common");
    const scriptQuery = convertUserQueryToSequelizeQuery(userQuery);

    // get object from db
    const data = await getMessageThreadByQuery(scriptQuery);

    if (!data) {
      throw new NotFoundError("errMsg_FethcedObjectNotFound:messageThread");
    }

    return data;
  }
}

[3] Step : readParameters

Manager reads input parameters, normalizes missing values, applies default type casting, and stores them in the API context.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[4] Action : checkParticipantForSend

Action Type: FunctionCallAction

Checks sender is in participantIds for thread.

class Api {
  async checkParticipantForSend() {
    try {
      return await runMScript(
        () =>
          (async () =>
            (async () => {
              const t = await db.getMessageThreadById(this.messageThreadId);
              this.targetThread = this.targetThread || t;
              return !!(
                t &&
                Array.isArray(t.participantIds) &&
                t.participantIds.includes(this.session.userId)
              );
            })())(),
        {
          path: "services[2].businessLogic[4].actions.functionCallActions[0].callScript",
        },
      );
    } catch (err) {
      console.error(
        "Error in FunctionCallAction checkParticipantForSend:",
        err,
      );
      throw err;
    }
  }
}

[5] Step : transposeParameters

Manager transforms parameters, computes derived values, flattens or remaps arrays/objects, and adjusts formats for downstream processing.


[6] Step : checkParameters

Manager executes built-in validations: required field checks, type enforcement, and basic business rules. Prevents operation if validation fails.


[7] Action : enforceParticipantForSend

Action Type: ValidationAction

Sender must be a thread participant.

class Api {
  async enforceParticipantForSend() {
    if (this.checkAbsolute()) return true;

    const isValid = runMScript(() => this.canSend === true, {
      path: "services[2].businessLogic[4].actions.validationActions[0].validationScript",
    });

    if (!isValid) {
      throw new ForbiddenError(
        "Forbidden: only thread participants may send messages.",
      );
    }
    return isValid;
  }
}

[8] Step : checkBasicAuth

Manager performs authentication and authorization checks: verifies session, user roles, permissions, and tenant restrictions.

You can use the following settings to change some behavior of this step. authOptions

[9] Step : buildDataClause

Manager constructs the final data object for creation, fills auto-generated fields (IDs, timestamps, owner fields), and ensures schema consistency.

You can use the following settings to change some behavior of this step. dataClause

[10] Step : mainCreateOperation

Manager executes the database insert operation, updates indexes/caches, and triggers internal post-processing like linked default records.


[11] Action : updateThreadLastMessageAt

Action Type: UpdateCrudAction

Update thread lastMessageAt after message send.

class Api {
  async updateThreadLastMessageAt() {
    // Aggregated Update Operation on childObject messageThread

    const params = {
      lastMessageAt: runMScript(() => this.sentAt, {
        path: "services[2].businessLogic[4].actions.updateCrudActions[0].dataClause[0].dataValue",
      }),
    };
    const userQuery = runMScript(() => ({ id: this.messageThreadId }), {
      path: "services[2].businessLogic[4].actions.updateCrudActions[0].whereClause",
    });

    const { convertUserQueryToSequelizeQuery } = require("common");
    const query = convertUserQueryToSequelizeQuery(userQuery);

    const result = await updateMessageThreadByQuery(params, query, this);
    if (!result) return null;

    const resultArray = Array.isArray(result) ? result : [result];
    // if updated record is in main data update main data
    if (this.dbResult) {
      for (const item of resultArray) {
        if (item.id == this.dbResult.id) {
          Object.assign(this.dbResult, item);
          this.message = this.dbResult;
        }
      }
    }
    if (resultArray.length == 0) return null;
    if (resultArray.length == 1) return resultArray[0];
    return resultArray;
  }
}

[12] Step : buildOutput

Manager shapes the response: masks sensitive fields, resolves linked references, and formats output according to API contract.


[13] Step : sendResponse

Manager sends the response to the client and finalizes internal tasks like flushing logs or updating session state.


[14] Step : raiseApiEvent

Manager triggers API-level events (Kafka, WebSocket, async workflows) as the final internal step.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The createMessage api has got 6 regular client parameters

Parameter Type Required Population
threadId ID true request.body?.[“threadId”]
content Text true request.body?.[“content”]
readByIds ID false request.body?.[“readByIds”]
moderationStatus Enum true request.body?.[“moderationStatus”]
flaggedReason String false request.body?.[“flaggedReason”]
adminAction String false request.body?.[“adminAction”]

REST Request

To access the api you can use the REST controller with the path POST /v1/messages

  axios({
    method: 'POST',
    url: '/v1/messages',
    data: {
            threadId:"ID",  
            content:"Text",  
            readByIds:"ID",  
            moderationStatus:"Enum",  
            flaggedReason:"String",  
            adminAction:"String",  
    
    },
    params: {
    
        }
  });

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the message object in the respones. However, some properties may be omitted based on the object’s internal logic.

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "message",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"message": {
		"id": "ID",
		"threadId": "ID",
		"senderId": "ID",
		"content": "Text",
		"sentAt": "Date",
		"readByIds": "ID",
		"moderationStatus": "Enum",
		"moderationStatus_idx": "Integer",
		"flaggedReason": "String",
		"adminAction": "String",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Business API Design Specification - Get Message

Business API Design Specification - Get Message

A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic.

While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized.

This document provides an in-depth explanation of the architectural design of the getMessage Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side.

Main Data Object and CRUD Operation

The getMessage Business API is designed to handle a get operation on the Message data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

Fetch a single message, thread participant or admin only.

API Frontend Description By The Backend Architect

Load message (for thread/conversation display or moderation). Only allowed for participant or admin/superAdmin.

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The getMessage Business API includes a REST controller that can be triggered via the following route:

/v1/messages/:messageId

By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the Parameters section.

MCP Tool

REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This getMessage Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The getMessage Business API has 1 parameter that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client.

Business API parameters can be:

Regular Parameters

Name Type Required Default Location Data Path
messageId ID Yes - urlpath messageId
Description: This id paremeter is used to query the required data object.

Parameter Transformations

Some parameters are post-processed using transform scripts after being read from the request but before validation or workflow execution. Only parameters with a transform script are listed below.

No parameters are transformed in this API.

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the getMessage Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Select Clause

Specifies which fields will be selected from the main data object during a get or list operation. Leave blank to select all properties. This applies only to get and list type APIs.",

``

Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({$and:[{id:this.messageId},{isActive:true}]}), {"path":"services[2].businessLogic[5].whereClause.fullWhereClause"})

Get Options

Use these options to set get specific settings.

setAsRead: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed.

No setAsread field-value pair is configured.

Business Logic Workflow

[1] Step : startBusinessApi

Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Action : fetchThreadForMessageGet

Action Type: FetchObjectAction

Get parent thread for access check.

class Api {
  async fetchThreadForMessageGet() {
    // Fetch Object on childObject messageThread

    const userQuery = {
      $and: [
        {
          id: runMScript(() => this.threadId, {
            path: "services[2].businessLogic[5].actions.fetchObjectActions[0].matchValue",
          }),
        },
        { isActive: true },
      ],
    };
    const { convertUserQueryToSequelizeQuery } = require("common");
    const scriptQuery = convertUserQueryToSequelizeQuery(userQuery);

    // get object from db
    const data = await getMessageThreadByQuery(scriptQuery);

    if (!data) {
      throw new NotFoundError("errMsg_FethcedObjectNotFound:messageThread");
    }

    return data;
  }
}

[3] Step : readParameters

Extracts parameters from request and Redis, applies defaults, and writes them to context.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[4] Action : checkCanViewMessage

Action Type: FunctionCallAction

Checks user access to message (participant or admin).

class Api {
  async checkCanViewMessage() {
    try {
      return runMScript(
        () => LIB.isThreadAccessibleByUser(this.targetThread, this.session),
        {
          path: "services[2].businessLogic[5].actions.functionCallActions[0].callScript",
        },
      );
    } catch (err) {
      console.error("Error in FunctionCallAction checkCanViewMessage:", err);
      throw err;
    }
  }
}

[5] Step : transposeParameters

Executes parameter transformation scripts, applies type coercion, merges derived values, and reshapes inputs for downstream milestones.


[6] Step : checkParameters

Validates required and custom parameters, enforcing business-specific rules and constraints.


[7] Action : enforceMessageViewAccess

Action Type: ValidationAction

Only thread participant or admin may view message.

class Api {
  async enforceMessageViewAccess() {
    if (this.checkAbsolute()) return true;

    const isValid = runMScript(() => this.canView === true, {
      path: "services[2].businessLogic[5].actions.validationActions[0].validationScript",
    });

    if (!isValid) {
      throw new ForbiddenError("Forbidden: not allowed to view this message.");
    }
    return isValid;
  }
}

[8] Step : checkBasicAuth

Performs login, role, and permission checks, and applies dynamic object-level access rules.

You can use the following settings to change some behavior of this step. authOptions

[9] Step : buildWhereClause

Builds the WHERE clause for fetching the object and applies additional scoped filters if configured.

You can use the following settings to change some behavior of this step. whereClause

[10] Step : mainGetOperation

Executes the database fetch, retrieves the object, and stores it in context for enrichment or further checks.

You can use the following settings to change some behavior of this step. selectClause, getOptions

[11] Step : checkInstance

Performs instance-level validations, such as ownership, existence, or access conditions.


[12] Step : buildOutput

Assembles the response from the object, applies masking, formatting, and injects additional metadata if needed.


[13] Step : sendResponse

Delivers the response to the controller for client delivery.


[14] Step : raiseApiEvent

Triggers optional API-level events after workflow completion, sending messages to integrations like Kafka if configured.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The getMessage api has got 1 regular client parameter

Parameter Type Required Population
messageId ID true request.params?.[“messageId”]

REST Request

To access the api you can use the REST controller with the path GET /v1/messages/:messageId

  axios({
    method: 'GET',
    url: `/v1/messages/${messageId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the message object in the respones. However, some properties may be omitted based on the object’s internal logic.

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "message",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"message": {
		"id": "ID",
		"threadId": "ID",
		"senderId": "ID",
		"content": "Text",
		"sentAt": "Date",
		"readByIds": "ID",
		"moderationStatus": "Enum",
		"moderationStatus_idx": "Integer",
		"flaggedReason": "String",
		"adminAction": "String",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"thread": {
			"participantIds": "ID",
			"subject": "String",
			"relatedProjectId": "ID",
			"threadStatus": "Enum",
			"threadStatus_idx": "Integer"
		}
	}
}

Business API Design Specification - List Messages

Business API Design Specification - List Messages

A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic.

While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized.

This document provides an in-depth explanation of the architectural design of the listMessages Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side.

Main Data Object and CRUD Operation

The listMessages Business API is designed to handle a list operation on the Message data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

List messages for a thread (or per filter by participant/project/moderation). Participant or admin only.

API Frontend Description By The Backend Architect

Conversation message list for a given thread, or admin-moderated message audit. Enables filter/sort/paginate (newest last). Only participant of the thread or admin can list.

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The listMessages Business API includes a REST controller that can be triggered via the following route:

/v1/messages

By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the Parameters section.

MCP Tool

REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This listMessages Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The listMessages Business API has 2 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client.

Business API parameters can be:

Filter Parameters

The listMessages api supports 2 optional filter parameters for filtering list results using URL query parameters. These parameters are only available for list type APIs.

threadId Filter

Type: ID
Description: The parent thread of this message.
Location: Query Parameter

Usage:

Non-Array Property:

Examples:

// Get records with a specific ID
GET /v1/messages?threadId=550e8400-e29b-41d4-a716-446655440000

// Get records with multiple IDs (use multiple parameters)
GET /v1/messages?threadId=550e8400-e29b-41d4-a716-446655440000&threadId=660e8400-e29b-41d4-a716-446655440001

// Get records without this field
GET /v1/messages?threadId=null

moderationStatus Filter

Type: Enum
Description: Moderation status: normal (default), flagged (pending review), or removed by admin/moderation.
Location: Query Parameter

Usage:

Examples:

// Get records with specific enum value
GET /v1/messages?moderationStatus=active

// Get records with multiple enum values (use multiple parameters)
GET /v1/messages?moderationStatus=active&moderationStatus=pending

// Get records without this field
GET /v1/messages?moderationStatus=null

Parameter Transformations

Some parameters are post-processed using transform scripts after being read from the request but before validation or workflow execution. Only parameters with a transform script are listed below.

No parameters are transformed in this API.

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the listMessages Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Select Clause

Specifies which fields will be selected from the main data object during a get or list operation. Leave blank to select all properties. This applies only to get and list type APIs.",

``

Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has a fullWhereClause setting :

{ isActive: true }

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({$and:[{ isActive: true },{isActive:true}]}), {"path":"services[2].businessLogic[6].whereClause.fullWhereClause"})

List Options

Defines list-specific options including filtering logic, default sorting, and result customization for APIs that return multiple records.

List Sort By Sort order definitions for the result set. Multiple fields can be provided with direction (asc/desc).

[ sentAt asc ]

List Group By Grouping definitions for the result set. This is typically used for visual or report-based grouping.

The list is not grouped.

setAsRead: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed.

No setAsread field-value pair is configured.

Permission Filter Optional filter that applies permission constraints dynamically based on session or object roles. So that the list items are filtered by the user’s OBAC or ABAC permissions.

Permission filter is not active at the moment. Follow Mindbricks updates to be able to use it.

Pagination Options

Contains settings to configure pagination behavior for list APIs. Includes options like page size, offset, cursor support, and total count inclusion.

Business Logic Workflow

[1] Step : startBusinessApi

Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Reads request and Redis parameters, applies defaults, and writes them to context for downstream processing.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Transforms and normalizes parameters, derives dependent values, and reshapes inputs for the main list query.


[4] Step : checkParameters

Executes validation logic on required and custom parameters, enforcing business rules and cross-field consistency.


[5] Step : checkBasicAuth

Performs role-based access checks and applies dynamic membership or session-based restrictions.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildWhereClause

Constructs the main query WHERE clause and applies optional filters or scoped access controls.

You can use the following settings to change some behavior of this step. whereClause

[7] Step : mainListOperation

Executes the paginated database query, retrieves the list, and stores results in context for enrichment.

You can use the following settings to change some behavior of this step. selectClause, listOptions, paginationOptions

[8] Step : buildOutput

Assembles the list response, sanitizes sensitive fields, applies transformations, and injects extra context if needed.


[9] Step : sendResponse

Sends the paginated list to the client through the controller.


[10] Step : raiseApiEvent

Triggers optional post-workflow events, such as Kafka messages, logs, or system notifications.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The listMessages api has 2 filter parameters available for filtering list results. See the Filter Parameters section above for detailed usage examples.

Filter Parameter Type Array Property Description
threadId ID No The parent thread of this message.
moderationStatus Enum No Moderation status: normal (default), flagged (pending review), or removed by admin/moderation.

REST Request

To access the api you can use the REST controller with the path GET /v1/messages

  axios({
    method: 'GET',
    url: '/v1/messages',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section for usage examples)
        // threadId: '<value>' // Filter by threadId
        // moderationStatus: '<value>' // Filter by moderationStatus
            }
  });

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the messages object in the respones. However, some properties may be omitted based on the object’s internal logic.

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "messages",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"messages": [
		{
			"id": "ID",
			"threadId": "ID",
			"senderId": "ID",
			"content": "Text",
			"sentAt": "Date",
			"readByIds": "ID",
			"moderationStatus": "Enum",
			"moderationStatus_idx": "Integer",
			"flaggedReason": "String",
			"adminAction": "String",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID",
			"thread": [
				{
					"participantIds": "ID",
					"subject": "String",
					"relatedProjectId": "ID",
					"threadStatus": "Enum",
					"threadStatus_idx": "Integer"
				},
				{},
				{}
			]
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Business API Design Specification - Update Message

Business API Design Specification - Update Message

A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic.

While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized.

This document provides an in-depth explanation of the architectural design of the updateMessage Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side.

Main Data Object and CRUD Operation

The updateMessage Business API is designed to handle a update operation on the Message data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

Update a message’s content (by sender & only before flagged/removed) or moderation fields (admin only).

API Frontend Description By The Backend Architect

Sender may edit own message content if not yet flagged/removed and within allowed time window (if desired). Only admin may set moderationStatus, flaggedReason, adminAction fields.

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The updateMessage Business API includes a REST controller that can be triggered via the following route:

/v1/messages/:messageId

By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the Parameters section.

MCP Tool

REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This updateMessage Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The updateMessage Business API has 6 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client.

Business API parameters can be:

Regular Parameters

Name Type Required Default Location Data Path
messageId ID Yes - urlpath messageId
Description: This id paremeter is used to select the required data object that will be updated
content Text No - body content
Description: The actual message content (body).
readByIds ID No - body readByIds
Description: User IDs who have read the message (for read receipts).
moderationStatus Enum No - body moderationStatus
Description: Moderation status: normal (default), flagged (pending review), or removed by admin/moderation.
flaggedReason String No - body flaggedReason
Description: Reason for message being flagged (set by admin or reporting workflow).
adminAction String No - body adminAction
Description: Admin/moderator action/note taken regarding this message (set only by admin).

Parameter Transformations

Some parameters are post-processed using transform scripts after being read from the request but before validation or workflow execution. Only parameters with a transform script are listed below.

No parameters are transformed in this API.

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the updateMessage Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({$and:[{id:this.messageId},{isActive:true}]}), {"path":"services[2].businessLogic[7].whereClause.fullWhereClause"})

Data Clause

Defines custom field-value assignments used to modify or augment the default payload for create and update operations. These settings override values derived from the session or parameters if explicitly provided.", Note that a default data clause is always prepared by Mindbricks using data property settings, however any property in the data clause can be override by Data Clause Settings.

An update data clause populates all update-allowed properties of a data object, however the null properties (that are not provided by client) are ignored in db layer.

Custom Data Clause Override No custom data clause override configured

Actual Data Clause

The business api will use the following data clause. Note that any calculated value will be added to the data clause in the api manager.

{
  content: this.content,
  readByIds: this.readByIds ? this.readByIds : 
                 ( this.readByIds_remove ? sequelize.fn('array_remove', sequelize.col('readByIds'), this.readByIds_remove) : (this.readByIds_append ? sequelize.fn('array_append', sequelize.col('readByIds'), this.readByIds_append) : undefined)) ,
  moderationStatus: this.moderationStatus,
  flaggedReason: this.flaggedReason,
  adminAction: this.adminAction,
}

Business Logic Workflow

[1] Step : startBusinessApi

Manager initializes context, prepares request and session objects, and sets up internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Action : getMessageForUpdate

Action Type: FetchObjectAction

Load message instance for access check.

class Api {
  async getMessageForUpdate() {
    // Fetch Object on childObject message

    const userQuery = {
      $and: [
        {
          id: runMScript(() => this.id, {
            path: "services[2].businessLogic[7].actions.fetchObjectActions[0].matchValue",
          }),
        },
        { isActive: true },
      ],
    };
    const { convertUserQueryToSequelizeQuery } = require("common");
    const scriptQuery = convertUserQueryToSequelizeQuery(userQuery);

    // get object from db
    const data = await getMessageByQuery(scriptQuery);

    if (!data) {
      throw new NotFoundError("errMsg_FethcedObjectNotFound:message");
    }

    return data;
  }
}

[3] Step : readParameters

Manager reads parameters from the request or Redis, applies defaults, and writes them into context for downstream milestones.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[4] Action : validateUpdatePermitted

Action Type: FunctionCallAction

Checks permission: sender can edit content if not flagged/removed, admin may set moderation fields.

class Api {
  async validateUpdatePermitted() {
    try {
      return runMScript(
        () => LIB.canUpdateMessage(this.session, this.msgInstance, this),
        {
          path: "services[2].businessLogic[7].actions.functionCallActions[0].callScript",
        },
      );
    } catch (err) {
      console.error(
        "Error in FunctionCallAction validateUpdatePermitted:",
        err,
      );
      throw err;
    }
  }
}

[5] Step : transposeParameters

Manager executes parameter transform scripts and derives any helper values or reshaped payloads into the context.


[6] Step : checkParameters

Manager validates required parameters, checks ID formats (UUID/ObjectId), and ensures all preconditions for update are met.


[7] Action : enforceMessageEditAccess

Action Type: ValidationAction

Only sender may update content, only admin updates moderation fields.

class Api {
  async enforceMessageEditAccess() {
    if (this.checkAbsolute()) return true;

    const isValid = runMScript(() => this.canEdit === true, {
      path: "services[2].businessLogic[7].actions.validationActions[0].validationScript",
    });

    if (!isValid) {
      throw new ForbiddenError(
        "Forbidden: not allowed to update this message.",
      );
    }
    return isValid;
  }
}

[8] Step : checkBasicAuth

Manager performs login verification, role, and permission checks, enforcing tenant and access rules before update.

You can use the following settings to change some behavior of this step. authOptions

[9] Step : buildWhereClause

Manager constructs the WHERE clause used to identify the record to update, applying ownership and parent checks if necessary.

You can use the following settings to change some behavior of this step. whereClause

[10] Step : fetchInstance

Manager fetches the existing record from the database and writes it to the context for validation or enrichment.


[11] Step : checkInstance

Manager performs instance-level validations, including ownership, existence, lock status, or other pre-update checks.


[12] Step : buildDataClause

Manager prepares the data clause for the update, applying transformations or enhancements before persisting.

You can use the following settings to change some behavior of this step. dataClause

[13] Step : mainUpdateOperation

Manager executes the update operation with the WHERE and data clauses. Database-level events are raised if configured.


[14] Step : buildOutput

Manager assembles the response object from the update result, masking fields or injecting additional metadata.


[15] Step : sendResponse

Manager sends the response back to the controller for delivery to the client.


[16] Step : raiseApiEvent

Manager triggers API-level events, sending relevant messages to Kafka or other integrations if configured.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The updateMessage api has got 6 regular client parameters

Parameter Type Required Population
messageId ID true request.params?.[“messageId”]
content Text false request.body?.[“content”]
readByIds ID false request.body?.[“readByIds”]
moderationStatus Enum false request.body?.[“moderationStatus”]
flaggedReason String false request.body?.[“flaggedReason”]
adminAction String false request.body?.[“adminAction”]

REST Request

To access the api you can use the REST controller with the path PATCH /v1/messages/:messageId

  axios({
    method: 'PATCH',
    url: `/v1/messages/${messageId}`,
    data: {
            content:"Text",  
            readByIds:"ID",  
            moderationStatus:"Enum",  
            flaggedReason:"String",  
            adminAction:"String",  
    
    },
    params: {
    
        }
  });

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the message object in the respones. However, some properties may be omitted based on the object’s internal logic.

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "message",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"message": {
		"id": "ID",
		"threadId": "ID",
		"senderId": "ID",
		"content": "Text",
		"sentAt": "Date",
		"readByIds": "ID",
		"moderationStatus": "Enum",
		"moderationStatus_idx": "Integer",
		"flaggedReason": "String",
		"adminAction": "String",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Business API Design Specification - Delete Message

Business API Design Specification - Delete Message

A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic.

While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized.

This document provides an in-depth explanation of the architectural design of the deleteMessage Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side.

Main Data Object and CRUD Operation

The deleteMessage Business API is designed to handle a delete operation on the Message data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

Delete message (by sender - if unflagged, or admin at any time).

API Frontend Description By The Backend Architect

Sender may remove their own unflagged/unmoderated message; admin may remove (hard/soft) any message (for moderation cleanup). All deletes are soft by default (isActive=false).

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The deleteMessage Business API includes a REST controller that can be triggered via the following route:

/v1/messages/:messageId

By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the Parameters section.

MCP Tool

REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This deleteMessage Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The deleteMessage Business API has 1 parameter that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client.

Business API parameters can be:

Regular Parameters

Name Type Required Default Location Data Path
messageId ID Yes - urlpath messageId
Description: This id paremeter is used to select the required data object that will be deleted

Parameter Transformations

Some parameters are post-processed using transform scripts after being read from the request but before validation or workflow execution. Only parameters with a transform script are listed below.

No parameters are transformed in this API.

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the deleteMessage Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({$and:[{id:this.messageId},{isActive:true}]}), {"path":"services[2].businessLogic[8].whereClause.fullWhereClause"})

Delete Options

Use these options to set delete specific settings.

useSoftDelete: true If true, the record will be marked as deleted (isActive: false) instead of removed. The implementation depends on the data object’s soft delete configuration.

Business Logic Workflow

[1] Step : startBusinessApi

Manager initializes context, prepares request/session objects, and sets up internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Action : getMessageForDelete

Action Type: FetchObjectAction

Get message for delete access check.

class Api {
  async getMessageForDelete() {
    // Fetch Object on childObject message

    const userQuery = {
      $and: [
        {
          id: runMScript(() => this.id, {
            path: "services[2].businessLogic[8].actions.fetchObjectActions[0].matchValue",
          }),
        },
        { isActive: true },
      ],
    };
    const { convertUserQueryToSequelizeQuery } = require("common");
    const scriptQuery = convertUserQueryToSequelizeQuery(userQuery);

    // get object from db
    const data = await getMessageByQuery(scriptQuery);

    if (!data) {
      throw new NotFoundError("errMsg_FethcedObjectNotFound:message");
    }

    return data;
  }
}

[3] Step : readParameters

Manager reads and normalizes parameters, applies defaults, and stores them in the context for downstream steps.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[4] Action : validateDeletePermitted

Action Type: FunctionCallAction

Checks sender or admin permission to delete.

class Api {
  async validateDeletePermitted() {
    try {
      return runMScript(
        () => LIB.canDeleteMessage(this.session, this.msgInstance),
        {
          path: "services[2].businessLogic[8].actions.functionCallActions[0].callScript",
        },
      );
    } catch (err) {
      console.error(
        "Error in FunctionCallAction validateDeletePermitted:",
        err,
      );
      throw err;
    }
  }
}

[5] Step : transposeParameters

Manager executes parameter transform scripts, computes derived values, and remaps objects or arrays as needed for later processing.


[6] Step : checkParameters

Manager runs built-in validations including required field checks, type enforcement, and deletion preconditions. Stops execution if validation fails.


[7] Action : enforceMessageDeleteAccess

Action Type: ValidationAction

Sender (unflagged/unmoderated) or admin required.

class Api {
  async enforceMessageDeleteAccess() {
    if (this.checkAbsolute()) return true;

    const isValid = runMScript(() => this.canDelete === true, {
      path: "services[2].businessLogic[8].actions.validationActions[0].validationScript",
    });

    if (!isValid) {
      throw new ForbiddenError(
        "Forbidden: not allowed to delete this message.",
      );
    }
    return isValid;
  }
}

[8] Step : checkBasicAuth

Manager validates session, user roles, permissions, and tenant-specific access rules to enforce basic auth restrictions.

You can use the following settings to change some behavior of this step. authOptions

[9] Step : buildWhereClause

Manager generates the query conditions, applies ownership and parent checks, and ensures the clause is correct for the delete operation.

You can use the following settings to change some behavior of this step. whereClause

[10] Step : fetchInstance

Manager fetches the target record, applies filters from WHERE clause, and writes the instance to the context for further checks.


[11] Step : checkInstance

Manager performs object-level validations such as lock status, soft-delete eligibility, and multi-step approval enforcement.


[12] Step : mainDeleteOperation

Manager executes the delete query, updates related indexes/caches, and handles soft/hard delete logic according to configuration.

You can use the following settings to change some behavior of this step. deleteOptions

[13] Step : buildOutput

Manager shapes the response payload, masks sensitive fields, and formats related cleanup results for output.


[14] Step : sendResponse

Manager delivers the response to the client and finalizes any temporary internal structures.


[15] Step : raiseApiEvent

Manager triggers asynchronous API events, notifies queues or streams, and performs final cleanup for the workflow.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The deleteMessage api has got 1 regular client parameter

Parameter Type Required Population
messageId ID true request.params?.[“messageId”]

REST Request

To access the api you can use the REST controller with the path DELETE /v1/messages/:messageId

  axios({
    method: 'DELETE',
    url: `/v1/messages/${messageId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the message object in the respones. However, some properties may be omitted based on the object’s internal logic.

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "message",
	"method": "DELETE",
	"action": "delete",
	"appVersion": "Version",
	"rowCount": 1,
	"message": {
		"id": "ID",
		"threadId": "ID",
		"senderId": "ID",
		"content": "Text",
		"sentAt": "Date",
		"readByIds": "ID",
		"moderationStatus": "Enum",
		"moderationStatus_idx": "Integer",
		"flaggedReason": "String",
		"adminAction": "String",
		"isActive": false,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Service Library - messagingCenter

Service Library - messagingCenter

This document provides a complete reference of the custom code library for the messagingCenter service. It includes all library functions, edge functions with their REST endpoints, templates, and assets.

Library Functions

Library functions are reusable modules available to all business APIs and other custom code within the service via require("lib/<moduleName>").

validateParticipantsCount.js

module.exports = function validateParticipantsCount(participantIds,isGroup) {
  if (!Array.isArray(participantIds)) return false;
  const uniqueCount = new Set(participantIds).size;
  if (isGroup) {
    return uniqueCount >= 2;
  } else {
    return uniqueCount === 2;
  }
};

isThreadAccessibleByUser.js

module.exports = function isThreadAccessibleByUser(threadOrThreadCtx,session) {
  if(!threadOrThreadCtx||!session||!session.userId) return false;
  if(['superAdmin','admin'].includes(session.roleId)) return true;
  if(Array.isArray(threadOrThreadCtx.participantIds))
    return threadOrThreadCtx.participantIds.includes(session.userId);
  return false;
};

canUpdateThread.js

module.exports = function canUpdateThread(apiContext,session,thread) {
  if(!session||!thread) return false;
  if(['superAdmin','admin'].includes(session.roleId)) return true;
  if(thread.createdBy===session.userId) return true;
  if(Array.isArray(thread.participantIds)&&thread.participantIds.includes(session.userId)){
    // Only allow subject/threadStatus update for participants
    return true;
  }
  return false;
};

isMessageSendAllowed.js

module.exports = function isMessageSendAllowed(userId,thread) {
  if(!thread||!userId) return false;
  if(Array.isArray(thread.participantIds)){
    return thread.participantIds.includes(userId);
  }
  return false;
};

canUpdateMessage.js

module.exports = function canUpdateMessage(session,msgInstance,updateInput) {
  if(!session||!msgInstance) return false;
  const isAdmin = ['superAdmin','admin'].includes(session.roleId);
  const upFields = Object.keys(updateInput||{});
  // Only admin can update moderationStatus, flaggedReason, adminAction
  if(
    upFields.some(f=>['moderationStatus','flaggedReason','adminAction'].includes(f))
    && !isAdmin
  )return false;
  // Only sender can update content if not flagged/removed
  if(upFields.includes('content')) {
    if(msgInstance.senderId===session.userId && ['normal'].includes(msgInstance.moderationStatus)){
      return true;
    }
    return false;
  }
  return isAdmin; // allow if admin
};

canDeleteMessage.js

module.exports = function canDeleteMessage(session,msgInstance) {
  if(!session||!msgInstance) return false;
  if(['superAdmin','admin'].includes(session.roleId)) return true;
  if(msgInstance.senderId===session.userId && ['normal'].includes(msgInstance.moderationStatus)){
    return true;
  }
  return false;
};

This document was generated from the service library configuration and should be kept in sync with design changes.


ModerationAdmin Service

Service Design Specification

Service Design Specification

auteurlabb-moderationadmin-service documentation Version: 1.0.11

Scope

This document provides a structured architectural overview of the moderationAdmin microservice, detailing its configuration, data model, authorization logic, business rules, and API design. It has been automatically generated based on the service definition within Mindbricks, ensuring that the information reflects the source of truth used during code generation and deployment.

The document is intended to serve multiple audiences:

Note for Frontend Developers: While this document is valuable for understanding business logic and data interactions, please refer to the Service API Documentation for endpoint-level specifications and integration details.

Note for Backend Developers: Since the code for this service is automatically generated by Mindbricks, you typically won’t need to implement or modify it manually. However, this document is especially valuable when you’re building other services—whether within Mindbricks or externally—that need to interact with or depend on this service. It provides a clear reference to the service’s data contracts, business rules, and API structure, helping ensure compatibility and correct integration.

ModerationAdmin Service Settings

Handles approval workflows for studios, investors, and projects; facilitates platform content moderation, user suspensions, and records all related admin actions for audit and compliance.

Service Overview

This service is configured to listen for HTTP requests on port 3002, serving both the main API interface and default administrative endpoints.

The following routes are available by default:

The service uses a PostgreSQL database for data storage, with the database name set to auteurlabb-moderationadmin-service.

This service is accessible via the following environment-specific URLs:

Authentication & Security

This service requires user authentication for access. It supports both JWT and RSA-based authentication mechanisms, ensuring secure user sessions and data integrity. If a crud route also is configured to require login, it will check a valid JWT token in the request query/header/bearer/cookie. If the token is valid, it will extract the user information from the token and make the fetched session data available in the request context.

Service Data Objects

The service uses a PostgreSQL database for data storage, with the database name set to auteurlabb-moderationadmin-service.

Data deletion is managed using a soft delete strategy. Instead of removing records from the database, they are flagged as inactive by setting the isActive field to false.

Object Name Description Public Access
approvalRequest Tracks approval workflows for studios, investors, and submitted projects. Each request points to a specific entity and is reviewed by admin. accessPrivate
reportLog Logs moderation/reporting actions: for project, message, or user. Each report includes status, type, review/action info. accessPrivate
suspensionRecord Admin action to suspend or lift suspension on a user. Each record logs a suspension/lift action for audit/compliance. accessPrivate
auditLog Generic audit log for all admin/moderation actions across services/objects for compliance and traceability. accessPrivate

approvalRequest Data Object

Object Overview

Description: Tracks approval workflows for studios, investors, and submitted projects. Each request points to a specific entity and is reviewed by admin.

This object represents a core data structure within the service and acts as the blueprint for database interaction, API generation, and business logic enforcement. It is defined using the ObjectSettings pattern, which governs its behavior, access control, caching strategy, and integration points with other systems such as Stripe and Redis.

Core Configuration

Composite Indexes

The index also defines a conflict resolution strategy for duplicate key violations.

When a new record would violate this composite index, the following action will be taken:

On Duplicate: throwError

An error will be thrown, preventing the insertion of conflicting data.

Properties Schema

Property Type Required Description
targetType Enum Yes Type of entity being approved (studio, investor, project)
targetId ID Yes ID of entity being approved (user or project, depending on type)
requestedAt Date Yes Request creation time
requestedByUserId ID Yes User ID who created the request
status Enum Yes Approval status: pending/approved/rejected
reviewedAt Date No Date/time request reviewed
reviewedByUserId ID No Admin userId who reviewed the request
adminNote String No Review note left by admin.

Default Values

Default values are automatically assigned to properties when a new object is created, if no value is provided in the request body. Since default values are applied on db level, they should be literal values, not expressions.If you want to use expressions, you can use transposed parameters in any business API to set default values dynamically.

Always Create with Default Values

Some of the default values are set to be always used when creating a new object, even if the property value is provided in the request body. It ensures that the property is always initialized with a default value when the object is created.

Constant Properties

targetType targetId requestedAt requestedByUserId

Constant properties are defined to be immutable after creation, meaning they cannot be updated or changed once set. They are typically used for properties that should remain constant throughout the object’s lifecycle. A property is set to be constant if the Allow Update option is set to false.

Auto Update Properties

targetType targetId requestedAt requestedByUserId status reviewedAt reviewedByUserId adminNote

An update crud API created with the option Auto Params enabled will automatically update these properties with the provided values in the request body. If you want to update any property in your own business logic not by user input, you can set the Allow Auto Update option to false. These properties will be added to the update API’s body parameters and can be updated by the user if any value is provided in the request body.

Enum Properties

Enum properties are defined with a set of allowed values, ensuring that only valid options can be assigned to them. The enum options value will be stored as strings in the database, but when a data object is created an addtional property with the same name plus an idx suffix will be created, which will hold the index of the selected enum option. You can use the index property to sort by the enum value or when your enum options represent a sequence of values.

Elastic Search Indexing

targetType targetId requestedAt requestedByUserId status reviewedAt reviewedByUserId

Properties that are indexed in Elastic Search will be searchable via the Elastic Search API. While all properties are stored in the elastic search index of the data object, only those marked for Elastic Search indexing will be available for search queries.

Database Indexing

targetType targetId requestedByUserId status reviewedByUserId

Properties that are indexed in the database will be optimized for query performance, allowing for faster data retrieval. Make a property indexed in the database if you want to use it frequently in query filters or sorting.

Relation Properties

requestedByUserId reviewedByUserId

Mindbricks supports relations between data objects, allowing you to define how objects are linked together. You can define relations in the data object properties, which will be used to create foreign key constraints in the database. For complex joins operations, Mindbricks supportsa BFF pattern, where you can view dynamic and static views based on Elastic Search Indexes. Use db level relations for simple one-to-one or one-to-many relationships, and use BFF views for complex joins that require multiple data objects to be joined together.

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

On Delete: Set Null Required: Yes

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

On Delete: Set Null Required: No

Session Data Properties

requestedByUserId

Session data properties are used to store data that is specific to the user session, allowing for personalized experiences and temporary data storage. If a property is configured as session data, it will be automatically mapped to the related field in the user session during CRUD operations. Note that session data properties can not be mutated by the user, but only by the system.

This property is also used to store the owner of the session data, allowing for ownership checks and access control.

Filter Properties

targetType targetId status

Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API’s that have “Auto Params” enabled.

reportLog Data Object

Object Overview

Description: Logs moderation/reporting actions: for project, message, or user. Each report includes status, type, review/action info.

This object represents a core data structure within the service and acts as the blueprint for database interaction, API generation, and business logic enforcement. It is defined using the ObjectSettings pattern, which governs its behavior, access control, caching strategy, and integration points with other systems such as Stripe and Redis.

Core Configuration

Properties Schema

Property Type Required Description
contentType Enum Yes Type of content being reported: project/message/user
contentId ID Yes ID of the reported content (project ID, message ID, user ID)
reportType String Yes Nature of report (abuse, spam, copyright, etc.)
reportedByUserId ID Yes ID of user reporting
reportedAt Date Yes Report creation timestamp
reviewStatus Enum Yes Open/closed/ignored
reviewAction String No Action taken by admin (removed, warned, etc.) or note
actionedByUserId ID No Admin making the moderation action
actionedAt Date No Time of moderation action

Default Values

Default values are automatically assigned to properties when a new object is created, if no value is provided in the request body. Since default values are applied on db level, they should be literal values, not expressions.If you want to use expressions, you can use transposed parameters in any business API to set default values dynamically.

Always Create with Default Values

Some of the default values are set to be always used when creating a new object, even if the property value is provided in the request body. It ensures that the property is always initialized with a default value when the object is created.

Constant Properties

contentType contentId reportType reportedByUserId reportedAt

Constant properties are defined to be immutable after creation, meaning they cannot be updated or changed once set. They are typically used for properties that should remain constant throughout the object’s lifecycle. A property is set to be constant if the Allow Update option is set to false.

Auto Update Properties

contentType contentId reportType reportedByUserId reportedAt reviewStatus reviewAction actionedByUserId actionedAt

An update crud API created with the option Auto Params enabled will automatically update these properties with the provided values in the request body. If you want to update any property in your own business logic not by user input, you can set the Allow Auto Update option to false. These properties will be added to the update API’s body parameters and can be updated by the user if any value is provided in the request body.

Enum Properties

Enum properties are defined with a set of allowed values, ensuring that only valid options can be assigned to them. The enum options value will be stored as strings in the database, but when a data object is created an addtional property with the same name plus an idx suffix will be created, which will hold the index of the selected enum option. You can use the index property to sort by the enum value or when your enum options represent a sequence of values.

Elastic Search Indexing

contentType contentId reportType reportedByUserId reportedAt reviewStatus actionedByUserId actionedAt

Properties that are indexed in Elastic Search will be searchable via the Elastic Search API. While all properties are stored in the elastic search index of the data object, only those marked for Elastic Search indexing will be available for search queries.

Database Indexing

contentType contentId reportedByUserId reviewStatus actionedByUserId

Properties that are indexed in the database will be optimized for query performance, allowing for faster data retrieval. Make a property indexed in the database if you want to use it frequently in query filters or sorting.

Relation Properties

reportedByUserId actionedByUserId

Mindbricks supports relations between data objects, allowing you to define how objects are linked together. You can define relations in the data object properties, which will be used to create foreign key constraints in the database. For complex joins operations, Mindbricks supportsa BFF pattern, where you can view dynamic and static views based on Elastic Search Indexes. Use db level relations for simple one-to-one or one-to-many relationships, and use BFF views for complex joins that require multiple data objects to be joined together.

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

On Delete: Set Null Required: Yes

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

On Delete: Set Null Required: No

Session Data Properties

reportedByUserId

Session data properties are used to store data that is specific to the user session, allowing for personalized experiences and temporary data storage. If a property is configured as session data, it will be automatically mapped to the related field in the user session during CRUD operations. Note that session data properties can not be mutated by the user, but only by the system.

This property is also used to store the owner of the session data, allowing for ownership checks and access control.

Filter Properties

contentType contentId reportType reviewStatus

Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API’s that have “Auto Params” enabled.

suspensionRecord Data Object

Object Overview

Description: Admin action to suspend or lift suspension on a user. Each record logs a suspension/lift action for audit/compliance.

This object represents a core data structure within the service and acts as the blueprint for database interaction, API generation, and business logic enforcement. It is defined using the ObjectSettings pattern, which governs its behavior, access control, caching strategy, and integration points with other systems such as Stripe and Redis.

Core Configuration

Properties Schema

Property Type Required Description
userId ID Yes Suspended user id
reason String Yes Reason for suspension action
suspendedByUserId ID Yes Admin ID who performed the suspension action
suspendedAt Date Yes Time of action (suspend/lift)
status Enum Yes Current state: active (suspended), lifted (reinstated)

Default Values

Default values are automatically assigned to properties when a new object is created, if no value is provided in the request body. Since default values are applied on db level, they should be literal values, not expressions.If you want to use expressions, you can use transposed parameters in any business API to set default values dynamically.

Always Create with Default Values

Some of the default values are set to be always used when creating a new object, even if the property value is provided in the request body. It ensures that the property is always initialized with a default value when the object is created.

Constant Properties

userId reason suspendedByUserId suspendedAt status

Constant properties are defined to be immutable after creation, meaning they cannot be updated or changed once set. They are typically used for properties that should remain constant throughout the object’s lifecycle. A property is set to be constant if the Allow Update option is set to false.

Auto Update Properties

userId reason suspendedByUserId suspendedAt status

An update crud API created with the option Auto Params enabled will automatically update these properties with the provided values in the request body. If you want to update any property in your own business logic not by user input, you can set the Allow Auto Update option to false. These properties will be added to the update API’s body parameters and can be updated by the user if any value is provided in the request body.

Enum Properties

Enum properties are defined with a set of allowed values, ensuring that only valid options can be assigned to them. The enum options value will be stored as strings in the database, but when a data object is created an addtional property with the same name plus an idx suffix will be created, which will hold the index of the selected enum option. You can use the index property to sort by the enum value or when your enum options represent a sequence of values.

Elastic Search Indexing

userId suspendedByUserId suspendedAt status

Properties that are indexed in Elastic Search will be searchable via the Elastic Search API. While all properties are stored in the elastic search index of the data object, only those marked for Elastic Search indexing will be available for search queries.

Database Indexing

userId suspendedByUserId status

Properties that are indexed in the database will be optimized for query performance, allowing for faster data retrieval. Make a property indexed in the database if you want to use it frequently in query filters or sorting.

Relation Properties

userId suspendedByUserId

Mindbricks supports relations between data objects, allowing you to define how objects are linked together. You can define relations in the data object properties, which will be used to create foreign key constraints in the database. For complex joins operations, Mindbricks supportsa BFF pattern, where you can view dynamic and static views based on Elastic Search Indexes. Use db level relations for simple one-to-one or one-to-many relationships, and use BFF views for complex joins that require multiple data objects to be joined together.

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

On Delete: Set Null Required: Yes

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

On Delete: Set Null Required: Yes

auditLog Data Object

Object Overview

Description: Generic audit log for all admin/moderation actions across services/objects for compliance and traceability.

This object represents a core data structure within the service and acts as the blueprint for database interaction, API generation, and business logic enforcement. It is defined using the ObjectSettings pattern, which governs its behavior, access control, caching strategy, and integration points with other systems such as Stripe and Redis.

Core Configuration

Properties Schema

Property Type Required Description
actionType String Yes Type of admin action (created, updated, suspended, approved, etc.)
actorUserId ID Yes User ID of admin/staff performing the action
targetType String Yes Type of object affected by this action (approvalRequest, reportLog, suspensionRecord, etc.)
targetId ID Yes ID of the object affected by this action
details Text No Freeform details, note, or JSON blob describing action context
actionAt Date Yes When the action occurred

Default Values

Default values are automatically assigned to properties when a new object is created, if no value is provided in the request body. Since default values are applied on db level, they should be literal values, not expressions.If you want to use expressions, you can use transposed parameters in any business API to set default values dynamically.

Constant Properties

actionType actorUserId targetType targetId details actionAt

Constant properties are defined to be immutable after creation, meaning they cannot be updated or changed once set. They are typically used for properties that should remain constant throughout the object’s lifecycle. A property is set to be constant if the Allow Update option is set to false.

Auto Update Properties

actionType actorUserId targetType targetId details actionAt

An update crud API created with the option Auto Params enabled will automatically update these properties with the provided values in the request body. If you want to update any property in your own business logic not by user input, you can set the Allow Auto Update option to false. These properties will be added to the update API’s body parameters and can be updated by the user if any value is provided in the request body.

Elastic Search Indexing

actionType actorUserId targetType targetId actionAt

Properties that are indexed in Elastic Search will be searchable via the Elastic Search API. While all properties are stored in the elastic search index of the data object, only those marked for Elastic Search indexing will be available for search queries.

Business Logic

moderationAdmin has got 15 Business APIs to manage its internal and crud logic. For the details of each business API refer to its chapter.


This document was generated from the service architecture definition and should be kept in sync with implementation changes.


REST API GUIDE

REST API GUIDE

auteurlabb-moderationadmin-service

Version: 1.0.11

Handles approval workflows for studios, investors, and projects; facilitates platform content moderation, user suspensions, and records all related admin actions for audit and compliance.

Architectural Design Credit and Contact Information

The architectural design of this microservice is credited to . For inquiries, feedback, or further information regarding the architecture, please direct your communication to:

Email:

We encourage open communication and welcome any questions or discussions related to the architectural aspects of this microservice.

Documentation Scope

Welcome to the official documentation for the ModerationAdmin Service’s REST API. This document is designed to provide a comprehensive guide to interfacing with our ModerationAdmin Service exclusively through RESTful API endpoints.

Intended Audience

This documentation is intended for developers and integrators who are looking to interact with the ModerationAdmin Service via HTTP requests for purposes such as creating, updating, deleting and querying ModerationAdmin objects.

Overview

Within these pages, you will find detailed information on how to effectively utilize the REST API, including authentication methods, request and response formats, endpoint descriptions, and examples of common use cases.

Beyond REST It’s important to note that the ModerationAdmin Service also supports alternative methods of interaction, such as gRPC and messaging via a Message Broker. These communication methods are beyond the scope of this document. For information regarding these protocols, please refer to their respective documentation.

Authentication And Authorization

To ensure secure access to the ModerationAdmin service’s protected endpoints, a project-wide access token is required. This token serves as the primary method for authenticating requests to our service. However, it’s important to note that access control varies across different routes:

Protected API: Certain API (routes) require specific authorization levels. Access to these routes is contingent upon the possession of a valid access token that meets the route-specific authorization criteria. Unauthorized requests to these routes will be rejected.

**Public API **: The service also includes public API (routes) that are accessible without authentication. These public endpoints are designed for open access and do not require an access token.

Token Locations

When including your access token in a request, ensure it is placed in one of the following specified locations. The service will sequentially search these locations for the token, utilizing the first one it encounters.

Location Token Name / Param Name
Query access_token
Authorization Header Bearer
Header auteurlabb-access-token
Cookie auteurlabb-access-token

Please ensure the token is correctly placed in one of these locations, using the appropriate label as indicated. The service prioritizes these locations in the order listed, processing the first token it successfully identifies.

Api Definitions

This section outlines the API endpoints available within the ModerationAdmin service. Each endpoint can receive parameters through various methods, meticulously described in the following definitions. It’s important to understand the flexibility in how parameters can be included in requests to effectively interact with the ModerationAdmin service.

This service is configured to listen for HTTP requests on port 3002, serving both the main API interface and default administrative endpoints.

The following routes are available by default:

This service is accessible via the following environment-specific URLs:

Parameter Inclusion Methods: Parameters can be incorporated into API requests in several ways, each with its designated location. Understanding these methods is crucial for correctly constructing your requests:

Query Parameters: Included directly in the URL’s query string.

Path Parameters: Embedded within the URL’s path.

Body Parameters: Sent within the JSON body of the request.

Session Parameters: Automatically read from the session object. This method is used for parameters that are intrinsic to the user’s session, such as userId. When using an API that involves session parameters, you can omit these from your request. The service will automatically bind them to the API layer, provided that a session is associated with your request.

Note on Session Parameters: Session parameters represent a unique method of parameter inclusion, relying on the context of the user’s session. A common example of a session parameter is userId, which the service automatically associates with your request when a session exists. This feature ensures seamless integration of user-specific data without manual input for each request.

By adhering to the specified parameter inclusion methods, you can effectively utilize the ModerationAdmin service’s API endpoints. For detailed information on each endpoint, including required parameters and their accepted locations, refer to the individual API definitions below.

Common Parameters

The ModerationAdmin service’s business API support several common parameters designed to modify and enhance the behavior of API requests. These parameters are not individually listed in the API route definitions to avoid repetition. Instead, refer to this section to understand how to leverage these common behaviors across different routes. Note that all common parameters should be included in the query part of the URL.

Supported Common Parameters:

By utilizing these common parameters, you can tailor the behavior of API requests to suit your specific requirements, ensuring optimal performance and usability of the ModerationAdmin service.

Error Response

If a request encounters an issue, whether due to a logical fault or a technical problem, the service responds with a standardized JSON error structure. The HTTP status code within this response indicates the nature of the error, utilizing commonly recognized codes for clarity:

Each error response is structured to provide meaningful insight into the problem, assisting in diagnosing and resolving issues efficiently.

{
  "result": "ERR",
  "status": 400,
  "message": "errMsg_organizationIdisNotAValidID",
  "errCode": 400,
  "date": "2024-03-19T12:13:54.124Z",
  "detail": "String"
}

Object Structure of a Successfull Response

When the ModerationAdmin service processes requests successfully, it wraps the requested resource(s) within a JSON envelope. This envelope not only contains the data but also includes essential metadata, such as configuration details and pagination information, to enrich the response and provide context to the client.

Key Characteristics of the Response Envelope:

Design Considerations: The structure of a API’s response data is meticulously crafted during the service’s architectural planning. This design ensures that responses adequately reflect the intended data relationships and service logic, providing clients with rich and meaningful information.

Brief Data: Certain API’s return a condensed version of the object data, intentionally selecting only specific fields deemed useful for that request. In such instances, the API documentation will detail the properties included in the response, guiding developers on what to expect.

API Response Structure

The API utilizes a standardized JSON envelope to encapsulate responses. This envelope is designed to consistently deliver both the requested data and essential metadata, ensuring that clients can efficiently interpret and utilize the response.

HTTP Status Codes:

Success Response Format:

For successful operations, the response includes a "status": "OK" property, signaling the successful execution of the request. The structure of a successful response is outlined below:

{
  "status":"OK",
  "statusCode": 200,   
  "elapsedMs":126,
  "ssoTime":120,
  "source": "db",
  "cacheKey": "hexCode",
  "userId": "ID",
  "sessionId": "ID",
  "requestId": "ID",
  "dataName":"products",
  "method":"GET",
  "action":"list",
  "appVersion":"Version",
  "rowCount":3
  "products":[{},{},{}],
  "paging": {
    "pageNumber":1, 
    "pageRowCount":25, 
    "totalRowCount":3,
    "pageCount":1
  },
  "filters": [],
  "uiPermissions": []
}

Handling Errors:

For details on handling error scenarios and understanding the structure of error responses, please refer to the “Error Response” section provided earlier in this documentation. It outlines how error conditions are communicated, including the use of HTTP status codes and standardized JSON structures for error messages.

Resources

ModerationAdmin service provides the following resources which are stored in its own database as a data object. Note that a resource for an api access is a data object for the service.

ApprovalRequest resource

Resource Definition : Tracks approval workflows for studios, investors, and submitted projects. Each request points to a specific entity and is reviewed by admin. ApprovalRequest Resource Properties

Name Type Required Default Definition
targetType Enum Type of entity being approved (studio, investor, project)
targetId ID ID of entity being approved (user or project, depending on type)
requestedAt Date Request creation time
requestedByUserId ID User ID who created the request
status Enum Approval status: pending/approved/rejected
reviewedAt Date Date/time request reviewed
reviewedByUserId ID Admin userId who reviewed the request
adminNote String Review note left by admin.

Enum Properties

Enum properties are represented as strings in the database. The values are mapped to their corresponding names in the application layer.

targetType Enum Property

Property Definition : Type of entity being approved (studio, investor, project)Enum Options

Name Value Index
studio "studio"" 0
investor "investor"" 1
project "project"" 2
filmmaker "filmmaker"" 3
status Enum Property

Property Definition : Approval status: pending/approved/rejectedEnum Options

Name Value Index
pending "pending"" 0
approved "approved"" 1
rejected "rejected"" 2

ReportLog resource

Resource Definition : Logs moderation/reporting actions: for project, message, or user. Each report includes status, type, review/action info. ReportLog Resource Properties

Name Type Required Default Definition
contentType Enum Type of content being reported: project/message/user
contentId ID ID of the reported content (project ID, message ID, user ID)
reportType String Nature of report (abuse, spam, copyright, etc.)
reportedByUserId ID ID of user reporting
reportedAt Date Report creation timestamp
reviewStatus Enum Open/closed/ignored
reviewAction String Action taken by admin (removed, warned, etc.) or note
actionedByUserId ID Admin making the moderation action
actionedAt Date Time of moderation action

Enum Properties

Enum properties are represented as strings in the database. The values are mapped to their corresponding names in the application layer.

contentType Enum Property

Property Definition : Type of content being reported: project/message/userEnum Options

Name Value Index
project "project"" 0
message "message"" 1
user "user"" 2
reviewStatus Enum Property

Property Definition : Open/closed/ignoredEnum Options

Name Value Index
open "open"" 0
closed "closed"" 1
ignored "ignored"" 2

SuspensionRecord resource

Resource Definition : Admin action to suspend or lift suspension on a user. Each record logs a suspension/lift action for audit/compliance. SuspensionRecord Resource Properties

Name Type Required Default Definition
userId ID Suspended user id
reason String Reason for suspension action
suspendedByUserId ID Admin ID who performed the suspension action
suspendedAt Date Time of action (suspend/lift)
status Enum Current state: active (suspended), lifted (reinstated)

Enum Properties

Enum properties are represented as strings in the database. The values are mapped to their corresponding names in the application layer.

status Enum Property

Property Definition : Current state: active (suspended), lifted (reinstated)Enum Options

Name Value Index
active "active"" 0
lifted "lifted"" 1

AuditLog resource

Resource Definition : Generic audit log for all admin/moderation actions across services/objects for compliance and traceability. AuditLog Resource Properties

Name Type Required Default Definition
actionType String Type of admin action (created, updated, suspended, approved, etc.)
actorUserId ID User ID of admin/staff performing the action
targetType String Type of object affected by this action (approvalRequest, reportLog, suspensionRecord, etc.)
targetId ID ID of the object affected by this action
details Text Freeform details, note, or JSON blob describing action context
actionAt Date When the action occurred

Business Api

Create Approvalrequest API

[Default create API] — This is the designated default create API for the approvalRequest data object. Frontend generators and AI agents should use this API for standard CRUD operations. Create a new approval request for studio, investor, or project. Status defaults to pending. Only non-admins can create requests for themselvessss.

Rest Route

The createApprovalRequest API REST controller can be triggered via the following route:

/v1/approvalrequests

Rest Request Parameters

The createApprovalRequest api has got 6 regular request parameters

Parameter Type Required Population
targetType Enum true request.body?.[“targetType”]
targetId ID true request.body?.[“targetId”]
requestedAt Date true request.body?.[“requestedAt”]
reviewedAt Date false request.body?.[“reviewedAt”]
reviewedByUserId ID false request.body?.[“reviewedByUserId”]
adminNote String false request.body?.[“adminNote”]
targetType : Type of entity being approved (studio, investor, project)
targetId : ID of entity being approved (user or project, depending on type)
requestedAt : Request creation time
reviewedAt : Date/time request reviewed
reviewedByUserId : Admin userId who reviewed the request
adminNote : Review note left by admin.

REST Request To access the api you can use the REST controller with the path POST /v1/approvalrequests

  axios({
    method: 'POST',
    url: '/v1/approvalrequests',
    data: {
            targetType:"Enum",  
            targetId:"ID",  
            requestedAt:"Date",  
            reviewedAt:"Date",  
            reviewedByUserId:"ID",  
            adminNote:"String",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "approvalRequest",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"approvalRequest": {
		"id": "ID",
		"targetType": "Enum",
		"targetType_idx": "Integer",
		"targetId": "ID",
		"requestedAt": "Date",
		"requestedByUserId": "ID",
		"status": "Enum",
		"status_idx": "Integer",
		"reviewedAt": "Date",
		"reviewedByUserId": "ID",
		"adminNote": "String",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Review Approvalrequest API

[Default update API] — This is the designated default update API for the approvalRequest data object. Frontend generators and AI agents should use this API for standard CRUD operations. Approve or reject an approval request. Only superAdmin or admin may update status or add review notes.

Rest Route

The reviewApprovalRequest API REST controller can be triggered via the following route:

/v1/reviewapprovalrequest/:approvalRequestId

Rest Request Parameters

The reviewApprovalRequest api has got 5 regular request parameters

Parameter Type Required Population
approvalRequestId ID true request.params?.[“approvalRequestId”]
status Enum true request.body?.[“status”]
reviewedAt Date false request.body?.[“reviewedAt”]
reviewedByUserId ID false request.body?.[“reviewedByUserId”]
adminNote String false request.body?.[“adminNote”]
approvalRequestId : This id paremeter is used to select the required data object that will be updated
status : Approval status: pending/approved/rejected
reviewedAt : Date/time request reviewed
reviewedByUserId : Admin userId who reviewed the request
adminNote : Review note left by admin.

REST Request To access the api you can use the REST controller with the path PATCH /v1/reviewapprovalrequest/:approvalRequestId

  axios({
    method: 'PATCH',
    url: `/v1/reviewapprovalrequest/${approvalRequestId}`,
    data: {
            status:"Enum",  
            reviewedAt:"Date",  
            reviewedByUserId:"ID",  
            adminNote:"String",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "approvalRequest",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"approvalRequest": {
		"id": "ID",
		"targetType": "Enum",
		"targetType_idx": "Integer",
		"targetId": "ID",
		"requestedAt": "Date",
		"requestedByUserId": "ID",
		"status": "Enum",
		"status_idx": "Integer",
		"reviewedAt": "Date",
		"reviewedByUserId": "ID",
		"adminNote": "String",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Get Approvalrequest API

[Default get API] — This is the designated default get API for the approvalRequest data object. Frontend generators and AI agents should use this API for standard CRUD operations. Get a single approvalRequest. Only owner or admin may view.

Rest Route

The getApprovalRequest API REST controller can be triggered via the following route:

/v1/approvalrequests/:approvalRequestId

Rest Request Parameters

The getApprovalRequest api has got 1 regular request parameter

Parameter Type Required Population
approvalRequestId ID true request.params?.[“approvalRequestId”]
approvalRequestId : This id paremeter is used to query the required data object.

REST Request To access the api you can use the REST controller with the path GET /v1/approvalrequests/:approvalRequestId

  axios({
    method: 'GET',
    url: `/v1/approvalrequests/${approvalRequestId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "approvalRequest",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"approvalRequest": {
		"id": "ID",
		"targetType": "Enum",
		"targetType_idx": "Integer",
		"targetId": "ID",
		"requestedAt": "Date",
		"requestedByUserId": "ID",
		"status": "Enum",
		"status_idx": "Integer",
		"reviewedAt": "Date",
		"reviewedByUserId": "ID",
		"adminNote": "String",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"requester": {
			"email": "String",
			"fullname": "String",
			"roleId": "String"
		},
		"reviewer": {
			"email": "String",
			"fullname": "String"
		}
	}
}

List Approvalrequests API

[Default list API] — This is the designated default list API for the approvalRequest data object. Frontend generators and AI agents should use this API for standard CRUD operations. List approval requests. Admins see all, non-admins see only their own.

Rest Route

The listApprovalRequests API REST controller can be triggered via the following route:

/v1/approvalrequests

Rest Request Parameters

Filter Parameters

The listApprovalRequests api supports 3 optional filter parameters for filtering list results:

targetType (Enum): Type of entity being approved (studio, investor, project)

targetId (ID): ID of entity being approved (user or project, depending on type)

status (Enum): Approval status: pending/approved/rejected

REST Request To access the api you can use the REST controller with the path GET /v1/approvalrequests

  axios({
    method: 'GET',
    url: '/v1/approvalrequests',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section above)
        // targetType: '<value>' // Filter by targetType
        // targetId: '<value>' // Filter by targetId
        // status: '<value>' // Filter by status
            }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "approvalRequests",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"approvalRequests": [
		{
			"id": "ID",
			"targetType": "Enum",
			"targetType_idx": "Integer",
			"targetId": "ID",
			"requestedAt": "Date",
			"requestedByUserId": "ID",
			"status": "Enum",
			"status_idx": "Integer",
			"reviewedAt": "Date",
			"reviewedByUserId": "ID",
			"adminNote": "String",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID",
			"requester": [
				{
					"email": "String",
					"fullname": "String",
					"roleId": "String"
				},
				{},
				{}
			],
			"reviewer": [
				{
					"email": "String",
					"fullname": "String"
				},
				{},
				{}
			]
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Create Reportlog API

[Default create API] — This is the designated default create API for the reportLog data object. Frontend generators and AI agents should use this API for standard CRUD operations. Create a content/user/project moderation report

Rest Route

The createReportLog API REST controller can be triggered via the following route:

/v1/reportlogs

Rest Request Parameters

The createReportLog api has got 7 regular request parameters

Parameter Type Required Population
contentType Enum true request.body?.[“contentType”]
contentId ID true request.body?.[“contentId”]
reportType String true request.body?.[“reportType”]
reportedAt Date true request.body?.[“reportedAt”]
reviewAction String false request.body?.[“reviewAction”]
actionedByUserId ID false request.body?.[“actionedByUserId”]
actionedAt Date false request.body?.[“actionedAt”]
contentType : Type of content being reported: project/message/user
contentId : ID of the reported content (project ID, message ID, user ID)
reportType : Nature of report (abuse, spam, copyright, etc.)
reportedAt : Report creation timestamp
reviewAction : Action taken by admin (removed, warned, etc.) or note
actionedByUserId : Admin making the moderation action
actionedAt : Time of moderation action

REST Request To access the api you can use the REST controller with the path POST /v1/reportlogs

  axios({
    method: 'POST',
    url: '/v1/reportlogs',
    data: {
            contentType:"Enum",  
            contentId:"ID",  
            reportType:"String",  
            reportedAt:"Date",  
            reviewAction:"String",  
            actionedByUserId:"ID",  
            actionedAt:"Date",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "reportLog",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"reportLog": {
		"id": "ID",
		"contentType": "Enum",
		"contentType_idx": "Integer",
		"contentId": "ID",
		"reportType": "String",
		"reportedByUserId": "ID",
		"reportedAt": "Date",
		"reviewStatus": "Enum",
		"reviewStatus_idx": "Integer",
		"reviewAction": "String",
		"actionedByUserId": "ID",
		"actionedAt": "Date",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Review Reportlog API

[Default update API] — This is the designated default update API for the reportLog data object. Frontend generators and AI agents should use this API for standard CRUD operations. Admin-only: Close/ignore a report, add review action/note. Only superAdmin/admin allowed.

Rest Route

The reviewReportLog API REST controller can be triggered via the following route:

/v1/reviewreportlog/:reportLogId

Rest Request Parameters

The reviewReportLog api has got 5 regular request parameters

Parameter Type Required Population
reportLogId ID true request.params?.[“reportLogId”]
reviewStatus Enum true request.body?.[“reviewStatus”]
reviewAction String false request.body?.[“reviewAction”]
actionedByUserId ID false request.body?.[“actionedByUserId”]
actionedAt Date false request.body?.[“actionedAt”]
reportLogId : This id paremeter is used to select the required data object that will be updated
reviewStatus : Open/closed/ignored
reviewAction : Action taken by admin (removed, warned, etc.) or note
actionedByUserId : Admin making the moderation action
actionedAt : Time of moderation action

REST Request To access the api you can use the REST controller with the path PATCH /v1/reviewreportlog/:reportLogId

  axios({
    method: 'PATCH',
    url: `/v1/reviewreportlog/${reportLogId}`,
    data: {
            reviewStatus:"Enum",  
            reviewAction:"String",  
            actionedByUserId:"ID",  
            actionedAt:"Date",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "reportLog",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"reportLog": {
		"id": "ID",
		"contentType": "Enum",
		"contentType_idx": "Integer",
		"contentId": "ID",
		"reportType": "String",
		"reportedByUserId": "ID",
		"reportedAt": "Date",
		"reviewStatus": "Enum",
		"reviewStatus_idx": "Integer",
		"reviewAction": "String",
		"actionedByUserId": "ID",
		"actionedAt": "Date",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Get Reportlog API

[Default get API] — This is the designated default get API for the reportLog data object. Frontend generators and AI agents should use this API for standard CRUD operations. Get a single report log. Only admins or reporting user may view.

Rest Route

The getReportLog API REST controller can be triggered via the following route:

/v1/reportlogs/:reportLogId

Rest Request Parameters

The getReportLog api has got 1 regular request parameter

Parameter Type Required Population
reportLogId ID true request.params?.[“reportLogId”]
reportLogId : This id paremeter is used to query the required data object.

REST Request To access the api you can use the REST controller with the path GET /v1/reportlogs/:reportLogId

  axios({
    method: 'GET',
    url: `/v1/reportlogs/${reportLogId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "reportLog",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"reportLog": {
		"id": "ID",
		"contentType": "Enum",
		"contentType_idx": "Integer",
		"contentId": "ID",
		"reportType": "String",
		"reportedByUserId": "ID",
		"reportedAt": "Date",
		"reviewStatus": "Enum",
		"reviewStatus_idx": "Integer",
		"reviewAction": "String",
		"actionedByUserId": "ID",
		"actionedAt": "Date",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"reportedBy": {
			"email": "String",
			"fullname": "String",
			"roleId": "String"
		},
		"actionedBy": {
			"email": "String",
			"fullname": "String"
		}
	}
}

List Reportlogs API

[Default list API] — This is the designated default list API for the reportLog data object. Frontend generators and AI agents should use this API for standard CRUD operations. List moderation reports. Admins see all; other users see only their reports.

Rest Route

The listReportLogs API REST controller can be triggered via the following route:

/v1/reportlogs

Rest Request Parameters

Filter Parameters

The listReportLogs api supports 4 optional filter parameters for filtering list results:

contentType (Enum): Type of content being reported: project/message/user

contentId (ID): ID of the reported content (project ID, message ID, user ID)

reportType (String): Nature of report (abuse, spam, copyright, etc.)

reviewStatus (Enum): Open/closed/ignored

REST Request To access the api you can use the REST controller with the path GET /v1/reportlogs

  axios({
    method: 'GET',
    url: '/v1/reportlogs',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section above)
        // contentType: '<value>' // Filter by contentType
        // contentId: '<value>' // Filter by contentId
        // reportType: '<value>' // Filter by reportType
        // reviewStatus: '<value>' // Filter by reviewStatus
            }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "reportLogs",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"reportLogs": [
		{
			"id": "ID",
			"contentType": "Enum",
			"contentType_idx": "Integer",
			"contentId": "ID",
			"reportType": "String",
			"reportedByUserId": "ID",
			"reportedAt": "Date",
			"reviewStatus": "Enum",
			"reviewStatus_idx": "Integer",
			"reviewAction": "String",
			"actionedByUserId": "ID",
			"actionedAt": "Date",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID",
			"reportedBy": [
				{
					"email": "String",
					"fullname": "String",
					"roleId": "String"
				},
				{},
				{}
			],
			"actionedBy": [
				{
					"email": "String",
					"fullname": "String"
				},
				{},
				{}
			]
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Create Suspensionrecord API

[Default create API] — This is the designated default create API for the suspensionRecord data object. Frontend generators and AI agents should use this API for standard CRUD operations. Admin: suspend a user from the platform. Action triggers update to auth:user isActive = false.

Rest Route

The createSuspensionRecord API REST controller can be triggered via the following route:

/v1/suspensionrecords

Rest Request Parameters

The createSuspensionRecord api has got 4 regular request parameters

Parameter Type Required Population
userId ID true request.body?.[“userId”]
reason String true request.body?.[“reason”]
suspendedByUserId ID true request.body?.[“suspendedByUserId”]
suspendedAt Date true request.body?.[“suspendedAt”]
userId : Suspended user id
reason : Reason for suspension action
suspendedByUserId : Admin ID who performed the suspension action
suspendedAt : Time of action (suspend/lift)

REST Request To access the api you can use the REST controller with the path POST /v1/suspensionrecords

  axios({
    method: 'POST',
    url: '/v1/suspensionrecords',
    data: {
            userId:"ID",  
            reason:"String",  
            suspendedByUserId:"ID",  
            suspendedAt:"Date",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "suspensionRecord",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"suspensionRecord": {
		"id": "ID",
		"userId": "ID",
		"reason": "String",
		"suspendedByUserId": "ID",
		"suspendedAt": "Date",
		"status": "Enum",
		"status_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Lift Suspensionrecord API

[Default update API] — This is the designated default update API for the suspensionRecord data object. Frontend generators and AI agents should use this API for standard CRUD operations. Admin: lift user suspension, set status to lifted & update user isActive=true in auth service.

Rest Route

The liftSuspensionRecord API REST controller can be triggered via the following route:

/v1/liftsuspensionrecord/:suspensionRecordId

Rest Request Parameters

The liftSuspensionRecord api has got 1 regular request parameter

Parameter Type Required Population
suspensionRecordId ID true request.params?.[“suspensionRecordId”]
suspensionRecordId : This id paremeter is used to select the required data object that will be updated

REST Request To access the api you can use the REST controller with the path PATCH /v1/liftsuspensionrecord/:suspensionRecordId

  axios({
    method: 'PATCH',
    url: `/v1/liftsuspensionrecord/${suspensionRecordId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "suspensionRecord",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"suspensionRecord": {
		"id": "ID",
		"userId": "ID",
		"reason": "String",
		"suspendedByUserId": "ID",
		"suspendedAt": "Date",
		"status": "Enum",
		"status_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Get Suspensionrecord API

[Default get API] — This is the designated default get API for the suspensionRecord data object. Frontend generators and AI agents should use this API for standard CRUD operations. Get a suspension record. Only admin/superAdmin or suspended user.

Rest Route

The getSuspensionRecord API REST controller can be triggered via the following route:

/v1/suspensionrecords/:suspensionRecordId

Rest Request Parameters

The getSuspensionRecord api has got 1 regular request parameter

Parameter Type Required Population
suspensionRecordId ID true request.params?.[“suspensionRecordId”]
suspensionRecordId : This id paremeter is used to query the required data object.

REST Request To access the api you can use the REST controller with the path GET /v1/suspensionrecords/:suspensionRecordId

  axios({
    method: 'GET',
    url: `/v1/suspensionrecords/${suspensionRecordId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "suspensionRecord",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"suspensionRecord": {
		"id": "ID",
		"userId": "ID",
		"reason": "String",
		"suspendedByUserId": "ID",
		"suspendedAt": "Date",
		"status": "Enum",
		"status_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"user": {
			"email": "String",
			"fullname": "String",
			"roleId": "String"
		},
		"suspendedByUser": {
			"email": "String",
			"fullname": "String"
		}
	}
}

List Suspensionrecords API

[Default list API] — This is the designated default list API for the suspensionRecord data object. Frontend generators and AI agents should use this API for standard CRUD operations. List suspension records. Admins see all; users see only their own.

Rest Route

The listSuspensionRecords API REST controller can be triggered via the following route:

/v1/suspensionrecords

Rest Request Parameters The listSuspensionRecords api has got no request parameters.

REST Request To access the api you can use the REST controller with the path GET /v1/suspensionrecords

  axios({
    method: 'GET',
    url: '/v1/suspensionrecords',
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "suspensionRecords",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"suspensionRecords": [
		{
			"id": "ID",
			"userId": "ID",
			"reason": "String",
			"suspendedByUserId": "ID",
			"suspendedAt": "Date",
			"status": "Enum",
			"status_idx": "Integer",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID",
			"user": [
				{
					"email": "String",
					"fullname": "String",
					"roleId": "String"
				},
				{},
				{}
			],
			"suspendedByUser": [
				{
					"email": "String",
					"fullname": "String"
				},
				{},
				{}
			]
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Create Auditlog API

[Default create API] — This is the designated default create API for the auditLog data object. Frontend generators and AI agents should use this API for standard CRUD operations. Create audit log entry. Only used by system or admin workflows.

Rest Route

The createAuditLog API REST controller can be triggered via the following route:

/v1/auditlogs

Rest Request Parameters

The createAuditLog api has got 6 regular request parameters

Parameter Type Required Population
actionType String true request.body?.[“actionType”]
actorUserId ID true request.body?.[“actorUserId”]
targetType String true request.body?.[“targetType”]
targetId ID true request.body?.[“targetId”]
details Text false request.body?.[“details”]
actionAt Date true request.body?.[“actionAt”]
actionType : Type of admin action (created, updated, suspended, approved, etc.)
actorUserId : User ID of admin/staff performing the action
targetType : Type of object affected by this action (approvalRequest, reportLog, suspensionRecord, etc.)
targetId : ID of the object affected by this action
details : Freeform details, note, or JSON blob describing action context
actionAt : When the action occurred

REST Request To access the api you can use the REST controller with the path POST /v1/auditlogs

  axios({
    method: 'POST',
    url: '/v1/auditlogs',
    data: {
            actionType:"String",  
            actorUserId:"ID",  
            targetType:"String",  
            targetId:"ID",  
            details:"Text",  
            actionAt:"Date",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "auditLog",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"auditLog": {
		"id": "ID",
		"actionType": "String",
		"actorUserId": "ID",
		"targetType": "String",
		"targetId": "ID",
		"details": "Text",
		"actionAt": "Date",
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"isActive": true
	}
}

Get Auditlog API

[Default get API] — This is the designated default get API for the auditLog data object. Frontend generators and AI agents should use this API for standard CRUD operations. Get a single audit log record. Only superAdmin/admin.

Rest Route

The getAuditLog API REST controller can be triggered via the following route:

/v1/auditlogs/:auditLogId

Rest Request Parameters

The getAuditLog api has got 1 regular request parameter

Parameter Type Required Population
auditLogId ID true request.params?.[“auditLogId”]
auditLogId : This id paremeter is used to query the required data object.

REST Request To access the api you can use the REST controller with the path GET /v1/auditlogs/:auditLogId

  axios({
    method: 'GET',
    url: `/v1/auditlogs/${auditLogId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "auditLog",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"auditLog": {
		"id": "ID",
		"actionType": "String",
		"actorUserId": "ID",
		"targetType": "String",
		"targetId": "ID",
		"details": "Text",
		"actionAt": "Date",
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"isActive": true
	}
}

List Auditlogs API

[Default list API] — This is the designated default list API for the auditLog data object. Frontend generators and AI agents should use this API for standard CRUD operations. List audit log records. Only superAdmin/admin.

Rest Route

The listAuditLogs API REST controller can be triggered via the following route:

/v1/auditlogs

Rest Request Parameters The listAuditLogs api has got no request parameters.

REST Request To access the api you can use the REST controller with the path GET /v1/auditlogs

  axios({
    method: 'GET',
    url: '/v1/auditlogs',
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "auditLogs",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"auditLogs": [
		{
			"id": "ID",
			"actionType": "String",
			"actorUserId": "ID",
			"targetType": "String",
			"targetId": "ID",
			"details": "Text",
			"actionAt": "Date",
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID",
			"isActive": true
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Authentication Specific Routes

Common Routes

Route: currentuser

Route Definition: Retrieves the currently authenticated user’s session information.

Route Type: sessionInfo

Access Route: GET /currentuser

Parameters

This route does not require any request parameters.

Behavior

// Sample GET /currentuser call
axios.get("/currentuser", {
  headers: {
    "Authorization": "Bearer your-jwt-token"
  }
});

Success Response Returns the session object, including user-related data and token information.

{
  "sessionId": "9cf23fa8-07d4-4e7c-80a6-ec6d6ac96bb9",
  "userId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38",
  "email": "user@example.com",
  "fullname": "John Doe",
  "roleId": "user",
  "tenantId": "abc123",
  "accessToken": "jwt-token-string",
  ...
}

Error Response 401 Unauthorized: No active session found.

{
  "status": "ERR",
  "message": "No login found"
}

Notes

Route: permissions

*Route Definition*: Retrieves all effective permission records assigned to the currently authenticated user.

*Route Type*: permissionFetch

Access Route: GET /permissions

Parameters

This route does not require any request parameters.

Behavior

// Sample GET /permissions call
axios.get("/permissions", {
  headers: {
    "Authorization": "Bearer your-jwt-token"
  }
});

Success Response

Returns an array of permission objects.

[
  {
    "id": "perm1",
    "permissionName": "adminPanel.access",
    "roleId": "admin",
    "subjectUserId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38",
    "subjectUserGroupId": null,
    "objectId": null,
    "canDo": true,
    "tenantCodename": "store123"
  },
  {
    "id": "perm2",
    "permissionName": "orders.manage",
    "roleId": null,
    "subjectUserId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38",
    "subjectUserGroupId": null,
    "objectId": null,
    "canDo": true,
    "tenantCodename": "store123"
  }
]

Each object reflects a single permission grant, aligned with the givenPermissions model:

Error Responses

{
  "status": "ERR",
  "message": "No login found"
}

Notes

Tip: Applications can cache permission results client-side or server-side, but should occasionally refresh by calling this endpoint, especially after login or permission-changing operations.

Route: permissions/:permissionName

Route Definition: Checks whether the current user has access to a specific permission, and provides a list of scoped object exceptions or inclusions.

Route Type: permissionScopeCheck

Access Route: GET /permissions/:permissionName

Parameters

Parameter Type Required Population
permissionName String Yes request.params.permissionName

Behavior

// Sample GET /permissions/orders.manage
axios.get("/permissions/orders.manage", {
  headers: {
    "Authorization": "Bearer your-jwt-token"
  }
});

Success Response

{
  "canDo": true,
  "exceptions": [
    "a1f2e3d4-xxxx-yyyy-zzzz-object1",
    "b2c3d4e5-xxxx-yyyy-zzzz-object2"
  ]
}

Copyright

All sources, documents and other digital materials are copyright of .

About Us

For more information please visit our website: .

. .


EVENT GUIDE

EVENT GUIDE

auteurlabb-moderationadmin-service

Handles approval workflows for studios, investors, and projects; facilitates platform content moderation, user suspensions, and records all related admin actions for audit and compliance.

Architectural Design Credit and Contact Information

The architectural design of this microservice is credited to . For inquiries, feedback, or further information regarding the architecture, please direct your communication to:

Email:

We encourage open communication and welcome any questions or discussions related to the architectural aspects of this microservice.

Documentation Scope

Welcome to the official documentation for the ModerationAdmin Service Event descriptions. This guide is dedicated to detailing how to subscribe to and listen for state changes within the ModerationAdmin Service, offering an exclusive focus on event subscription mechanisms.

Intended Audience

This documentation is aimed at developers and integrators looking to monitor ModerationAdmin Service state changes. It is especially relevant for those wishing to implement or enhance business logic based on interactions with ModerationAdmin objects.

Overview

This section provides detailed instructions on monitoring service events, covering payload structures and demonstrating typical use cases through examples.

Authentication and Authorization

Access to the ModerationAdmin service’s events is facilitated through the project’s Kafka server, which is not accessible to the public. Subscription to a Kafka topic requires being on the same network and possessing valid Kafka user credentials. This document presupposes that readers have existing access to the Kafka server.

Additionally, the service offers a public subscription option via REST for real-time data management in frontend applications, secured through REST API authentication and authorization mechanisms. To subscribe to service events via the REST API, please consult the Realtime REST API Guide.

Database Events

Database events are triggered at the database layer, automatically and atomically, in response to any modifications at the data level. These events serve to notify subscribers about the creation, update, or deletion of objects within the database, distinct from any overarching business logic.

Listening to database events is particularly beneficial for those focused on tracking changes at the database level. A typical use case for subscribing to database events is to replicate the data store of one service within another service’s scope, ensuring data consistency and syncronization across services.

For example, while a business operation such as “approve membership” might generate a high-level business event like membership-approved, the underlying database changes could involve multiple state updates to different entities. These might be published as separate events, such as dbevent-member-updated and dbevent-user-updated, reflecting the granular changes at the database level.

Such detailed eventing provides a robust foundation for building responsive, data-driven applications, enabling fine-grained observability and reaction to the dynamics of the data landscape. It also facilitates the architectural pattern of event sourcing, where state changes are captured as a sequence of events, allowing for high-fidelity data replication and history replay for analytical or auditing purposes.

DbEvent approvalRequest-created

Event topic: auteurlabb-moderationadmin-service-dbevent-approvalrequest-created

This event is triggered upon the creation of a approvalRequest data object in the database. The event payload encompasses the newly created data, encapsulated within the root of the paylod.

Event payload:

{"id":"ID","targetType":"Enum","targetType_idx":"Integer","targetId":"ID","requestedAt":"Date","requestedByUserId":"ID","status":"Enum","status_idx":"Integer","reviewedAt":"Date","reviewedByUserId":"ID","adminNote":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

DbEvent approvalRequest-updated

Event topic: auteurlabb-moderationadmin-service-dbevent-approvalrequest-updated

Activation of this event follows the update of a approvalRequest data object. The payload contains the updated information under the approvalRequest attribute, along with the original data prior to update, labeled as old_approvalRequest and also you can find the old and new versions of updated-only portion of the data…

Event payload:

{
old_approvalRequest:{"id":"ID","targetType":"Enum","targetType_idx":"Integer","targetId":"ID","requestedAt":"Date","requestedByUserId":"ID","status":"Enum","status_idx":"Integer","reviewedAt":"Date","reviewedByUserId":"ID","adminNote":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},
approvalRequest:{"id":"ID","targetType":"Enum","targetType_idx":"Integer","targetId":"ID","requestedAt":"Date","requestedByUserId":"ID","status":"Enum","status_idx":"Integer","reviewedAt":"Date","reviewedByUserId":"ID","adminNote":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},
oldDataValues,
newDataValues
}

DbEvent approvalRequest-deleted

Event topic: auteurlabb-moderationadmin-service-dbevent-approvalrequest-deleted

This event announces the deletion of a approvalRequest data object, covering both hard deletions (permanent removal) and soft deletions (where the isActive attribute is set to false). Regardless of the deletion type, the event payload will present the data as it was immediately before deletion, highlighting an isActive status of false for soft deletions.

Event payload:

{"id":"ID","targetType":"Enum","targetType_idx":"Integer","targetId":"ID","requestedAt":"Date","requestedByUserId":"ID","status":"Enum","status_idx":"Integer","reviewedAt":"Date","reviewedByUserId":"ID","adminNote":"String","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

DbEvent reportLog-created

Event topic: auteurlabb-moderationadmin-service-dbevent-reportlog-created

This event is triggered upon the creation of a reportLog data object in the database. The event payload encompasses the newly created data, encapsulated within the root of the paylod.

Event payload:

{"id":"ID","contentType":"Enum","contentType_idx":"Integer","contentId":"ID","reportType":"String","reportedByUserId":"ID","reportedAt":"Date","reviewStatus":"Enum","reviewStatus_idx":"Integer","reviewAction":"String","actionedByUserId":"ID","actionedAt":"Date","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

DbEvent reportLog-updated

Event topic: auteurlabb-moderationadmin-service-dbevent-reportlog-updated

Activation of this event follows the update of a reportLog data object. The payload contains the updated information under the reportLog attribute, along with the original data prior to update, labeled as old_reportLog and also you can find the old and new versions of updated-only portion of the data…

Event payload:

{
old_reportLog:{"id":"ID","contentType":"Enum","contentType_idx":"Integer","contentId":"ID","reportType":"String","reportedByUserId":"ID","reportedAt":"Date","reviewStatus":"Enum","reviewStatus_idx":"Integer","reviewAction":"String","actionedByUserId":"ID","actionedAt":"Date","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},
reportLog:{"id":"ID","contentType":"Enum","contentType_idx":"Integer","contentId":"ID","reportType":"String","reportedByUserId":"ID","reportedAt":"Date","reviewStatus":"Enum","reviewStatus_idx":"Integer","reviewAction":"String","actionedByUserId":"ID","actionedAt":"Date","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},
oldDataValues,
newDataValues
}

DbEvent reportLog-deleted

Event topic: auteurlabb-moderationadmin-service-dbevent-reportlog-deleted

This event announces the deletion of a reportLog data object, covering both hard deletions (permanent removal) and soft deletions (where the isActive attribute is set to false). Regardless of the deletion type, the event payload will present the data as it was immediately before deletion, highlighting an isActive status of false for soft deletions.

Event payload:

{"id":"ID","contentType":"Enum","contentType_idx":"Integer","contentId":"ID","reportType":"String","reportedByUserId":"ID","reportedAt":"Date","reviewStatus":"Enum","reviewStatus_idx":"Integer","reviewAction":"String","actionedByUserId":"ID","actionedAt":"Date","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

DbEvent suspensionRecord-created

Event topic: auteurlabb-moderationadmin-service-dbevent-suspensionrecord-created

This event is triggered upon the creation of a suspensionRecord data object in the database. The event payload encompasses the newly created data, encapsulated within the root of the paylod.

Event payload:

{"id":"ID","userId":"ID","reason":"String","suspendedByUserId":"ID","suspendedAt":"Date","status":"Enum","status_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

DbEvent suspensionRecord-updated

Event topic: auteurlabb-moderationadmin-service-dbevent-suspensionrecord-updated

Activation of this event follows the update of a suspensionRecord data object. The payload contains the updated information under the suspensionRecord attribute, along with the original data prior to update, labeled as old_suspensionRecord and also you can find the old and new versions of updated-only portion of the data…

Event payload:

{
old_suspensionRecord:{"id":"ID","userId":"ID","reason":"String","suspendedByUserId":"ID","suspendedAt":"Date","status":"Enum","status_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},
suspensionRecord:{"id":"ID","userId":"ID","reason":"String","suspendedByUserId":"ID","suspendedAt":"Date","status":"Enum","status_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},
oldDataValues,
newDataValues
}

DbEvent suspensionRecord-deleted

Event topic: auteurlabb-moderationadmin-service-dbevent-suspensionrecord-deleted

This event announces the deletion of a suspensionRecord data object, covering both hard deletions (permanent removal) and soft deletions (where the isActive attribute is set to false). Regardless of the deletion type, the event payload will present the data as it was immediately before deletion, highlighting an isActive status of false for soft deletions.

Event payload:

{"id":"ID","userId":"ID","reason":"String","suspendedByUserId":"ID","suspendedAt":"Date","status":"Enum","status_idx":"Integer","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

DbEvent auditLog-created

Event topic: auteurlabb-moderationadmin-service-dbevent-auditlog-created

This event is triggered upon the creation of a auditLog data object in the database. The event payload encompasses the newly created data, encapsulated within the root of the paylod.

Event payload:

{"id":"ID","actionType":"String","actorUserId":"ID","targetType":"String","targetId":"ID","details":"Text","actionAt":"Date","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

DbEvent auditLog-updated

Event topic: auteurlabb-moderationadmin-service-dbevent-auditlog-updated

Activation of this event follows the update of a auditLog data object. The payload contains the updated information under the auditLog attribute, along with the original data prior to update, labeled as old_auditLog and also you can find the old and new versions of updated-only portion of the data…

Event payload:

{
old_auditLog:{"id":"ID","actionType":"String","actorUserId":"ID","targetType":"String","targetId":"ID","details":"Text","actionAt":"Date","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},
auditLog:{"id":"ID","actionType":"String","actorUserId":"ID","targetType":"String","targetId":"ID","details":"Text","actionAt":"Date","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},
oldDataValues,
newDataValues
}

DbEvent auditLog-deleted

Event topic: auteurlabb-moderationadmin-service-dbevent-auditlog-deleted

This event announces the deletion of a auditLog data object, covering both hard deletions (permanent removal) and soft deletions (where the isActive attribute is set to false). Regardless of the deletion type, the event payload will present the data as it was immediately before deletion, highlighting an isActive status of false for soft deletions.

Event payload:

{"id":"ID","actionType":"String","actorUserId":"ID","targetType":"String","targetId":"ID","details":"Text","actionAt":"Date","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":false}

ElasticSearch Index Events

Within the ModerationAdmin service, most data objects are mirrored in ElasticSearch indices, ensuring these indices remain syncronized with their database counterparts through creation, updates, and deletions. These indices serve dual purposes: they act as a data source for external services and furnish aggregated data tailored to enhance frontend user experiences. Consequently, an ElasticSearch index might encapsulate data in its original form or aggregate additional information from other data objects.

These aggregations can include both one-to-one and one-to-many relationships not only with database objects within the same service but also across different services. This capability allows developers to access comprehensive, aggregated data efficiently. By subscribing to ElasticSearch index events, developers are notified when an index is updated and can directly obtain the aggregated entity within the event payload, bypassing the need for separate ElasticSearch queries.

It’s noteworthy that some services may augment another service’s index by appending to the entity’s extends object. In such scenarios, an *-extended event will contain only the newly added data. Should you require the complete dataset, you would need to retrieve the full ElasticSearch index entity using the provided ID.

This approach to indexing and event handling facilitates a modular, interconnected architecture where services can seamlessly integrate and react to changes, enriching the overall data ecosystem and enabling more dynamic, responsive applications.

Index Event approvalrequest-created

Event topic: elastic-index-auteurlabb_approvalrequest-created

Event payload:

{"id":"ID","targetType":"Enum","targetType_idx":"Integer","targetId":"ID","requestedAt":"Date","requestedByUserId":"ID","status":"Enum","status_idx":"Integer","reviewedAt":"Date","reviewedByUserId":"ID","adminNote":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event approvalrequest-updated

Event topic: elastic-index-auteurlabb_approvalrequest-created

Event payload:

{"id":"ID","targetType":"Enum","targetType_idx":"Integer","targetId":"ID","requestedAt":"Date","requestedByUserId":"ID","status":"Enum","status_idx":"Integer","reviewedAt":"Date","reviewedByUserId":"ID","adminNote":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event approvalrequest-deleted

Event topic: elastic-index-auteurlabb_approvalrequest-deleted

Event payload:

{"id":"ID","targetType":"Enum","targetType_idx":"Integer","targetId":"ID","requestedAt":"Date","requestedByUserId":"ID","status":"Enum","status_idx":"Integer","reviewedAt":"Date","reviewedByUserId":"ID","adminNote":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event approvalrequest-extended

Event topic: elastic-index-auteurlabb_approvalrequest-extended

Event payload:

{
  id: id,
  extends: {
    [extendName]: "Object",
    [extendName + "_count"]: "Number",
  },
}

Route Events

Route events are emitted following the successful execution of a route. While most routes perform CRUD (Create, Read, Update, Delete) operations on data objects, resulting in route events that closely resemble database events, there are distinctions worth noting. A single route execution might trigger multiple CRUD actions and ElasticSearch indexing operations. However, for those primarily concerned with the overarching business logic and its outcomes, listening to the consolidated route event, published once at the conclusion of the route’s execution, is more pertinent.

Moreover, routes often deliver aggregated data beyond the primary database object, catering to specific client needs. For instance, creating a data object via a route might not only return the entity’s data but also route-specific metrics, such as the executing user’s permissions related to the entity. Alternatively, a route might automatically generate default child entities following the creation of a parent object. Consequently, the route event encapsulates a unified dataset encompassing both the parent and its children, in contrast to individual events triggered for each entity created. Therefore, subscribing to route events can offer a richer, more contextually relevant set of information aligned with business logic.

The payload of a route event mirrors the REST response JSON of the route, providing a direct and comprehensive reflection of the data and metadata communicated to the client. This ensures that subscribers to route events receive a payload that encapsulates both the primary data involved and any additional information deemed significant at the business level, facilitating a deeper understanding and integration of the service’s functional outcomes.

Route Event approvalrequest-created

Event topic : auteurlabb-moderationadmin-service-approvalrequest-created

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the approvalRequest data object itself.

The following JSON included in the payload illustrates the fullest representation of the approvalRequest object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"approvalRequest","method":"POST","action":"create","appVersion":"Version","rowCount":1,"approvalRequest":{"id":"ID","targetType":"Enum","targetType_idx":"Integer","targetId":"ID","requestedAt":"Date","requestedByUserId":"ID","status":"Enum","status_idx":"Integer","reviewedAt":"Date","reviewedByUserId":"ID","adminNote":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event approvalrequest-reviewed

Event topic : auteurlabb-moderationadmin-service-approvalrequest-reviewed

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the approvalRequest data object itself.

The following JSON included in the payload illustrates the fullest representation of the approvalRequest object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"approvalRequest","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"approvalRequest":{"id":"ID","targetType":"Enum","targetType_idx":"Integer","targetId":"ID","requestedAt":"Date","requestedByUserId":"ID","status":"Enum","status_idx":"Integer","reviewedAt":"Date","reviewedByUserId":"ID","adminNote":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event reportlog-created

Event topic : auteurlabb-moderationadmin-service-reportlog-created

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the reportLog data object itself.

The following JSON included in the payload illustrates the fullest representation of the reportLog object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"reportLog","method":"POST","action":"create","appVersion":"Version","rowCount":1,"reportLog":{"id":"ID","contentType":"Enum","contentType_idx":"Integer","contentId":"ID","reportType":"String","reportedByUserId":"ID","reportedAt":"Date","reviewStatus":"Enum","reviewStatus_idx":"Integer","reviewAction":"String","actionedByUserId":"ID","actionedAt":"Date","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event reportlog-reviewed

Event topic : auteurlabb-moderationadmin-service-reportlog-reviewed

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the reportLog data object itself.

The following JSON included in the payload illustrates the fullest representation of the reportLog object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"reportLog","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"reportLog":{"id":"ID","contentType":"Enum","contentType_idx":"Integer","contentId":"ID","reportType":"String","reportedByUserId":"ID","reportedAt":"Date","reviewStatus":"Enum","reviewStatus_idx":"Integer","reviewAction":"String","actionedByUserId":"ID","actionedAt":"Date","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event suspensionrecord-created

Event topic : auteurlabb-moderationadmin-service-suspensionrecord-created

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the suspensionRecord data object itself.

The following JSON included in the payload illustrates the fullest representation of the suspensionRecord object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"suspensionRecord","method":"POST","action":"create","appVersion":"Version","rowCount":1,"suspensionRecord":{"id":"ID","userId":"ID","reason":"String","suspendedByUserId":"ID","suspendedAt":"Date","status":"Enum","status_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event suspensionrecord-lifted

Event topic : auteurlabb-moderationadmin-service-suspensionrecord-lifted

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the suspensionRecord data object itself.

The following JSON included in the payload illustrates the fullest representation of the suspensionRecord object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"suspensionRecord","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"suspensionRecord":{"id":"ID","userId":"ID","reason":"String","suspendedByUserId":"ID","suspendedAt":"Date","status":"Enum","status_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event auditlog-created

Event topic : auteurlabb-moderationadmin-service-auditlog-created

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the auditLog data object itself.

The following JSON included in the payload illustrates the fullest representation of the auditLog object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"auditLog","method":"POST","action":"create","appVersion":"Version","rowCount":1,"auditLog":{"id":"ID","actionType":"String","actorUserId":"ID","targetType":"String","targetId":"ID","details":"Text","actionAt":"Date","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true}}

Index Event reportlog-created

Event topic: elastic-index-auteurlabb_reportlog-created

Event payload:

{"id":"ID","contentType":"Enum","contentType_idx":"Integer","contentId":"ID","reportType":"String","reportedByUserId":"ID","reportedAt":"Date","reviewStatus":"Enum","reviewStatus_idx":"Integer","reviewAction":"String","actionedByUserId":"ID","actionedAt":"Date","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event reportlog-updated

Event topic: elastic-index-auteurlabb_reportlog-created

Event payload:

{"id":"ID","contentType":"Enum","contentType_idx":"Integer","contentId":"ID","reportType":"String","reportedByUserId":"ID","reportedAt":"Date","reviewStatus":"Enum","reviewStatus_idx":"Integer","reviewAction":"String","actionedByUserId":"ID","actionedAt":"Date","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event reportlog-deleted

Event topic: elastic-index-auteurlabb_reportlog-deleted

Event payload:

{"id":"ID","contentType":"Enum","contentType_idx":"Integer","contentId":"ID","reportType":"String","reportedByUserId":"ID","reportedAt":"Date","reviewStatus":"Enum","reviewStatus_idx":"Integer","reviewAction":"String","actionedByUserId":"ID","actionedAt":"Date","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event reportlog-extended

Event topic: elastic-index-auteurlabb_reportlog-extended

Event payload:

{
  id: id,
  extends: {
    [extendName]: "Object",
    [extendName + "_count"]: "Number",
  },
}

Route Events

Route events are emitted following the successful execution of a route. While most routes perform CRUD (Create, Read, Update, Delete) operations on data objects, resulting in route events that closely resemble database events, there are distinctions worth noting. A single route execution might trigger multiple CRUD actions and ElasticSearch indexing operations. However, for those primarily concerned with the overarching business logic and its outcomes, listening to the consolidated route event, published once at the conclusion of the route’s execution, is more pertinent.

Moreover, routes often deliver aggregated data beyond the primary database object, catering to specific client needs. For instance, creating a data object via a route might not only return the entity’s data but also route-specific metrics, such as the executing user’s permissions related to the entity. Alternatively, a route might automatically generate default child entities following the creation of a parent object. Consequently, the route event encapsulates a unified dataset encompassing both the parent and its children, in contrast to individual events triggered for each entity created. Therefore, subscribing to route events can offer a richer, more contextually relevant set of information aligned with business logic.

The payload of a route event mirrors the REST response JSON of the route, providing a direct and comprehensive reflection of the data and metadata communicated to the client. This ensures that subscribers to route events receive a payload that encapsulates both the primary data involved and any additional information deemed significant at the business level, facilitating a deeper understanding and integration of the service’s functional outcomes.

Route Event approvalrequest-created

Event topic : auteurlabb-moderationadmin-service-approvalrequest-created

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the approvalRequest data object itself.

The following JSON included in the payload illustrates the fullest representation of the approvalRequest object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"approvalRequest","method":"POST","action":"create","appVersion":"Version","rowCount":1,"approvalRequest":{"id":"ID","targetType":"Enum","targetType_idx":"Integer","targetId":"ID","requestedAt":"Date","requestedByUserId":"ID","status":"Enum","status_idx":"Integer","reviewedAt":"Date","reviewedByUserId":"ID","adminNote":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event approvalrequest-reviewed

Event topic : auteurlabb-moderationadmin-service-approvalrequest-reviewed

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the approvalRequest data object itself.

The following JSON included in the payload illustrates the fullest representation of the approvalRequest object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"approvalRequest","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"approvalRequest":{"id":"ID","targetType":"Enum","targetType_idx":"Integer","targetId":"ID","requestedAt":"Date","requestedByUserId":"ID","status":"Enum","status_idx":"Integer","reviewedAt":"Date","reviewedByUserId":"ID","adminNote":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event reportlog-created

Event topic : auteurlabb-moderationadmin-service-reportlog-created

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the reportLog data object itself.

The following JSON included in the payload illustrates the fullest representation of the reportLog object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"reportLog","method":"POST","action":"create","appVersion":"Version","rowCount":1,"reportLog":{"id":"ID","contentType":"Enum","contentType_idx":"Integer","contentId":"ID","reportType":"String","reportedByUserId":"ID","reportedAt":"Date","reviewStatus":"Enum","reviewStatus_idx":"Integer","reviewAction":"String","actionedByUserId":"ID","actionedAt":"Date","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event reportlog-reviewed

Event topic : auteurlabb-moderationadmin-service-reportlog-reviewed

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the reportLog data object itself.

The following JSON included in the payload illustrates the fullest representation of the reportLog object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"reportLog","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"reportLog":{"id":"ID","contentType":"Enum","contentType_idx":"Integer","contentId":"ID","reportType":"String","reportedByUserId":"ID","reportedAt":"Date","reviewStatus":"Enum","reviewStatus_idx":"Integer","reviewAction":"String","actionedByUserId":"ID","actionedAt":"Date","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event suspensionrecord-created

Event topic : auteurlabb-moderationadmin-service-suspensionrecord-created

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the suspensionRecord data object itself.

The following JSON included in the payload illustrates the fullest representation of the suspensionRecord object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"suspensionRecord","method":"POST","action":"create","appVersion":"Version","rowCount":1,"suspensionRecord":{"id":"ID","userId":"ID","reason":"String","suspendedByUserId":"ID","suspendedAt":"Date","status":"Enum","status_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event suspensionrecord-lifted

Event topic : auteurlabb-moderationadmin-service-suspensionrecord-lifted

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the suspensionRecord data object itself.

The following JSON included in the payload illustrates the fullest representation of the suspensionRecord object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"suspensionRecord","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"suspensionRecord":{"id":"ID","userId":"ID","reason":"String","suspendedByUserId":"ID","suspendedAt":"Date","status":"Enum","status_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event auditlog-created

Event topic : auteurlabb-moderationadmin-service-auditlog-created

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the auditLog data object itself.

The following JSON included in the payload illustrates the fullest representation of the auditLog object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"auditLog","method":"POST","action":"create","appVersion":"Version","rowCount":1,"auditLog":{"id":"ID","actionType":"String","actorUserId":"ID","targetType":"String","targetId":"ID","details":"Text","actionAt":"Date","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true}}

Index Event suspensionrecord-created

Event topic: elastic-index-auteurlabb_suspensionrecord-created

Event payload:

{"id":"ID","userId":"ID","reason":"String","suspendedByUserId":"ID","suspendedAt":"Date","status":"Enum","status_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event suspensionrecord-updated

Event topic: elastic-index-auteurlabb_suspensionrecord-created

Event payload:

{"id":"ID","userId":"ID","reason":"String","suspendedByUserId":"ID","suspendedAt":"Date","status":"Enum","status_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event suspensionrecord-deleted

Event topic: elastic-index-auteurlabb_suspensionrecord-deleted

Event payload:

{"id":"ID","userId":"ID","reason":"String","suspendedByUserId":"ID","suspendedAt":"Date","status":"Enum","status_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event suspensionrecord-extended

Event topic: elastic-index-auteurlabb_suspensionrecord-extended

Event payload:

{
  id: id,
  extends: {
    [extendName]: "Object",
    [extendName + "_count"]: "Number",
  },
}

Route Events

Route events are emitted following the successful execution of a route. While most routes perform CRUD (Create, Read, Update, Delete) operations on data objects, resulting in route events that closely resemble database events, there are distinctions worth noting. A single route execution might trigger multiple CRUD actions and ElasticSearch indexing operations. However, for those primarily concerned with the overarching business logic and its outcomes, listening to the consolidated route event, published once at the conclusion of the route’s execution, is more pertinent.

Moreover, routes often deliver aggregated data beyond the primary database object, catering to specific client needs. For instance, creating a data object via a route might not only return the entity’s data but also route-specific metrics, such as the executing user’s permissions related to the entity. Alternatively, a route might automatically generate default child entities following the creation of a parent object. Consequently, the route event encapsulates a unified dataset encompassing both the parent and its children, in contrast to individual events triggered for each entity created. Therefore, subscribing to route events can offer a richer, more contextually relevant set of information aligned with business logic.

The payload of a route event mirrors the REST response JSON of the route, providing a direct and comprehensive reflection of the data and metadata communicated to the client. This ensures that subscribers to route events receive a payload that encapsulates both the primary data involved and any additional information deemed significant at the business level, facilitating a deeper understanding and integration of the service’s functional outcomes.

Route Event approvalrequest-created

Event topic : auteurlabb-moderationadmin-service-approvalrequest-created

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the approvalRequest data object itself.

The following JSON included in the payload illustrates the fullest representation of the approvalRequest object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"approvalRequest","method":"POST","action":"create","appVersion":"Version","rowCount":1,"approvalRequest":{"id":"ID","targetType":"Enum","targetType_idx":"Integer","targetId":"ID","requestedAt":"Date","requestedByUserId":"ID","status":"Enum","status_idx":"Integer","reviewedAt":"Date","reviewedByUserId":"ID","adminNote":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event approvalrequest-reviewed

Event topic : auteurlabb-moderationadmin-service-approvalrequest-reviewed

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the approvalRequest data object itself.

The following JSON included in the payload illustrates the fullest representation of the approvalRequest object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"approvalRequest","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"approvalRequest":{"id":"ID","targetType":"Enum","targetType_idx":"Integer","targetId":"ID","requestedAt":"Date","requestedByUserId":"ID","status":"Enum","status_idx":"Integer","reviewedAt":"Date","reviewedByUserId":"ID","adminNote":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event reportlog-created

Event topic : auteurlabb-moderationadmin-service-reportlog-created

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the reportLog data object itself.

The following JSON included in the payload illustrates the fullest representation of the reportLog object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"reportLog","method":"POST","action":"create","appVersion":"Version","rowCount":1,"reportLog":{"id":"ID","contentType":"Enum","contentType_idx":"Integer","contentId":"ID","reportType":"String","reportedByUserId":"ID","reportedAt":"Date","reviewStatus":"Enum","reviewStatus_idx":"Integer","reviewAction":"String","actionedByUserId":"ID","actionedAt":"Date","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event reportlog-reviewed

Event topic : auteurlabb-moderationadmin-service-reportlog-reviewed

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the reportLog data object itself.

The following JSON included in the payload illustrates the fullest representation of the reportLog object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"reportLog","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"reportLog":{"id":"ID","contentType":"Enum","contentType_idx":"Integer","contentId":"ID","reportType":"String","reportedByUserId":"ID","reportedAt":"Date","reviewStatus":"Enum","reviewStatus_idx":"Integer","reviewAction":"String","actionedByUserId":"ID","actionedAt":"Date","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event suspensionrecord-created

Event topic : auteurlabb-moderationadmin-service-suspensionrecord-created

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the suspensionRecord data object itself.

The following JSON included in the payload illustrates the fullest representation of the suspensionRecord object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"suspensionRecord","method":"POST","action":"create","appVersion":"Version","rowCount":1,"suspensionRecord":{"id":"ID","userId":"ID","reason":"String","suspendedByUserId":"ID","suspendedAt":"Date","status":"Enum","status_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event suspensionrecord-lifted

Event topic : auteurlabb-moderationadmin-service-suspensionrecord-lifted

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the suspensionRecord data object itself.

The following JSON included in the payload illustrates the fullest representation of the suspensionRecord object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"suspensionRecord","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"suspensionRecord":{"id":"ID","userId":"ID","reason":"String","suspendedByUserId":"ID","suspendedAt":"Date","status":"Enum","status_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event auditlog-created

Event topic : auteurlabb-moderationadmin-service-auditlog-created

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the auditLog data object itself.

The following JSON included in the payload illustrates the fullest representation of the auditLog object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"auditLog","method":"POST","action":"create","appVersion":"Version","rowCount":1,"auditLog":{"id":"ID","actionType":"String","actorUserId":"ID","targetType":"String","targetId":"ID","details":"Text","actionAt":"Date","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true}}

Index Event auditlog-created

Event topic: elastic-index-auteurlabb_auditlog-created

Event payload:

{"id":"ID","actionType":"String","actorUserId":"ID","targetType":"String","targetId":"ID","details":"Text","actionAt":"Date","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event auditlog-updated

Event topic: elastic-index-auteurlabb_auditlog-created

Event payload:

{"id":"ID","actionType":"String","actorUserId":"ID","targetType":"String","targetId":"ID","details":"Text","actionAt":"Date","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event auditlog-deleted

Event topic: elastic-index-auteurlabb_auditlog-deleted

Event payload:

{"id":"ID","actionType":"String","actorUserId":"ID","targetType":"String","targetId":"ID","details":"Text","actionAt":"Date","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event auditlog-extended

Event topic: elastic-index-auteurlabb_auditlog-extended

Event payload:

{
  id: id,
  extends: {
    [extendName]: "Object",
    [extendName + "_count"]: "Number",
  },
}

Route Events

Route events are emitted following the successful execution of a route. While most routes perform CRUD (Create, Read, Update, Delete) operations on data objects, resulting in route events that closely resemble database events, there are distinctions worth noting. A single route execution might trigger multiple CRUD actions and ElasticSearch indexing operations. However, for those primarily concerned with the overarching business logic and its outcomes, listening to the consolidated route event, published once at the conclusion of the route’s execution, is more pertinent.

Moreover, routes often deliver aggregated data beyond the primary database object, catering to specific client needs. For instance, creating a data object via a route might not only return the entity’s data but also route-specific metrics, such as the executing user’s permissions related to the entity. Alternatively, a route might automatically generate default child entities following the creation of a parent object. Consequently, the route event encapsulates a unified dataset encompassing both the parent and its children, in contrast to individual events triggered for each entity created. Therefore, subscribing to route events can offer a richer, more contextually relevant set of information aligned with business logic.

The payload of a route event mirrors the REST response JSON of the route, providing a direct and comprehensive reflection of the data and metadata communicated to the client. This ensures that subscribers to route events receive a payload that encapsulates both the primary data involved and any additional information deemed significant at the business level, facilitating a deeper understanding and integration of the service’s functional outcomes.

Route Event approvalrequest-created

Event topic : auteurlabb-moderationadmin-service-approvalrequest-created

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the approvalRequest data object itself.

The following JSON included in the payload illustrates the fullest representation of the approvalRequest object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"approvalRequest","method":"POST","action":"create","appVersion":"Version","rowCount":1,"approvalRequest":{"id":"ID","targetType":"Enum","targetType_idx":"Integer","targetId":"ID","requestedAt":"Date","requestedByUserId":"ID","status":"Enum","status_idx":"Integer","reviewedAt":"Date","reviewedByUserId":"ID","adminNote":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event approvalrequest-reviewed

Event topic : auteurlabb-moderationadmin-service-approvalrequest-reviewed

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the approvalRequest data object itself.

The following JSON included in the payload illustrates the fullest representation of the approvalRequest object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"approvalRequest","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"approvalRequest":{"id":"ID","targetType":"Enum","targetType_idx":"Integer","targetId":"ID","requestedAt":"Date","requestedByUserId":"ID","status":"Enum","status_idx":"Integer","reviewedAt":"Date","reviewedByUserId":"ID","adminNote":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event reportlog-created

Event topic : auteurlabb-moderationadmin-service-reportlog-created

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the reportLog data object itself.

The following JSON included in the payload illustrates the fullest representation of the reportLog object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"reportLog","method":"POST","action":"create","appVersion":"Version","rowCount":1,"reportLog":{"id":"ID","contentType":"Enum","contentType_idx":"Integer","contentId":"ID","reportType":"String","reportedByUserId":"ID","reportedAt":"Date","reviewStatus":"Enum","reviewStatus_idx":"Integer","reviewAction":"String","actionedByUserId":"ID","actionedAt":"Date","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event reportlog-reviewed

Event topic : auteurlabb-moderationadmin-service-reportlog-reviewed

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the reportLog data object itself.

The following JSON included in the payload illustrates the fullest representation of the reportLog object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"reportLog","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"reportLog":{"id":"ID","contentType":"Enum","contentType_idx":"Integer","contentId":"ID","reportType":"String","reportedByUserId":"ID","reportedAt":"Date","reviewStatus":"Enum","reviewStatus_idx":"Integer","reviewAction":"String","actionedByUserId":"ID","actionedAt":"Date","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event suspensionrecord-created

Event topic : auteurlabb-moderationadmin-service-suspensionrecord-created

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the suspensionRecord data object itself.

The following JSON included in the payload illustrates the fullest representation of the suspensionRecord object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"suspensionRecord","method":"POST","action":"create","appVersion":"Version","rowCount":1,"suspensionRecord":{"id":"ID","userId":"ID","reason":"String","suspendedByUserId":"ID","suspendedAt":"Date","status":"Enum","status_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event suspensionrecord-lifted

Event topic : auteurlabb-moderationadmin-service-suspensionrecord-lifted

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the suspensionRecord data object itself.

The following JSON included in the payload illustrates the fullest representation of the suspensionRecord object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"suspensionRecord","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"suspensionRecord":{"id":"ID","userId":"ID","reason":"String","suspendedByUserId":"ID","suspendedAt":"Date","status":"Enum","status_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event auditlog-created

Event topic : auteurlabb-moderationadmin-service-auditlog-created

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the auditLog data object itself.

The following JSON included in the payload illustrates the fullest representation of the auditLog object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"auditLog","method":"POST","action":"create","appVersion":"Version","rowCount":1,"auditLog":{"id":"ID","actionType":"String","actorUserId":"ID","targetType":"String","targetId":"ID","details":"Text","actionAt":"Date","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true}}

Copyright

All sources, documents and other digital materials are copyright of .

About Us

For more information please visit our website: .

. .


Data Objects

Service Design Specification - Object Design for approvalRequest

Service Design Specification - Object Design for approvalRequest

auteurlabb-moderationadmin-service documentation

Document Overview

This document outlines the object design for the approvalRequest model in our application. It includes details about the model’s attributes, relationships, and any specific validation or business logic that applies.

approvalRequest Data Object

Object Overview

Description: Tracks approval workflows for studios, investors, and submitted projects. Each request points to a specific entity and is reviewed by admin.

This object represents a core data structure within the service and acts as the blueprint for database interaction, API generation, and business logic enforcement. It is defined using the ObjectSettings pattern, which governs its behavior, access control, caching strategy, and integration points with other systems such as Stripe and Redis.

Core Configuration

Composite Indexes

The index also defines a conflict resolution strategy for duplicate key violations.

When a new record would violate this composite index, the following action will be taken:

On Duplicate: throwError

An error will be thrown, preventing the insertion of conflicting data.

Properties Schema

Property Type Required Description
targetType Enum Yes Type of entity being approved (studio, investor, project)
targetId ID Yes ID of entity being approved (user or project, depending on type)
requestedAt Date Yes Request creation time
requestedByUserId ID Yes User ID who created the request
status Enum Yes Approval status: pending/approved/rejected
reviewedAt Date No Date/time request reviewed
reviewedByUserId ID No Admin userId who reviewed the request
adminNote String No Review note left by admin.

Default Values

Default values are automatically assigned to properties when a new object is created, if no value is provided in the request body. Since default values are applied on db level, they should be literal values, not expressions.If you want to use expressions, you can use transposed parameters in any business API to set default values dynamically.

Always Create with Default Values

Some of the default values are set to be always used when creating a new object, even if the property value is provided in the request body. It ensures that the property is always initialized with a default value when the object is created.

Constant Properties

targetType targetId requestedAt requestedByUserId

Constant properties are defined to be immutable after creation, meaning they cannot be updated or changed once set. They are typically used for properties that should remain constant throughout the object’s lifecycle. A property is set to be constant if the Allow Update option is set to false.

Auto Update Properties

targetType targetId requestedAt requestedByUserId status reviewedAt reviewedByUserId adminNote

An update crud API created with the option Auto Params enabled will automatically update these properties with the provided values in the request body. If you want to update any property in your own business logic not by user input, you can set the Allow Auto Update option to false. These properties will be added to the update API’s body parameters and can be updated by the user if any value is provided in the request body.

Enum Properties

Enum properties are defined with a set of allowed values, ensuring that only valid options can be assigned to them. The enum options value will be stored as strings in the database, but when a data object is created an addtional property with the same name plus an idx suffix will be created, which will hold the index of the selected enum option. You can use the index property to sort by the enum value or when your enum options represent a sequence of values.

Elastic Search Indexing

targetType targetId requestedAt requestedByUserId status reviewedAt reviewedByUserId

Properties that are indexed in Elastic Search will be searchable via the Elastic Search API. While all properties are stored in the elastic search index of the data object, only those marked for Elastic Search indexing will be available for search queries.

Database Indexing

targetType targetId requestedByUserId status reviewedByUserId

Properties that are indexed in the database will be optimized for query performance, allowing for faster data retrieval. Make a property indexed in the database if you want to use it frequently in query filters or sorting.

Relation Properties

requestedByUserId reviewedByUserId

Mindbricks supports relations between data objects, allowing you to define how objects are linked together. You can define relations in the data object properties, which will be used to create foreign key constraints in the database. For complex joins operations, Mindbricks supportsa BFF pattern, where you can view dynamic and static views based on Elastic Search Indexes. Use db level relations for simple one-to-one or one-to-many relationships, and use BFF views for complex joins that require multiple data objects to be joined together.

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

On Delete: Set Null Required: Yes

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

On Delete: Set Null Required: No

Session Data Properties

requestedByUserId

Session data properties are used to store data that is specific to the user session, allowing for personalized experiences and temporary data storage. If a property is configured as session data, it will be automatically mapped to the related field in the user session during CRUD operations. Note that session data properties can not be mutated by the user, but only by the system.

This property is also used to store the owner of the session data, allowing for ownership checks and access control.

Filter Properties

targetType targetId status

Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API’s that have “Auto Params” enabled.


Service Design Specification - Object Design for reportLog

Service Design Specification - Object Design for reportLog

auteurlabb-moderationadmin-service documentation

Document Overview

This document outlines the object design for the reportLog model in our application. It includes details about the model’s attributes, relationships, and any specific validation or business logic that applies.

reportLog Data Object

Object Overview

Description: Logs moderation/reporting actions: for project, message, or user. Each report includes status, type, review/action info.

This object represents a core data structure within the service and acts as the blueprint for database interaction, API generation, and business logic enforcement. It is defined using the ObjectSettings pattern, which governs its behavior, access control, caching strategy, and integration points with other systems such as Stripe and Redis.

Core Configuration

Properties Schema

Property Type Required Description
contentType Enum Yes Type of content being reported: project/message/user
contentId ID Yes ID of the reported content (project ID, message ID, user ID)
reportType String Yes Nature of report (abuse, spam, copyright, etc.)
reportedByUserId ID Yes ID of user reporting
reportedAt Date Yes Report creation timestamp
reviewStatus Enum Yes Open/closed/ignored
reviewAction String No Action taken by admin (removed, warned, etc.) or note
actionedByUserId ID No Admin making the moderation action
actionedAt Date No Time of moderation action

Default Values

Default values are automatically assigned to properties when a new object is created, if no value is provided in the request body. Since default values are applied on db level, they should be literal values, not expressions.If you want to use expressions, you can use transposed parameters in any business API to set default values dynamically.

Always Create with Default Values

Some of the default values are set to be always used when creating a new object, even if the property value is provided in the request body. It ensures that the property is always initialized with a default value when the object is created.

Constant Properties

contentType contentId reportType reportedByUserId reportedAt

Constant properties are defined to be immutable after creation, meaning they cannot be updated or changed once set. They are typically used for properties that should remain constant throughout the object’s lifecycle. A property is set to be constant if the Allow Update option is set to false.

Auto Update Properties

contentType contentId reportType reportedByUserId reportedAt reviewStatus reviewAction actionedByUserId actionedAt

An update crud API created with the option Auto Params enabled will automatically update these properties with the provided values in the request body. If you want to update any property in your own business logic not by user input, you can set the Allow Auto Update option to false. These properties will be added to the update API’s body parameters and can be updated by the user if any value is provided in the request body.

Enum Properties

Enum properties are defined with a set of allowed values, ensuring that only valid options can be assigned to them. The enum options value will be stored as strings in the database, but when a data object is created an addtional property with the same name plus an idx suffix will be created, which will hold the index of the selected enum option. You can use the index property to sort by the enum value or when your enum options represent a sequence of values.

Elastic Search Indexing

contentType contentId reportType reportedByUserId reportedAt reviewStatus actionedByUserId actionedAt

Properties that are indexed in Elastic Search will be searchable via the Elastic Search API. While all properties are stored in the elastic search index of the data object, only those marked for Elastic Search indexing will be available for search queries.

Database Indexing

contentType contentId reportedByUserId reviewStatus actionedByUserId

Properties that are indexed in the database will be optimized for query performance, allowing for faster data retrieval. Make a property indexed in the database if you want to use it frequently in query filters or sorting.

Relation Properties

reportedByUserId actionedByUserId

Mindbricks supports relations between data objects, allowing you to define how objects are linked together. You can define relations in the data object properties, which will be used to create foreign key constraints in the database. For complex joins operations, Mindbricks supportsa BFF pattern, where you can view dynamic and static views based on Elastic Search Indexes. Use db level relations for simple one-to-one or one-to-many relationships, and use BFF views for complex joins that require multiple data objects to be joined together.

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

On Delete: Set Null Required: Yes

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

On Delete: Set Null Required: No

Session Data Properties

reportedByUserId

Session data properties are used to store data that is specific to the user session, allowing for personalized experiences and temporary data storage. If a property is configured as session data, it will be automatically mapped to the related field in the user session during CRUD operations. Note that session data properties can not be mutated by the user, but only by the system.

This property is also used to store the owner of the session data, allowing for ownership checks and access control.

Filter Properties

contentType contentId reportType reviewStatus

Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API’s that have “Auto Params” enabled.


Service Design Specification - Object Design for suspensionRecord

Service Design Specification - Object Design for suspensionRecord

auteurlabb-moderationadmin-service documentation

Document Overview

This document outlines the object design for the suspensionRecord model in our application. It includes details about the model’s attributes, relationships, and any specific validation or business logic that applies.

suspensionRecord Data Object

Object Overview

Description: Admin action to suspend or lift suspension on a user. Each record logs a suspension/lift action for audit/compliance.

This object represents a core data structure within the service and acts as the blueprint for database interaction, API generation, and business logic enforcement. It is defined using the ObjectSettings pattern, which governs its behavior, access control, caching strategy, and integration points with other systems such as Stripe and Redis.

Core Configuration

Properties Schema

Property Type Required Description
userId ID Yes Suspended user id
reason String Yes Reason for suspension action
suspendedByUserId ID Yes Admin ID who performed the suspension action
suspendedAt Date Yes Time of action (suspend/lift)
status Enum Yes Current state: active (suspended), lifted (reinstated)

Default Values

Default values are automatically assigned to properties when a new object is created, if no value is provided in the request body. Since default values are applied on db level, they should be literal values, not expressions.If you want to use expressions, you can use transposed parameters in any business API to set default values dynamically.

Always Create with Default Values

Some of the default values are set to be always used when creating a new object, even if the property value is provided in the request body. It ensures that the property is always initialized with a default value when the object is created.

Constant Properties

userId reason suspendedByUserId suspendedAt status

Constant properties are defined to be immutable after creation, meaning they cannot be updated or changed once set. They are typically used for properties that should remain constant throughout the object’s lifecycle. A property is set to be constant if the Allow Update option is set to false.

Auto Update Properties

userId reason suspendedByUserId suspendedAt status

An update crud API created with the option Auto Params enabled will automatically update these properties with the provided values in the request body. If you want to update any property in your own business logic not by user input, you can set the Allow Auto Update option to false. These properties will be added to the update API’s body parameters and can be updated by the user if any value is provided in the request body.

Enum Properties

Enum properties are defined with a set of allowed values, ensuring that only valid options can be assigned to them. The enum options value will be stored as strings in the database, but when a data object is created an addtional property with the same name plus an idx suffix will be created, which will hold the index of the selected enum option. You can use the index property to sort by the enum value or when your enum options represent a sequence of values.

Elastic Search Indexing

userId suspendedByUserId suspendedAt status

Properties that are indexed in Elastic Search will be searchable via the Elastic Search API. While all properties are stored in the elastic search index of the data object, only those marked for Elastic Search indexing will be available for search queries.

Database Indexing

userId suspendedByUserId status

Properties that are indexed in the database will be optimized for query performance, allowing for faster data retrieval. Make a property indexed in the database if you want to use it frequently in query filters or sorting.

Relation Properties

userId suspendedByUserId

Mindbricks supports relations between data objects, allowing you to define how objects are linked together. You can define relations in the data object properties, which will be used to create foreign key constraints in the database. For complex joins operations, Mindbricks supportsa BFF pattern, where you can view dynamic and static views based on Elastic Search Indexes. Use db level relations for simple one-to-one or one-to-many relationships, and use BFF views for complex joins that require multiple data objects to be joined together.

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

On Delete: Set Null Required: Yes

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

On Delete: Set Null Required: Yes


Service Design Specification - Object Design for auditLog

Service Design Specification - Object Design for auditLog

auteurlabb-moderationadmin-service documentation

Document Overview

This document outlines the object design for the auditLog model in our application. It includes details about the model’s attributes, relationships, and any specific validation or business logic that applies.

auditLog Data Object

Object Overview

Description: Generic audit log for all admin/moderation actions across services/objects for compliance and traceability.

This object represents a core data structure within the service and acts as the blueprint for database interaction, API generation, and business logic enforcement. It is defined using the ObjectSettings pattern, which governs its behavior, access control, caching strategy, and integration points with other systems such as Stripe and Redis.

Core Configuration

Properties Schema

Property Type Required Description
actionType String Yes Type of admin action (created, updated, suspended, approved, etc.)
actorUserId ID Yes User ID of admin/staff performing the action
targetType String Yes Type of object affected by this action (approvalRequest, reportLog, suspensionRecord, etc.)
targetId ID Yes ID of the object affected by this action
details Text No Freeform details, note, or JSON blob describing action context
actionAt Date Yes When the action occurred

Default Values

Default values are automatically assigned to properties when a new object is created, if no value is provided in the request body. Since default values are applied on db level, they should be literal values, not expressions.If you want to use expressions, you can use transposed parameters in any business API to set default values dynamically.

Constant Properties

actionType actorUserId targetType targetId details actionAt

Constant properties are defined to be immutable after creation, meaning they cannot be updated or changed once set. They are typically used for properties that should remain constant throughout the object’s lifecycle. A property is set to be constant if the Allow Update option is set to false.

Auto Update Properties

actionType actorUserId targetType targetId details actionAt

An update crud API created with the option Auto Params enabled will automatically update these properties with the provided values in the request body. If you want to update any property in your own business logic not by user input, you can set the Allow Auto Update option to false. These properties will be added to the update API’s body parameters and can be updated by the user if any value is provided in the request body.

Elastic Search Indexing

actionType actorUserId targetType targetId actionAt

Properties that are indexed in Elastic Search will be searchable via the Elastic Search API. While all properties are stored in the elastic search index of the data object, only those marked for Elastic Search indexing will be available for search queries.


Business APIs

Business API Design Specification - Create Approvalrequest

Business API Design Specification - Create Approvalrequest

A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic.

While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized.

This document provides an in-depth explanation of the architectural design of the createApprovalRequest Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side.

Main Data Object and CRUD Operation

The createApprovalRequest Business API is designed to handle a create operation on the ApprovalRequest data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

Create a new approval request for studio, investor, or project. Status defaults to pending. Only non-admins can create requests for themselvessss.

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The createApprovalRequest Business API includes a REST controller that can be triggered via the following route:

/v1/approvalrequests

By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the Parameters section.

MCP Tool

REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This createApprovalRequest Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The createApprovalRequest Business API has 8 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client.

Business API parameters can be:

Regular Parameters

Name Type Required Default Location Data Path
approvalRequestId ID No - body approvalRequestId
Description: This id paremeter is used to create the data object with a given specific id. Leave null for automatic id.
targetType Enum Yes - body targetType
Description: Type of entity being approved (studio, investor, project)
targetId ID Yes - body targetId
Description: ID of entity being approved (user or project, depending on type)
requestedAt Date Yes - body requestedAt
Description: Request creation time
requestedByUserId ID Yes - session userId
Description: User ID who created the request
reviewedAt Date No - body reviewedAt
Description: Date/time request reviewed
reviewedByUserId ID No - body reviewedByUserId
Description: Admin userId who reviewed the request
adminNote String No - body adminNote
Description: Review note left by admin.

Parameter Transformations

Some parameters are post-processed using transform scripts after being read from the request but before validation or workflow execution. Only parameters with a transform script are listed below.

No parameters are transformed in this API.

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the createApprovalRequest Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Data Clause

Defines custom field-value assignments used to modify or augment the default payload for create and update operations. These settings override values derived from the session or parameters if explicitly provided.", Note that a default data clause is always prepared by Mindbricks using data property settings, however any property in the data clause can be override by Data Clause Settings.

Custom Data Clause Override

{
    status: runMScript(() => ("pending"), {"path":"services[3].businessLogic[0].dataClause.customData[0].value"}),
    requestedAt: runMScript(() => (new Date()), {"path":"services[3].businessLogic[0].dataClause.customData[1].value"}),
   
}

Actual Data Clause

The business api will use the following data clause. Note that any calculated value will be added to the data clause in the api manager.

{
  id: this.approvalRequestId,
  targetType: this.targetType,
  targetId: this.targetId,
  requestedAt: runMScript(() => (new Date()), {"path":"services[3].businessLogic[0].dataClause.customData[1].value"}),
  requestedByUserId: this.requestedByUserId,
  reviewedAt: this.reviewedAt,
  reviewedByUserId: this.reviewedByUserId,
  adminNote: this.adminNote,
  status: runMScript(() => ("pending"), {"path":"services[3].businessLogic[0].dataClause.customData[0].value"}),
  isActive: true,
  _archivedAt: null,
}

Business Logic Workflow

[1] Step : startBusinessApi

Manager initializes context, populates session and request objects, prepares internal structures for parameter handling and workflow execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Manager reads input parameters, normalizes missing values, applies default type casting, and stores them in the API context.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Manager transforms parameters, computes derived values, flattens or remaps arrays/objects, and adjusts formats for downstream processing.


[4] Step : checkParameters

Manager executes built-in validations: required field checks, type enforcement, and basic business rules. Prevents operation if validation fails.


[5] Step : checkBasicAuth

Manager performs authentication and authorization checks: verifies session, user roles, permissions, and tenant restrictions.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildDataClause

Manager constructs the final data object for creation, fills auto-generated fields (IDs, timestamps, owner fields), and ensures schema consistency.

You can use the following settings to change some behavior of this step. dataClause

[7] Step : mainCreateOperation

Manager executes the database insert operation, updates indexes/caches, and triggers internal post-processing like linked default records.


[8] Step : buildOutput

Manager shapes the response: masks sensitive fields, resolves linked references, and formats output according to API contract.


[9] Step : sendResponse

Manager sends the response to the client and finalizes internal tasks like flushing logs or updating session state.


[10] Step : raiseApiEvent

Manager triggers API-level events (Kafka, WebSocket, async workflows) as the final internal step.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The createApprovalRequest api has got 6 regular client parameters

Parameter Type Required Population
targetType Enum true request.body?.[“targetType”]
targetId ID true request.body?.[“targetId”]
requestedAt Date true request.body?.[“requestedAt”]
reviewedAt Date false request.body?.[“reviewedAt”]
reviewedByUserId ID false request.body?.[“reviewedByUserId”]
adminNote String false request.body?.[“adminNote”]

REST Request

To access the api you can use the REST controller with the path POST /v1/approvalrequests

  axios({
    method: 'POST',
    url: '/v1/approvalrequests',
    data: {
            targetType:"Enum",  
            targetId:"ID",  
            requestedAt:"Date",  
            reviewedAt:"Date",  
            reviewedByUserId:"ID",  
            adminNote:"String",  
    
    },
    params: {
    
        }
  });

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the approvalRequest object in the respones. However, some properties may be omitted based on the object’s internal logic.

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "approvalRequest",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"approvalRequest": {
		"id": "ID",
		"targetType": "Enum",
		"targetType_idx": "Integer",
		"targetId": "ID",
		"requestedAt": "Date",
		"requestedByUserId": "ID",
		"status": "Enum",
		"status_idx": "Integer",
		"reviewedAt": "Date",
		"reviewedByUserId": "ID",
		"adminNote": "String",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Business API Design Specification - Review Approvalrequest

Business API Design Specification - Review Approvalrequest

A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic.

While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized.

This document provides an in-depth explanation of the architectural design of the reviewApprovalRequest Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side.

Main Data Object and CRUD Operation

The reviewApprovalRequest Business API is designed to handle a update operation on the ApprovalRequest data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

Approve or reject an approval request. Only superAdmin or admin may update status or add review notes.

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The reviewApprovalRequest Business API includes a REST controller that can be triggered via the following route:

/v1/reviewapprovalrequest/:approvalRequestId

By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the Parameters section.

MCP Tool

REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This reviewApprovalRequest Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The reviewApprovalRequest Business API has 5 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client.

Business API parameters can be:

Regular Parameters

Name Type Required Default Location Data Path
approvalRequestId ID Yes - urlpath approvalRequestId
Description: This id paremeter is used to select the required data object that will be updated
status Enum Yes - body status
Description: Approval status: pending/approved/rejected
reviewedAt Date No - body reviewedAt
Description: Date/time request reviewed
reviewedByUserId ID No - body reviewedByUserId
Description: Admin userId who reviewed the request
adminNote String No - body adminNote
Description: Review note left by admin.

Parameter Transformations

Some parameters are post-processed using transform scripts after being read from the request but before validation or workflow execution. Only parameters with a transform script are listed below.

No parameters are transformed in this API.

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the reviewApprovalRequest Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({$and:[{id:this.approvalRequestId},{isActive:true}]}), {"path":"services[3].businessLogic[1].whereClause.fullWhereClause"})

Data Clause

Defines custom field-value assignments used to modify or augment the default payload for create and update operations. These settings override values derived from the session or parameters if explicitly provided.", Note that a default data clause is always prepared by Mindbricks using data property settings, however any property in the data clause can be override by Data Clause Settings.

An update data clause populates all update-allowed properties of a data object, however the null properties (that are not provided by client) are ignored in db layer.

Custom Data Clause Override No custom data clause override configured

Actual Data Clause

The business api will use the following data clause. Note that any calculated value will be added to the data clause in the api manager.

{
  status: this.status,
  reviewedAt: this.reviewedAt,
  reviewedByUserId: this.reviewedByUserId,
  adminNote: this.adminNote,
}

Business Logic Workflow

[1] Step : startBusinessApi

Manager initializes context, prepares request and session objects, and sets up internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Manager reads parameters from the request or Redis, applies defaults, and writes them into context for downstream milestones.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Manager executes parameter transform scripts and derives any helper values or reshaped payloads into the context.


[4] Step : checkParameters

Manager validates required parameters, checks ID formats (UUID/ObjectId), and ensures all preconditions for update are met.


[5] Action : checkStatusChangeAuthorization

Action Type: ValidationAction

Only superAdmin or admin can approve/reject requests.

class Api {
  async checkStatusChangeAuthorization() {
    if (this.checkAbsolute()) return true;

    const isValid = runMScript(
      () =>
        ["approved", "rejected"].includes(this.status)
          ? this.session.roleId === "admin" ||
            this.session.roleId === "superAdmin"
          : true,
      {
        path: "services[3].businessLogic[1].actions.validationActions[0].validationScript",
      },
    );

    if (!isValid) {
      throw new ForbiddenError("Only admins may approve/reject requests.");
    }
    return isValid;
  }
}

[6] Step : checkBasicAuth

Manager performs login verification, role, and permission checks, enforcing tenant and access rules before update.

You can use the following settings to change some behavior of this step. authOptions

[7] Step : buildWhereClause

Manager constructs the WHERE clause used to identify the record to update, applying ownership and parent checks if necessary.

You can use the following settings to change some behavior of this step. whereClause

[8] Step : fetchInstance

Manager fetches the existing record from the database and writes it to the context for validation or enrichment.


[9] Step : checkInstance

Manager performs instance-level validations, including ownership, existence, lock status, or other pre-update checks.


[10] Step : buildDataClause

Manager prepares the data clause for the update, applying transformations or enhancements before persisting.

You can use the following settings to change some behavior of this step. dataClause

[11] Step : mainUpdateOperation

Manager executes the update operation with the WHERE and data clauses. Database-level events are raised if configured.


[12] Action : logApprovalDecision

Action Type: PublishEventAction

On review action, log to the auditLog.

class Api {
  async logApprovalDecision() {
    const message = {
      actionType: "approvalReview",
      actorUserId: this.session.userId,
      targetType: "approvalRequest",
      targetId: this.approvalRequest.id,
      details: JSON.stringify({
        status: this.status,
        adminNote: this.adminNote,
      }),
      actionAt: new Date(),
    };

    // Publish event to the configured topic
    const _publisher = new ServicePublisher(
      "audit.approvalRequest.reviewed",
      message,
      this.session,
      this.requestId,
    );
    await _publisher.publish();
    return true;
  }
}

[13] Step : buildOutput

Manager assembles the response object from the update result, masking fields or injecting additional metadata.


[14] Step : sendResponse

Manager sends the response back to the controller for delivery to the client.


[15] Step : raiseApiEvent

Manager triggers API-level events, sending relevant messages to Kafka or other integrations if configured.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The reviewApprovalRequest api has got 5 regular client parameters

Parameter Type Required Population
approvalRequestId ID true request.params?.[“approvalRequestId”]
status Enum true request.body?.[“status”]
reviewedAt Date false request.body?.[“reviewedAt”]
reviewedByUserId ID false request.body?.[“reviewedByUserId”]
adminNote String false request.body?.[“adminNote”]

REST Request

To access the api you can use the REST controller with the path PATCH /v1/reviewapprovalrequest/:approvalRequestId

  axios({
    method: 'PATCH',
    url: `/v1/reviewapprovalrequest/${approvalRequestId}`,
    data: {
            status:"Enum",  
            reviewedAt:"Date",  
            reviewedByUserId:"ID",  
            adminNote:"String",  
    
    },
    params: {
    
        }
  });

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the approvalRequest object in the respones. However, some properties may be omitted based on the object’s internal logic.

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "approvalRequest",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"approvalRequest": {
		"id": "ID",
		"targetType": "Enum",
		"targetType_idx": "Integer",
		"targetId": "ID",
		"requestedAt": "Date",
		"requestedByUserId": "ID",
		"status": "Enum",
		"status_idx": "Integer",
		"reviewedAt": "Date",
		"reviewedByUserId": "ID",
		"adminNote": "String",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Business API Design Specification - Get Approvalrequest

Business API Design Specification - Get Approvalrequest

A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic.

While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized.

This document provides an in-depth explanation of the architectural design of the getApprovalRequest Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side.

Main Data Object and CRUD Operation

The getApprovalRequest Business API is designed to handle a get operation on the ApprovalRequest data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

Get a single approvalRequest. Only owner or admin may view.

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The getApprovalRequest Business API includes a REST controller that can be triggered via the following route:

/v1/approvalrequests/:approvalRequestId

By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the Parameters section.

MCP Tool

REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This getApprovalRequest Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The getApprovalRequest Business API has 1 parameter that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client.

Business API parameters can be:

Regular Parameters

Name Type Required Default Location Data Path
approvalRequestId ID Yes - urlpath approvalRequestId
Description: This id paremeter is used to query the required data object.

Parameter Transformations

Some parameters are post-processed using transform scripts after being read from the request but before validation or workflow execution. Only parameters with a transform script are listed below.

No parameters are transformed in this API.

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the getApprovalRequest Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks

This Business API enforces ownership of the main data object before executing the operation.


Role and Permission Settings


Select Clause

Specifies which fields will be selected from the main data object during a get or list operation. Leave blank to select all properties. This applies only to get and list type APIs.",

``

Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({$and:[{id:this.approvalRequestId},{isActive:true}]}), {"path":"services[3].businessLogic[2].whereClause.fullWhereClause"})

Get Options

Use these options to set get specific settings.

setAsRead: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed.

No setAsread field-value pair is configured.

Business Logic Workflow

[1] Step : startBusinessApi

Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Extracts parameters from request and Redis, applies defaults, and writes them to context.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Executes parameter transformation scripts, applies type coercion, merges derived values, and reshapes inputs for downstream milestones.


[4] Step : checkParameters

Validates required and custom parameters, enforcing business-specific rules and constraints.


[5] Step : checkBasicAuth

Performs login, role, and permission checks, and applies dynamic object-level access rules.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildWhereClause

Builds the WHERE clause for fetching the object and applies additional scoped filters if configured.

You can use the following settings to change some behavior of this step. whereClause

[7] Step : mainGetOperation

Executes the database fetch, retrieves the object, and stores it in context for enrichment or further checks.

You can use the following settings to change some behavior of this step. selectClause, getOptions

[8] Step : checkInstance

Performs instance-level validations, such as ownership, existence, or access conditions.


[9] Step : buildOutput

Assembles the response from the object, applies masking, formatting, and injects additional metadata if needed.


[10] Step : sendResponse

Delivers the response to the controller for client delivery.


[11] Step : raiseApiEvent

Triggers optional API-level events after workflow completion, sending messages to integrations like Kafka if configured.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The getApprovalRequest api has got 1 regular client parameter

Parameter Type Required Population
approvalRequestId ID true request.params?.[“approvalRequestId”]

REST Request

To access the api you can use the REST controller with the path GET /v1/approvalrequests/:approvalRequestId

  axios({
    method: 'GET',
    url: `/v1/approvalrequests/${approvalRequestId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the approvalRequest object in the respones. However, some properties may be omitted based on the object’s internal logic.

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "approvalRequest",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"approvalRequest": {
		"id": "ID",
		"targetType": "Enum",
		"targetType_idx": "Integer",
		"targetId": "ID",
		"requestedAt": "Date",
		"requestedByUserId": "ID",
		"status": "Enum",
		"status_idx": "Integer",
		"reviewedAt": "Date",
		"reviewedByUserId": "ID",
		"adminNote": "String",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"requester": {
			"email": "String",
			"fullname": "String",
			"roleId": "String"
		},
		"reviewer": {
			"email": "String",
			"fullname": "String"
		}
	}
}

Business API Design Specification - List Approvalrequests

Business API Design Specification - List Approvalrequests

A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic.

While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized.

This document provides an in-depth explanation of the architectural design of the listApprovalRequests Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side.

Main Data Object and CRUD Operation

The listApprovalRequests Business API is designed to handle a list operation on the ApprovalRequest data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

List approval requests. Admins see all, non-admins see only their own.

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The listApprovalRequests Business API includes a REST controller that can be triggered via the following route:

/v1/approvalrequests

By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the Parameters section.

MCP Tool

REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This listApprovalRequests Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The listApprovalRequests Business API has 3 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client.

Business API parameters can be:

Filter Parameters

The listApprovalRequests api supports 3 optional filter parameters for filtering list results using URL query parameters. These parameters are only available for list type APIs.

targetType Filter

Type: Enum
Description: Type of entity being approved (studio, investor, project)
Location: Query Parameter

Usage:

Examples:

// Get records with specific enum value
GET /v1/approvalrequests?targetType=active

// Get records with multiple enum values (use multiple parameters)
GET /v1/approvalrequests?targetType=active&targetType=pending

// Get records without this field
GET /v1/approvalrequests?targetType=null

targetId Filter

Type: ID
Description: ID of entity being approved (user or project, depending on type)
Location: Query Parameter

Usage:

Non-Array Property:

Examples:

// Get records with a specific ID
GET /v1/approvalrequests?targetId=550e8400-e29b-41d4-a716-446655440000

// Get records with multiple IDs (use multiple parameters)
GET /v1/approvalrequests?targetId=550e8400-e29b-41d4-a716-446655440000&targetId=660e8400-e29b-41d4-a716-446655440001

// Get records without this field
GET /v1/approvalrequests?targetId=null

status Filter

Type: Enum
Description: Approval status: pending/approved/rejected
Location: Query Parameter

Usage:

Examples:

// Get records with specific enum value
GET /v1/approvalrequests?status=active

// Get records with multiple enum values (use multiple parameters)
GET /v1/approvalrequests?status=active&status=pending

// Get records without this field
GET /v1/approvalrequests?status=null

Parameter Transformations

Some parameters are post-processed using transform scripts after being read from the request but before validation or workflow execution. Only parameters with a transform script are listed below.

No parameters are transformed in this API.

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the listApprovalRequests Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Select Clause

Specifies which fields will be selected from the main data object during a get or list operation. Leave blank to select all properties. This applies only to get and list type APIs.",

``

Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.


// Addtional Clause Name : scopeToRequester

// condition doWhen 
// this.session.roleId !== &#39;admin&#39; &amp;&amp; this.session.roleId !== &#39;superAdmin&#39;

// condition excludeWhen
// No excludeWhen condtion defined

// clause object
{requestedByUserId: this.session.userId}

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({isActive:true}), {"path":"services[3].businessLogic[3].whereClause.fullWhereClause"})

List Options

Defines list-specific options including filtering logic, default sorting, and result customization for APIs that return multiple records.

List Sort By Sort order definitions for the result set. Multiple fields can be provided with direction (asc/desc).

Specific sort order is not configure, natural order (ascending id) will be used.

List Group By Grouping definitions for the result set. This is typically used for visual or report-based grouping.

The list is not grouped.

setAsRead: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed.

No setAsread field-value pair is configured.

Permission Filter Optional filter that applies permission constraints dynamically based on session or object roles. So that the list items are filtered by the user’s OBAC or ABAC permissions.

Permission filter is not active at the moment. Follow Mindbricks updates to be able to use it.

Pagination Options

Contains settings to configure pagination behavior for list APIs. Includes options like page size, offset, cursor support, and total count inclusion.

Business Logic Workflow

[1] Step : startBusinessApi

Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Reads request and Redis parameters, applies defaults, and writes them to context for downstream processing.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Transforms and normalizes parameters, derives dependent values, and reshapes inputs for the main list query.


[4] Step : checkParameters

Executes validation logic on required and custom parameters, enforcing business rules and cross-field consistency.


[5] Step : checkBasicAuth

Performs role-based access checks and applies dynamic membership or session-based restrictions.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildWhereClause

Constructs the main query WHERE clause and applies optional filters or scoped access controls.

You can use the following settings to change some behavior of this step. whereClause

[7] Step : mainListOperation

Executes the paginated database query, retrieves the list, and stores results in context for enrichment.

You can use the following settings to change some behavior of this step. selectClause, listOptions, paginationOptions

[8] Step : buildOutput

Assembles the list response, sanitizes sensitive fields, applies transformations, and injects extra context if needed.


[9] Step : sendResponse

Sends the paginated list to the client through the controller.


[10] Step : raiseApiEvent

Triggers optional post-workflow events, such as Kafka messages, logs, or system notifications.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The listApprovalRequests api has 3 filter parameters available for filtering list results. See the Filter Parameters section above for detailed usage examples.

Filter Parameter Type Array Property Description
targetType Enum No Type of entity being approved (studio, investor, project)
targetId ID No ID of entity being approved (user or project, depending on type)
status Enum No Approval status: pending/approved/rejected

REST Request

To access the api you can use the REST controller with the path GET /v1/approvalrequests

  axios({
    method: 'GET',
    url: '/v1/approvalrequests',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section for usage examples)
        // targetType: '<value>' // Filter by targetType
        // targetId: '<value>' // Filter by targetId
        // status: '<value>' // Filter by status
            }
  });

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the approvalRequests object in the respones. However, some properties may be omitted based on the object’s internal logic.

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "approvalRequests",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"approvalRequests": [
		{
			"id": "ID",
			"targetType": "Enum",
			"targetType_idx": "Integer",
			"targetId": "ID",
			"requestedAt": "Date",
			"requestedByUserId": "ID",
			"status": "Enum",
			"status_idx": "Integer",
			"reviewedAt": "Date",
			"reviewedByUserId": "ID",
			"adminNote": "String",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID",
			"requester": [
				{
					"email": "String",
					"fullname": "String",
					"roleId": "String"
				},
				{},
				{}
			],
			"reviewer": [
				{
					"email": "String",
					"fullname": "String"
				},
				{},
				{}
			]
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Business API Design Specification - Create Reportlog

Business API Design Specification - Create Reportlog

A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic.

While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized.

This document provides an in-depth explanation of the architectural design of the createReportLog Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side.

Main Data Object and CRUD Operation

The createReportLog Business API is designed to handle a create operation on the ReportLog data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

Create a content/user/project moderation report

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The createReportLog Business API includes a REST controller that can be triggered via the following route:

/v1/reportlogs

By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the Parameters section.

MCP Tool

REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This createReportLog Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The createReportLog Business API has 9 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client.

Business API parameters can be:

Regular Parameters

Name Type Required Default Location Data Path
reportLogId ID No - body reportLogId
Description: This id paremeter is used to create the data object with a given specific id. Leave null for automatic id.
contentType Enum Yes - body contentType
Description: Type of content being reported: project/message/user
contentId ID Yes - body contentId
Description: ID of the reported content (project ID, message ID, user ID)
reportType String Yes - body reportType
Description: Nature of report (abuse, spam, copyright, etc.)
reportedByUserId ID Yes - session userId
Description: ID of user reporting
reportedAt Date Yes - body reportedAt
Description: Report creation timestamp
reviewAction String No - body reviewAction
Description: Action taken by admin (removed, warned, etc.) or note
actionedByUserId ID No - body actionedByUserId
Description: Admin making the moderation action
actionedAt Date No - body actionedAt
Description: Time of moderation action

Parameter Transformations

Some parameters are post-processed using transform scripts after being read from the request but before validation or workflow execution. Only parameters with a transform script are listed below.

No parameters are transformed in this API.

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the createReportLog Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Data Clause

Defines custom field-value assignments used to modify or augment the default payload for create and update operations. These settings override values derived from the session or parameters if explicitly provided.", Note that a default data clause is always prepared by Mindbricks using data property settings, however any property in the data clause can be override by Data Clause Settings.

Custom Data Clause Override

{
    reviewStatus: runMScript(() => ("open"), {"path":"services[3].businessLogic[4].dataClause.customData[0].value"}),
    reportedAt: runMScript(() => (new Date()), {"path":"services[3].businessLogic[4].dataClause.customData[1].value"}),
   
}

Actual Data Clause

The business api will use the following data clause. Note that any calculated value will be added to the data clause in the api manager.

{
  id: this.reportLogId,
  contentType: this.contentType,
  contentId: this.contentId,
  reportType: this.reportType,
  reportedByUserId: this.reportedByUserId,
  reportedAt: runMScript(() => (new Date()), {"path":"services[3].businessLogic[4].dataClause.customData[1].value"}),
  reviewAction: this.reviewAction,
  actionedByUserId: this.actionedByUserId,
  actionedAt: this.actionedAt,
  reviewStatus: runMScript(() => ("open"), {"path":"services[3].businessLogic[4].dataClause.customData[0].value"}),
  isActive: true,
  _archivedAt: null,
}

Business Logic Workflow

[1] Step : startBusinessApi

Manager initializes context, populates session and request objects, prepares internal structures for parameter handling and workflow execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Manager reads input parameters, normalizes missing values, applies default type casting, and stores them in the API context.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Manager transforms parameters, computes derived values, flattens or remaps arrays/objects, and adjusts formats for downstream processing.


[4] Step : checkParameters

Manager executes built-in validations: required field checks, type enforcement, and basic business rules. Prevents operation if validation fails.


[5] Step : checkBasicAuth

Manager performs authentication and authorization checks: verifies session, user roles, permissions, and tenant restrictions.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildDataClause

Manager constructs the final data object for creation, fills auto-generated fields (IDs, timestamps, owner fields), and ensures schema consistency.

You can use the following settings to change some behavior of this step. dataClause

[7] Step : mainCreateOperation

Manager executes the database insert operation, updates indexes/caches, and triggers internal post-processing like linked default records.


[8] Step : buildOutput

Manager shapes the response: masks sensitive fields, resolves linked references, and formats output according to API contract.


[9] Step : sendResponse

Manager sends the response to the client and finalizes internal tasks like flushing logs or updating session state.


[10] Step : raiseApiEvent

Manager triggers API-level events (Kafka, WebSocket, async workflows) as the final internal step.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The createReportLog api has got 7 regular client parameters

Parameter Type Required Population
contentType Enum true request.body?.[“contentType”]
contentId ID true request.body?.[“contentId”]
reportType String true request.body?.[“reportType”]
reportedAt Date true request.body?.[“reportedAt”]
reviewAction String false request.body?.[“reviewAction”]
actionedByUserId ID false request.body?.[“actionedByUserId”]
actionedAt Date false request.body?.[“actionedAt”]

REST Request

To access the api you can use the REST controller with the path POST /v1/reportlogs

  axios({
    method: 'POST',
    url: '/v1/reportlogs',
    data: {
            contentType:"Enum",  
            contentId:"ID",  
            reportType:"String",  
            reportedAt:"Date",  
            reviewAction:"String",  
            actionedByUserId:"ID",  
            actionedAt:"Date",  
    
    },
    params: {
    
        }
  });

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the reportLog object in the respones. However, some properties may be omitted based on the object’s internal logic.

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "reportLog",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"reportLog": {
		"id": "ID",
		"contentType": "Enum",
		"contentType_idx": "Integer",
		"contentId": "ID",
		"reportType": "String",
		"reportedByUserId": "ID",
		"reportedAt": "Date",
		"reviewStatus": "Enum",
		"reviewStatus_idx": "Integer",
		"reviewAction": "String",
		"actionedByUserId": "ID",
		"actionedAt": "Date",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Business API Design Specification - Review Reportlog

Business API Design Specification - Review Reportlog

A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic.

While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized.

This document provides an in-depth explanation of the architectural design of the reviewReportLog Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side.

Main Data Object and CRUD Operation

The reviewReportLog Business API is designed to handle a update operation on the ReportLog data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

Admin-only: Close/ignore a report, add review action/note. Only superAdmin/admin allowed.

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The reviewReportLog Business API includes a REST controller that can be triggered via the following route:

/v1/reviewreportlog/:reportLogId

By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the Parameters section.

MCP Tool

REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This reviewReportLog Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The reviewReportLog Business API has 5 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client.

Business API parameters can be:

Regular Parameters

Name Type Required Default Location Data Path
reportLogId ID Yes - urlpath reportLogId
Description: This id paremeter is used to select the required data object that will be updated
reviewStatus Enum Yes - body reviewStatus
Description: Open/closed/ignored
reviewAction String No - body reviewAction
Description: Action taken by admin (removed, warned, etc.) or note
actionedByUserId ID No - body actionedByUserId
Description: Admin making the moderation action
actionedAt Date No - body actionedAt
Description: Time of moderation action

Parameter Transformations

Some parameters are post-processed using transform scripts after being read from the request but before validation or workflow execution. Only parameters with a transform script are listed below.

No parameters are transformed in this API.

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the reviewReportLog Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({$and:[{id:this.reportLogId},{isActive:true}]}), {"path":"services[3].businessLogic[5].whereClause.fullWhereClause"})

Data Clause

Defines custom field-value assignments used to modify or augment the default payload for create and update operations. These settings override values derived from the session or parameters if explicitly provided.", Note that a default data clause is always prepared by Mindbricks using data property settings, however any property in the data clause can be override by Data Clause Settings.

An update data clause populates all update-allowed properties of a data object, however the null properties (that are not provided by client) are ignored in db layer.

Custom Data Clause Override No custom data clause override configured

Actual Data Clause

The business api will use the following data clause. Note that any calculated value will be added to the data clause in the api manager.

{
  reviewStatus: this.reviewStatus,
  reviewAction: this.reviewAction,
  actionedByUserId: this.actionedByUserId,
  actionedAt: this.actionedAt,
}

Business Logic Workflow

[1] Step : startBusinessApi

Manager initializes context, prepares request and session objects, and sets up internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Manager reads parameters from the request or Redis, applies defaults, and writes them into context for downstream milestones.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Manager executes parameter transform scripts and derives any helper values or reshaped payloads into the context.


[4] Step : checkParameters

Manager validates required parameters, checks ID formats (UUID/ObjectId), and ensures all preconditions for update are met.


[5] Action : checkAdminCanReviewReport

Action Type: ValidationAction

Only admins may update reviewStatus or add reviewAction.

class Api {
  async checkAdminCanReviewReport() {
    if (this.checkAbsolute()) return true;

    const isValid = runMScript(
      () =>
        ["closed", "ignored"].includes(this.reviewStatus)
          ? this.session.roleId === "admin" ||
            this.session.roleId === "superAdmin"
          : true,
      {
        path: "services[3].businessLogic[5].actions.validationActions[0].validationScript",
      },
    );

    if (!isValid) {
      throw new ForbiddenError("Only admins may close/resolve/ignore reports.");
    }
    return isValid;
  }
}

[6] Step : checkBasicAuth

Manager performs login verification, role, and permission checks, enforcing tenant and access rules before update.

You can use the following settings to change some behavior of this step. authOptions

[7] Step : buildWhereClause

Manager constructs the WHERE clause used to identify the record to update, applying ownership and parent checks if necessary.

You can use the following settings to change some behavior of this step. whereClause

[8] Step : fetchInstance

Manager fetches the existing record from the database and writes it to the context for validation or enrichment.


[9] Step : checkInstance

Manager performs instance-level validations, including ownership, existence, lock status, or other pre-update checks.


[10] Step : buildDataClause

Manager prepares the data clause for the update, applying transformations or enhancements before persisting.

You can use the following settings to change some behavior of this step. dataClause

[11] Step : mainUpdateOperation

Manager executes the update operation with the WHERE and data clauses. Database-level events are raised if configured.


[12] Action : logReportReviewed

Action Type: PublishEventAction

On report review, log to the auditLog.

class Api {
  async logReportReviewed() {
    const message = {
      actionType: "reportReview",
      actorUserId: this.session.userId,
      targetType: "reportLog",
      targetId: this.reportLog.id,
      details: JSON.stringify({
        reviewStatus: this.reviewStatus,
        reviewAction: this.reviewAction,
      }),
      actionAt: new Date(),
    };

    // Publish event to the configured topic
    const _publisher = new ServicePublisher(
      "audit.reportLog.reviewed",
      message,
      this.session,
      this.requestId,
    );
    await _publisher.publish();
    return true;
  }
}

[13] Step : buildOutput

Manager assembles the response object from the update result, masking fields or injecting additional metadata.


[14] Step : sendResponse

Manager sends the response back to the controller for delivery to the client.


[15] Step : raiseApiEvent

Manager triggers API-level events, sending relevant messages to Kafka or other integrations if configured.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The reviewReportLog api has got 5 regular client parameters

Parameter Type Required Population
reportLogId ID true request.params?.[“reportLogId”]
reviewStatus Enum true request.body?.[“reviewStatus”]
reviewAction String false request.body?.[“reviewAction”]
actionedByUserId ID false request.body?.[“actionedByUserId”]
actionedAt Date false request.body?.[“actionedAt”]

REST Request

To access the api you can use the REST controller with the path PATCH /v1/reviewreportlog/:reportLogId

  axios({
    method: 'PATCH',
    url: `/v1/reviewreportlog/${reportLogId}`,
    data: {
            reviewStatus:"Enum",  
            reviewAction:"String",  
            actionedByUserId:"ID",  
            actionedAt:"Date",  
    
    },
    params: {
    
        }
  });

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the reportLog object in the respones. However, some properties may be omitted based on the object’s internal logic.

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "reportLog",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"reportLog": {
		"id": "ID",
		"contentType": "Enum",
		"contentType_idx": "Integer",
		"contentId": "ID",
		"reportType": "String",
		"reportedByUserId": "ID",
		"reportedAt": "Date",
		"reviewStatus": "Enum",
		"reviewStatus_idx": "Integer",
		"reviewAction": "String",
		"actionedByUserId": "ID",
		"actionedAt": "Date",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Business API Design Specification - Get Reportlog

Business API Design Specification - Get Reportlog

A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic.

While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized.

This document provides an in-depth explanation of the architectural design of the getReportLog Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side.

Main Data Object and CRUD Operation

The getReportLog Business API is designed to handle a get operation on the ReportLog data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

Get a single report log. Only admins or reporting user may view.

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The getReportLog Business API includes a REST controller that can be triggered via the following route:

/v1/reportlogs/:reportLogId

By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the Parameters section.

MCP Tool

REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This getReportLog Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The getReportLog Business API has 1 parameter that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client.

Business API parameters can be:

Regular Parameters

Name Type Required Default Location Data Path
reportLogId ID Yes - urlpath reportLogId
Description: This id paremeter is used to query the required data object.

Parameter Transformations

Some parameters are post-processed using transform scripts after being read from the request but before validation or workflow execution. Only parameters with a transform script are listed below.

No parameters are transformed in this API.

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the getReportLog Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks

This Business API enforces ownership of the main data object before executing the operation.


Role and Permission Settings


Select Clause

Specifies which fields will be selected from the main data object during a get or list operation. Leave blank to select all properties. This applies only to get and list type APIs.",

``

Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({$and:[{id:this.reportLogId},{isActive:true}]}), {"path":"services[3].businessLogic[6].whereClause.fullWhereClause"})

Get Options

Use these options to set get specific settings.

setAsRead: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed.

No setAsread field-value pair is configured.

Business Logic Workflow

[1] Step : startBusinessApi

Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Extracts parameters from request and Redis, applies defaults, and writes them to context.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Executes parameter transformation scripts, applies type coercion, merges derived values, and reshapes inputs for downstream milestones.


[4] Step : checkParameters

Validates required and custom parameters, enforcing business-specific rules and constraints.


[5] Step : checkBasicAuth

Performs login, role, and permission checks, and applies dynamic object-level access rules.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildWhereClause

Builds the WHERE clause for fetching the object and applies additional scoped filters if configured.

You can use the following settings to change some behavior of this step. whereClause

[7] Step : mainGetOperation

Executes the database fetch, retrieves the object, and stores it in context for enrichment or further checks.

You can use the following settings to change some behavior of this step. selectClause, getOptions

[8] Step : checkInstance

Performs instance-level validations, such as ownership, existence, or access conditions.


[9] Step : buildOutput

Assembles the response from the object, applies masking, formatting, and injects additional metadata if needed.


[10] Step : sendResponse

Delivers the response to the controller for client delivery.


[11] Step : raiseApiEvent

Triggers optional API-level events after workflow completion, sending messages to integrations like Kafka if configured.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The getReportLog api has got 1 regular client parameter

Parameter Type Required Population
reportLogId ID true request.params?.[“reportLogId”]

REST Request

To access the api you can use the REST controller with the path GET /v1/reportlogs/:reportLogId

  axios({
    method: 'GET',
    url: `/v1/reportlogs/${reportLogId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the reportLog object in the respones. However, some properties may be omitted based on the object’s internal logic.

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "reportLog",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"reportLog": {
		"id": "ID",
		"contentType": "Enum",
		"contentType_idx": "Integer",
		"contentId": "ID",
		"reportType": "String",
		"reportedByUserId": "ID",
		"reportedAt": "Date",
		"reviewStatus": "Enum",
		"reviewStatus_idx": "Integer",
		"reviewAction": "String",
		"actionedByUserId": "ID",
		"actionedAt": "Date",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"reportedBy": {
			"email": "String",
			"fullname": "String",
			"roleId": "String"
		},
		"actionedBy": {
			"email": "String",
			"fullname": "String"
		}
	}
}

Business API Design Specification - List Reportlogs

Business API Design Specification - List Reportlogs

A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic.

While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized.

This document provides an in-depth explanation of the architectural design of the listReportLogs Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side.

Main Data Object and CRUD Operation

The listReportLogs Business API is designed to handle a list operation on the ReportLog data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

List moderation reports. Admins see all; other users see only their reports.

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The listReportLogs Business API includes a REST controller that can be triggered via the following route:

/v1/reportlogs

By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the Parameters section.

MCP Tool

REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This listReportLogs Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The listReportLogs Business API has 4 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client.

Business API parameters can be:

Filter Parameters

The listReportLogs api supports 4 optional filter parameters for filtering list results using URL query parameters. These parameters are only available for list type APIs.

contentType Filter

Type: Enum
Description: Type of content being reported: project/message/user
Location: Query Parameter

Usage:

Examples:

// Get records with specific enum value
GET /v1/reportlogs?contentType=active

// Get records with multiple enum values (use multiple parameters)
GET /v1/reportlogs?contentType=active&contentType=pending

// Get records without this field
GET /v1/reportlogs?contentType=null

contentId Filter

Type: ID
Description: ID of the reported content (project ID, message ID, user ID)
Location: Query Parameter

Usage:

Non-Array Property:

Examples:

// Get records with a specific ID
GET /v1/reportlogs?contentId=550e8400-e29b-41d4-a716-446655440000

// Get records with multiple IDs (use multiple parameters)
GET /v1/reportlogs?contentId=550e8400-e29b-41d4-a716-446655440000&contentId=660e8400-e29b-41d4-a716-446655440001

// Get records without this field
GET /v1/reportlogs?contentId=null

reportType Filter

Type: String
Description: Nature of report (abuse, spam, copyright, etc.)
Location: Query Parameter

Usage:

Non-Array Property (Case-Insensitive Partial Matching):

Examples:

// Find records with "john" in the field (case-insensitive partial match)
GET /v1/reportlogs?reportType=john
// Matches: "John", "Johnny", "johnson", "McJohn", etc.

// Find records with multiple values (use multiple parameters)
GET /v1/reportlogs?reportType=laptop&reportType=phone&reportType=tablet
// Matches records containing "laptop", "phone", or "tablet" anywhere in the field

// Find records without this field
GET /v1/reportlogs?reportType=null

reviewStatus Filter

Type: Enum
Description: Open/closed/ignored
Location: Query Parameter

Usage:

Examples:

// Get records with specific enum value
GET /v1/reportlogs?reviewStatus=active

// Get records with multiple enum values (use multiple parameters)
GET /v1/reportlogs?reviewStatus=active&reviewStatus=pending

// Get records without this field
GET /v1/reportlogs?reviewStatus=null

Parameter Transformations

Some parameters are post-processed using transform scripts after being read from the request but before validation or workflow execution. Only parameters with a transform script are listed below.

No parameters are transformed in this API.

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the listReportLogs Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Select Clause

Specifies which fields will be selected from the main data object during a get or list operation. Leave blank to select all properties. This applies only to get and list type APIs.",

``

Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.


// Addtional Clause Name : scopeToReporter

// condition doWhen 
// this.session.roleId !== &#39;admin&#39; &amp;&amp; this.session.roleId !== &#39;superAdmin&#39;

// condition excludeWhen
// No excludeWhen condtion defined

// clause object
{reportedByUserId: this.session.userId}

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({isActive:true}), {"path":"services[3].businessLogic[7].whereClause.fullWhereClause"})

List Options

Defines list-specific options including filtering logic, default sorting, and result customization for APIs that return multiple records.

List Sort By Sort order definitions for the result set. Multiple fields can be provided with direction (asc/desc).

Specific sort order is not configure, natural order (ascending id) will be used.

List Group By Grouping definitions for the result set. This is typically used for visual or report-based grouping.

The list is not grouped.

setAsRead: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed.

No setAsread field-value pair is configured.

Permission Filter Optional filter that applies permission constraints dynamically based on session or object roles. So that the list items are filtered by the user’s OBAC or ABAC permissions.

Permission filter is not active at the moment. Follow Mindbricks updates to be able to use it.

Pagination Options

Contains settings to configure pagination behavior for list APIs. Includes options like page size, offset, cursor support, and total count inclusion.

Business Logic Workflow

[1] Step : startBusinessApi

Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Reads request and Redis parameters, applies defaults, and writes them to context for downstream processing.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Transforms and normalizes parameters, derives dependent values, and reshapes inputs for the main list query.


[4] Step : checkParameters

Executes validation logic on required and custom parameters, enforcing business rules and cross-field consistency.


[5] Step : checkBasicAuth

Performs role-based access checks and applies dynamic membership or session-based restrictions.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildWhereClause

Constructs the main query WHERE clause and applies optional filters or scoped access controls.

You can use the following settings to change some behavior of this step. whereClause

[7] Step : mainListOperation

Executes the paginated database query, retrieves the list, and stores results in context for enrichment.

You can use the following settings to change some behavior of this step. selectClause, listOptions, paginationOptions

[8] Step : buildOutput

Assembles the list response, sanitizes sensitive fields, applies transformations, and injects extra context if needed.


[9] Step : sendResponse

Sends the paginated list to the client through the controller.


[10] Step : raiseApiEvent

Triggers optional post-workflow events, such as Kafka messages, logs, or system notifications.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The listReportLogs api has 4 filter parameters available for filtering list results. See the Filter Parameters section above for detailed usage examples.

Filter Parameter Type Array Property Description
contentType Enum No Type of content being reported: project/message/user
contentId ID No ID of the reported content (project ID, message ID, user ID)
reportType String No Nature of report (abuse, spam, copyright, etc.)
reviewStatus Enum No Open/closed/ignored

REST Request

To access the api you can use the REST controller with the path GET /v1/reportlogs

  axios({
    method: 'GET',
    url: '/v1/reportlogs',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section for usage examples)
        // contentType: '<value>' // Filter by contentType
        // contentId: '<value>' // Filter by contentId
        // reportType: '<value>' // Filter by reportType
        // reviewStatus: '<value>' // Filter by reviewStatus
            }
  });

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the reportLogs object in the respones. However, some properties may be omitted based on the object’s internal logic.

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "reportLogs",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"reportLogs": [
		{
			"id": "ID",
			"contentType": "Enum",
			"contentType_idx": "Integer",
			"contentId": "ID",
			"reportType": "String",
			"reportedByUserId": "ID",
			"reportedAt": "Date",
			"reviewStatus": "Enum",
			"reviewStatus_idx": "Integer",
			"reviewAction": "String",
			"actionedByUserId": "ID",
			"actionedAt": "Date",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID",
			"reportedBy": [
				{
					"email": "String",
					"fullname": "String",
					"roleId": "String"
				},
				{},
				{}
			],
			"actionedBy": [
				{
					"email": "String",
					"fullname": "String"
				},
				{},
				{}
			]
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Business API Design Specification - Create Suspensionrecord

Business API Design Specification - Create Suspensionrecord

A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic.

While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized.

This document provides an in-depth explanation of the architectural design of the createSuspensionRecord Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side.

Main Data Object and CRUD Operation

The createSuspensionRecord Business API is designed to handle a create operation on the SuspensionRecord data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

Admin: suspend a user from the platform. Action triggers update to auth:user isActive = false.

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The createSuspensionRecord Business API includes a REST controller that can be triggered via the following route:

/v1/suspensionrecords

By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the Parameters section.

MCP Tool

REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This createSuspensionRecord Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The createSuspensionRecord Business API has 5 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client.

Business API parameters can be:

Regular Parameters

Name Type Required Default Location Data Path
suspensionRecordId ID No - body suspensionRecordId
Description: This id paremeter is used to create the data object with a given specific id. Leave null for automatic id.
userId ID Yes - body userId
Description: Suspended user id
reason String Yes - body reason
Description: Reason for suspension action
suspendedByUserId ID Yes - body suspendedByUserId
Description: Admin ID who performed the suspension action
suspendedAt Date Yes - body suspendedAt
Description: Time of action (suspend/lift)

Parameter Transformations

Some parameters are post-processed using transform scripts after being read from the request but before validation or workflow execution. Only parameters with a transform script are listed below.

No parameters are transformed in this API.

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the createSuspensionRecord Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Data Clause

Defines custom field-value assignments used to modify or augment the default payload for create and update operations. These settings override values derived from the session or parameters if explicitly provided.", Note that a default data clause is always prepared by Mindbricks using data property settings, however any property in the data clause can be override by Data Clause Settings.

Custom Data Clause Override

{
    status: runMScript(() => ("active"), {"path":"services[3].businessLogic[8].dataClause.customData[0].value"}),
    suspendedAt: runMScript(() => (new Date()), {"path":"services[3].businessLogic[8].dataClause.customData[1].value"}),
   
}

Actual Data Clause

The business api will use the following data clause. Note that any calculated value will be added to the data clause in the api manager.

{
  id: this.suspensionRecordId,
  userId: this.userId,
  reason: this.reason,
  suspendedByUserId: this.suspendedByUserId,
  suspendedAt: runMScript(() => (new Date()), {"path":"services[3].businessLogic[8].dataClause.customData[1].value"}),
  status: runMScript(() => ("active"), {"path":"services[3].businessLogic[8].dataClause.customData[0].value"}),
  isActive: true,
  _archivedAt: null,
}

Business Logic Workflow

[1] Step : startBusinessApi

Manager initializes context, populates session and request objects, prepares internal structures for parameter handling and workflow execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Manager reads input parameters, normalizes missing values, applies default type casting, and stores them in the API context.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Manager transforms parameters, computes derived values, flattens or remaps arrays/objects, and adjusts formats for downstream processing.


[4] Step : checkParameters

Manager executes built-in validations: required field checks, type enforcement, and basic business rules. Prevents operation if validation fails.


[5] Step : checkBasicAuth

Manager performs authentication and authorization checks: verifies session, user roles, permissions, and tenant restrictions.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildDataClause

Manager constructs the final data object for creation, fills auto-generated fields (IDs, timestamps, owner fields), and ensures schema consistency.

You can use the following settings to change some behavior of this step. dataClause

[7] Step : mainCreateOperation

Manager executes the database insert operation, updates indexes/caches, and triggers internal post-processing like linked default records.


[8] Action : setUserInactiveInAuth

Action Type: InterserviceCallAction

Suspend user’s account in auth service (set isActive false)

class Api {
  async setUserInactiveInAuth() {
    const { InterService } = require("serviceCommon");

    const bodyParams = {};

    bodyParams["id"] = runMScript(() => this.userId, {
      path: "services[3].businessLogic[8].actions.interserviceCallActions[0].apiParameters[0].value",
    });

    bodyParams["dataClause"] = runMScript(() => ({ isActive: false }), {
      path: "services[3].businessLogic[8].actions.interserviceCallActions[0].apiParameters[1].value",
    });

    const resp = await InterService.callAuthM2mUpdateUserById({
      body: bodyParams,
    });

    return resp?.content ?? resp;
  }
}

[9] Action : logUserSuspension

Action Type: PublishEventAction

Log suspension in auditLog

class Api {
  async logUserSuspension() {
    const message = {
      actionType: "userSuspended",
      actorUserId: this.session.userId,
      targetType: "suspensionRecord",
      targetId: this.suspensionRecord.id,
      details: JSON.stringify({ userId: this.userId, reason: this.reason }),
      actionAt: new Date(),
    };

    // Publish event to the configured topic
    const _publisher = new ServicePublisher(
      "audit.suspension.create",
      message,
      this.session,
      this.requestId,
    );
    await _publisher.publish();
    return true;
  }
}

[10] Step : buildOutput

Manager shapes the response: masks sensitive fields, resolves linked references, and formats output according to API contract.


[11] Step : sendResponse

Manager sends the response to the client and finalizes internal tasks like flushing logs or updating session state.


[12] Step : raiseApiEvent

Manager triggers API-level events (Kafka, WebSocket, async workflows) as the final internal step.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The createSuspensionRecord api has got 4 regular client parameters

Parameter Type Required Population
userId ID true request.body?.[“userId”]
reason String true request.body?.[“reason”]
suspendedByUserId ID true request.body?.[“suspendedByUserId”]
suspendedAt Date true request.body?.[“suspendedAt”]

REST Request

To access the api you can use the REST controller with the path POST /v1/suspensionrecords

  axios({
    method: 'POST',
    url: '/v1/suspensionrecords',
    data: {
            userId:"ID",  
            reason:"String",  
            suspendedByUserId:"ID",  
            suspendedAt:"Date",  
    
    },
    params: {
    
        }
  });

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the suspensionRecord object in the respones. However, some properties may be omitted based on the object’s internal logic.

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "suspensionRecord",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"suspensionRecord": {
		"id": "ID",
		"userId": "ID",
		"reason": "String",
		"suspendedByUserId": "ID",
		"suspendedAt": "Date",
		"status": "Enum",
		"status_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Business API Design Specification - Lift Suspensionrecord

Business API Design Specification - Lift Suspensionrecord

A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic.

While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized.

This document provides an in-depth explanation of the architectural design of the liftSuspensionRecord Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side.

Main Data Object and CRUD Operation

The liftSuspensionRecord Business API is designed to handle a update operation on the SuspensionRecord data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

Admin: lift user suspension, set status to lifted & update user isActive=true in auth service.

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The liftSuspensionRecord Business API includes a REST controller that can be triggered via the following route:

/v1/liftsuspensionrecord/:suspensionRecordId

By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the Parameters section.

MCP Tool

REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This liftSuspensionRecord Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The liftSuspensionRecord Business API has 1 parameter that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client.

Business API parameters can be:

Regular Parameters

Name Type Required Default Location Data Path
suspensionRecordId ID Yes - urlpath suspensionRecordId
Description: This id paremeter is used to select the required data object that will be updated

Parameter Transformations

Some parameters are post-processed using transform scripts after being read from the request but before validation or workflow execution. Only parameters with a transform script are listed below.

No parameters are transformed in this API.

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the liftSuspensionRecord Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({$and:[{id:this.suspensionRecordId},{isActive:true}]}), {"path":"services[3].businessLogic[9].whereClause.fullWhereClause"})

Data Clause

Defines custom field-value assignments used to modify or augment the default payload for create and update operations. These settings override values derived from the session or parameters if explicitly provided.", Note that a default data clause is always prepared by Mindbricks using data property settings, however any property in the data clause can be override by Data Clause Settings.

An update data clause populates all update-allowed properties of a data object, however the null properties (that are not provided by client) are ignored in db layer.

Custom Data Clause Override

{
    status: runMScript(() => ("lifted"), {"path":"services[3].businessLogic[9].dataClause.customData[0].value"}),
    suspendedAt: runMScript(() => (new Date()), {"path":"services[3].businessLogic[9].dataClause.customData[1].value"}),
   
}

Actual Data Clause

The business api will use the following data clause. Note that any calculated value will be added to the data clause in the api manager.

{
  status: runMScript(() => ("lifted"), {"path":"services[3].businessLogic[9].dataClause.customData[0].value"}),
  suspendedAt: runMScript(() => (new Date()), {"path":"services[3].businessLogic[9].dataClause.customData[1].value"}),
}

Business Logic Workflow

[1] Step : startBusinessApi

Manager initializes context, prepares request and session objects, and sets up internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Manager reads parameters from the request or Redis, applies defaults, and writes them into context for downstream milestones.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Manager executes parameter transform scripts and derives any helper values or reshaped payloads into the context.


[4] Step : checkParameters

Manager validates required parameters, checks ID formats (UUID/ObjectId), and ensures all preconditions for update are met.


[5] Step : checkBasicAuth

Manager performs login verification, role, and permission checks, enforcing tenant and access rules before update.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildWhereClause

Manager constructs the WHERE clause used to identify the record to update, applying ownership and parent checks if necessary.

You can use the following settings to change some behavior of this step. whereClause

[7] Step : fetchInstance

Manager fetches the existing record from the database and writes it to the context for validation or enrichment.


[8] Step : checkInstance

Manager performs instance-level validations, including ownership, existence, lock status, or other pre-update checks.


[9] Step : buildDataClause

Manager prepares the data clause for the update, applying transformations or enhancements before persisting.

You can use the following settings to change some behavior of this step. dataClause

[10] Step : mainUpdateOperation

Manager executes the update operation with the WHERE and data clauses. Database-level events are raised if configured.


[11] Action : setUserActiveInAuth

Action Type: InterserviceCallAction

Reinstate user’s account in auth service (set isActive true)

class Api {
  async setUserActiveInAuth() {
    const { InterService } = require("serviceCommon");

    const bodyParams = {};

    bodyParams["id"] = runMScript(() => this.userId, {
      path: "services[3].businessLogic[9].actions.interserviceCallActions[0].apiParameters[0].value",
    });

    bodyParams["dataClause"] = runMScript(() => ({ isActive: true }), {
      path: "services[3].businessLogic[9].actions.interserviceCallActions[0].apiParameters[1].value",
    });

    const resp = await InterService.callAuthM2mUpdateUserById({
      body: bodyParams,
    });

    return resp?.content ?? resp;
  }
}

[12] Action : logUserReinstated

Action Type: PublishEventAction

Log reinstatement in auditLog

class Api {
  async logUserReinstated() {
    const message = {
      actionType: "userReinstated",
      actorUserId: this.session.userId,
      targetType: "suspensionRecord",
      targetId: this.suspensionRecord.id,
      details: JSON.stringify({ userId: this.userId, reason: this.reason }),
      actionAt: new Date(),
    };

    // Publish event to the configured topic
    const _publisher = new ServicePublisher(
      "audit.suspension.lifted",
      message,
      this.session,
      this.requestId,
    );
    await _publisher.publish();
    return true;
  }
}

[13] Step : buildOutput

Manager assembles the response object from the update result, masking fields or injecting additional metadata.


[14] Step : sendResponse

Manager sends the response back to the controller for delivery to the client.


[15] Step : raiseApiEvent

Manager triggers API-level events, sending relevant messages to Kafka or other integrations if configured.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The liftSuspensionRecord api has got 1 regular client parameter

Parameter Type Required Population
suspensionRecordId ID true request.params?.[“suspensionRecordId”]

REST Request

To access the api you can use the REST controller with the path PATCH /v1/liftsuspensionrecord/:suspensionRecordId

  axios({
    method: 'PATCH',
    url: `/v1/liftsuspensionrecord/${suspensionRecordId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the suspensionRecord object in the respones. However, some properties may be omitted based on the object’s internal logic.

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "suspensionRecord",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"suspensionRecord": {
		"id": "ID",
		"userId": "ID",
		"reason": "String",
		"suspendedByUserId": "ID",
		"suspendedAt": "Date",
		"status": "Enum",
		"status_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Business API Design Specification - Get Suspensionrecord

Business API Design Specification - Get Suspensionrecord

A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic.

While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized.

This document provides an in-depth explanation of the architectural design of the getSuspensionRecord Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side.

Main Data Object and CRUD Operation

The getSuspensionRecord Business API is designed to handle a get operation on the SuspensionRecord data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

Get a suspension record. Only admin/superAdmin or suspended user.

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The getSuspensionRecord Business API includes a REST controller that can be triggered via the following route:

/v1/suspensionrecords/:suspensionRecordId

By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the Parameters section.

MCP Tool

REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This getSuspensionRecord Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The getSuspensionRecord Business API has 1 parameter that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client.

Business API parameters can be:

Regular Parameters

Name Type Required Default Location Data Path
suspensionRecordId ID Yes - urlpath suspensionRecordId
Description: This id paremeter is used to query the required data object.

Parameter Transformations

Some parameters are post-processed using transform scripts after being read from the request but before validation or workflow execution. Only parameters with a transform script are listed below.

No parameters are transformed in this API.

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the getSuspensionRecord Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Select Clause

Specifies which fields will be selected from the main data object during a get or list operation. Leave blank to select all properties. This applies only to get and list type APIs.",

``

Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({$and:[{id:this.suspensionRecordId},{isActive:true}]}), {"path":"services[3].businessLogic[10].whereClause.fullWhereClause"})

Get Options

Use these options to set get specific settings.

setAsRead: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed.

No setAsread field-value pair is configured.

Business Logic Workflow

[1] Step : startBusinessApi

Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Extracts parameters from request and Redis, applies defaults, and writes them to context.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Executes parameter transformation scripts, applies type coercion, merges derived values, and reshapes inputs for downstream milestones.


[4] Step : checkParameters

Validates required and custom parameters, enforcing business-specific rules and constraints.


[5] Step : checkBasicAuth

Performs login, role, and permission checks, and applies dynamic object-level access rules.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildWhereClause

Builds the WHERE clause for fetching the object and applies additional scoped filters if configured.

You can use the following settings to change some behavior of this step. whereClause

[7] Step : mainGetOperation

Executes the database fetch, retrieves the object, and stores it in context for enrichment or further checks.

You can use the following settings to change some behavior of this step. selectClause, getOptions

[8] Step : checkInstance

Performs instance-level validations, such as ownership, existence, or access conditions.


[9] Step : buildOutput

Assembles the response from the object, applies masking, formatting, and injects additional metadata if needed.


[10] Step : sendResponse

Delivers the response to the controller for client delivery.


[11] Step : raiseApiEvent

Triggers optional API-level events after workflow completion, sending messages to integrations like Kafka if configured.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The getSuspensionRecord api has got 1 regular client parameter

Parameter Type Required Population
suspensionRecordId ID true request.params?.[“suspensionRecordId”]

REST Request

To access the api you can use the REST controller with the path GET /v1/suspensionrecords/:suspensionRecordId

  axios({
    method: 'GET',
    url: `/v1/suspensionrecords/${suspensionRecordId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the suspensionRecord object in the respones. However, some properties may be omitted based on the object’s internal logic.

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "suspensionRecord",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"suspensionRecord": {
		"id": "ID",
		"userId": "ID",
		"reason": "String",
		"suspendedByUserId": "ID",
		"suspendedAt": "Date",
		"status": "Enum",
		"status_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"user": {
			"email": "String",
			"fullname": "String",
			"roleId": "String"
		},
		"suspendedByUser": {
			"email": "String",
			"fullname": "String"
		}
	}
}

Business API Design Specification - List Suspensionrecords

Business API Design Specification - List Suspensionrecords

A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic.

While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized.

This document provides an in-depth explanation of the architectural design of the listSuspensionRecords Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side.

Main Data Object and CRUD Operation

The listSuspensionRecords Business API is designed to handle a list operation on the SuspensionRecord data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

List suspension records. Admins see all; users see only their own.

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The listSuspensionRecords Business API includes a REST controller that can be triggered via the following route:

/v1/suspensionrecords

By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the Parameters section.

MCP Tool

REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This listSuspensionRecords Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The listSuspensionRecords Business API does not require any parameters to be provided from the controllers.

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the listSuspensionRecords Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Select Clause

Specifies which fields will be selected from the main data object during a get or list operation. Leave blank to select all properties. This applies only to get and list type APIs.",

``

Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.


// Addtional Clause Name : scopeToUser

// condition doWhen 
// this.session.roleId !== &#39;admin&#39; &amp;&amp; this.session.roleId !== &#39;superAdmin&#39;

// condition excludeWhen
// No excludeWhen condtion defined

// clause object
{userId: this.session.userId}

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({isActive:true}), {"path":"services[3].businessLogic[11].whereClause.fullWhereClause"})

List Options

Defines list-specific options including filtering logic, default sorting, and result customization for APIs that return multiple records.

List Sort By Sort order definitions for the result set. Multiple fields can be provided with direction (asc/desc).

Specific sort order is not configure, natural order (ascending id) will be used.

List Group By Grouping definitions for the result set. This is typically used for visual or report-based grouping.

The list is not grouped.

setAsRead: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed.

No setAsread field-value pair is configured.

Permission Filter Optional filter that applies permission constraints dynamically based on session or object roles. So that the list items are filtered by the user’s OBAC or ABAC permissions.

Permission filter is not active at the moment. Follow Mindbricks updates to be able to use it.

Pagination Options

Contains settings to configure pagination behavior for list APIs. Includes options like page size, offset, cursor support, and total count inclusion.

Business Logic Workflow

[1] Step : startBusinessApi

Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Reads request and Redis parameters, applies defaults, and writes them to context for downstream processing.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Transforms and normalizes parameters, derives dependent values, and reshapes inputs for the main list query.


[4] Step : checkParameters

Executes validation logic on required and custom parameters, enforcing business rules and cross-field consistency.


[5] Step : checkBasicAuth

Performs role-based access checks and applies dynamic membership or session-based restrictions.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildWhereClause

Constructs the main query WHERE clause and applies optional filters or scoped access controls.

You can use the following settings to change some behavior of this step. whereClause

[7] Step : mainListOperation

Executes the paginated database query, retrieves the list, and stores results in context for enrichment.

You can use the following settings to change some behavior of this step. selectClause, listOptions, paginationOptions

[8] Step : buildOutput

Assembles the list response, sanitizes sensitive fields, applies transformations, and injects extra context if needed.


[9] Step : sendResponse

Sends the paginated list to the client through the controller.


[10] Step : raiseApiEvent

Triggers optional post-workflow events, such as Kafka messages, logs, or system notifications.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The listSuspensionRecords api has got no visible parameters.

REST Request

To access the api you can use the REST controller with the path GET /v1/suspensionrecords

  axios({
    method: 'GET',
    url: '/v1/suspensionrecords',
    data: {
    
    },
    params: {
    
        }
  });

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the suspensionRecords object in the respones. However, some properties may be omitted based on the object’s internal logic.

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "suspensionRecords",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"suspensionRecords": [
		{
			"id": "ID",
			"userId": "ID",
			"reason": "String",
			"suspendedByUserId": "ID",
			"suspendedAt": "Date",
			"status": "Enum",
			"status_idx": "Integer",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID",
			"user": [
				{
					"email": "String",
					"fullname": "String",
					"roleId": "String"
				},
				{},
				{}
			],
			"suspendedByUser": [
				{
					"email": "String",
					"fullname": "String"
				},
				{},
				{}
			]
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Business API Design Specification - Create Auditlog

Business API Design Specification - Create Auditlog

A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic.

While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized.

This document provides an in-depth explanation of the architectural design of the createAuditLog Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side.

Main Data Object and CRUD Operation

The createAuditLog Business API is designed to handle a create operation on the AuditLog data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

Create audit log entry. Only used by system or admin workflows.

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The createAuditLog Business API includes a REST controller that can be triggered via the following route:

/v1/auditlogs

By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the Parameters section.

MCP Tool

REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This createAuditLog Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The createAuditLog Business API has 7 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client.

Business API parameters can be:

Regular Parameters

Name Type Required Default Location Data Path
auditLogId ID No - body auditLogId
Description: This id paremeter is used to create the data object with a given specific id. Leave null for automatic id.
actionType String Yes - body actionType
Description: Type of admin action (created, updated, suspended, approved, etc.)
actorUserId ID Yes - body actorUserId
Description: User ID of admin/staff performing the action
targetType String Yes - body targetType
Description: Type of object affected by this action (approvalRequest, reportLog, suspensionRecord, etc.)
targetId ID Yes - body targetId
Description: ID of the object affected by this action
details Text No - body details
Description: Freeform details, note, or JSON blob describing action context
actionAt Date Yes - body actionAt
Description: When the action occurred

Parameter Transformations

Some parameters are post-processed using transform scripts after being read from the request but before validation or workflow execution. Only parameters with a transform script are listed below.

No parameters are transformed in this API.

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the createAuditLog Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Data Clause

Defines custom field-value assignments used to modify or augment the default payload for create and update operations. These settings override values derived from the session or parameters if explicitly provided.", Note that a default data clause is always prepared by Mindbricks using data property settings, however any property in the data clause can be override by Data Clause Settings.

Custom Data Clause Override

{
    actionAt: runMScript(() => (new Date()), {"path":"services[3].businessLogic[12].dataClause.customData[0].value"}),
   
}

Actual Data Clause

The business api will use the following data clause. Note that any calculated value will be added to the data clause in the api manager.

{
  id: this.auditLogId,
  actionType: this.actionType,
  actorUserId: this.actorUserId,
  targetType: this.targetType,
  targetId: this.targetId,
  details: this.details,
  actionAt: runMScript(() => (new Date()), {"path":"services[3].businessLogic[12].dataClause.customData[0].value"}),
}

Business Logic Workflow

[1] Step : startBusinessApi

Manager initializes context, populates session and request objects, prepares internal structures for parameter handling and workflow execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Manager reads input parameters, normalizes missing values, applies default type casting, and stores them in the API context.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Manager transforms parameters, computes derived values, flattens or remaps arrays/objects, and adjusts formats for downstream processing.


[4] Step : checkParameters

Manager executes built-in validations: required field checks, type enforcement, and basic business rules. Prevents operation if validation fails.


[5] Step : checkBasicAuth

Manager performs authentication and authorization checks: verifies session, user roles, permissions, and tenant restrictions.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildDataClause

Manager constructs the final data object for creation, fills auto-generated fields (IDs, timestamps, owner fields), and ensures schema consistency.

You can use the following settings to change some behavior of this step. dataClause

[7] Step : mainCreateOperation

Manager executes the database insert operation, updates indexes/caches, and triggers internal post-processing like linked default records.


[8] Step : buildOutput

Manager shapes the response: masks sensitive fields, resolves linked references, and formats output according to API contract.


[9] Step : sendResponse

Manager sends the response to the client and finalizes internal tasks like flushing logs or updating session state.


[10] Step : raiseApiEvent

Manager triggers API-level events (Kafka, WebSocket, async workflows) as the final internal step.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The createAuditLog api has got 6 regular client parameters

Parameter Type Required Population
actionType String true request.body?.[“actionType”]
actorUserId ID true request.body?.[“actorUserId”]
targetType String true request.body?.[“targetType”]
targetId ID true request.body?.[“targetId”]
details Text false request.body?.[“details”]
actionAt Date true request.body?.[“actionAt”]

REST Request

To access the api you can use the REST controller with the path POST /v1/auditlogs

  axios({
    method: 'POST',
    url: '/v1/auditlogs',
    data: {
            actionType:"String",  
            actorUserId:"ID",  
            targetType:"String",  
            targetId:"ID",  
            details:"Text",  
            actionAt:"Date",  
    
    },
    params: {
    
        }
  });

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the auditLog object in the respones. However, some properties may be omitted based on the object’s internal logic.

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "auditLog",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"auditLog": {
		"id": "ID",
		"actionType": "String",
		"actorUserId": "ID",
		"targetType": "String",
		"targetId": "ID",
		"details": "Text",
		"actionAt": "Date",
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"isActive": true
	}
}

Business API Design Specification - Get Auditlog

Business API Design Specification - Get Auditlog

A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic.

While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized.

This document provides an in-depth explanation of the architectural design of the getAuditLog Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side.

Main Data Object and CRUD Operation

The getAuditLog Business API is designed to handle a get operation on the AuditLog data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

Get a single audit log record. Only superAdmin/admin.

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The getAuditLog Business API includes a REST controller that can be triggered via the following route:

/v1/auditlogs/:auditLogId

By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the Parameters section.

MCP Tool

REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This getAuditLog Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The getAuditLog Business API has 1 parameter that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client.

Business API parameters can be:

Regular Parameters

Name Type Required Default Location Data Path
auditLogId ID Yes - urlpath auditLogId
Description: This id paremeter is used to query the required data object.

Parameter Transformations

Some parameters are post-processed using transform scripts after being read from the request but before validation or workflow execution. Only parameters with a transform script are listed below.

No parameters are transformed in this API.

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the getAuditLog Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Select Clause

Specifies which fields will be selected from the main data object during a get or list operation. Leave blank to select all properties. This applies only to get and list type APIs.",

``

Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({id:this.auditLogId}), {"path":"services[3].businessLogic[13].whereClause.fullWhereClause"})

Get Options

Use these options to set get specific settings.

setAsRead: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed.

No setAsread field-value pair is configured.

Business Logic Workflow

[1] Step : startBusinessApi

Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Extracts parameters from request and Redis, applies defaults, and writes them to context.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Executes parameter transformation scripts, applies type coercion, merges derived values, and reshapes inputs for downstream milestones.


[4] Step : checkParameters

Validates required and custom parameters, enforcing business-specific rules and constraints.


[5] Step : checkBasicAuth

Performs login, role, and permission checks, and applies dynamic object-level access rules.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildWhereClause

Builds the WHERE clause for fetching the object and applies additional scoped filters if configured.

You can use the following settings to change some behavior of this step. whereClause

[7] Step : mainGetOperation

Executes the database fetch, retrieves the object, and stores it in context for enrichment or further checks.

You can use the following settings to change some behavior of this step. selectClause, getOptions

[8] Step : checkInstance

Performs instance-level validations, such as ownership, existence, or access conditions.


[9] Step : buildOutput

Assembles the response from the object, applies masking, formatting, and injects additional metadata if needed.


[10] Step : sendResponse

Delivers the response to the controller for client delivery.


[11] Step : raiseApiEvent

Triggers optional API-level events after workflow completion, sending messages to integrations like Kafka if configured.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The getAuditLog api has got 1 regular client parameter

Parameter Type Required Population
auditLogId ID true request.params?.[“auditLogId”]

REST Request

To access the api you can use the REST controller with the path GET /v1/auditlogs/:auditLogId

  axios({
    method: 'GET',
    url: `/v1/auditlogs/${auditLogId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the auditLog object in the respones. However, some properties may be omitted based on the object’s internal logic.

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "auditLog",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"auditLog": {
		"id": "ID",
		"actionType": "String",
		"actorUserId": "ID",
		"targetType": "String",
		"targetId": "ID",
		"details": "Text",
		"actionAt": "Date",
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"isActive": true
	}
}

Business API Design Specification - List Auditlogs

Business API Design Specification - List Auditlogs

A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic.

While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized.

This document provides an in-depth explanation of the architectural design of the listAuditLogs Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side.

Main Data Object and CRUD Operation

The listAuditLogs Business API is designed to handle a list operation on the AuditLog data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

List audit log records. Only superAdmin/admin.

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The listAuditLogs Business API includes a REST controller that can be triggered via the following route:

/v1/auditlogs

By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the Parameters section.

MCP Tool

REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This listAuditLogs Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The listAuditLogs Business API does not require any parameters to be provided from the controllers.

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the listAuditLogs Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Select Clause

Specifies which fields will be selected from the main data object during a get or list operation. Leave blank to select all properties. This applies only to get and list type APIs.",

``

Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

null

List Options

Defines list-specific options including filtering logic, default sorting, and result customization for APIs that return multiple records.

List Sort By Sort order definitions for the result set. Multiple fields can be provided with direction (asc/desc).

Specific sort order is not configure, natural order (ascending id) will be used.

List Group By Grouping definitions for the result set. This is typically used for visual or report-based grouping.

The list is not grouped.

setAsRead: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed.

No setAsread field-value pair is configured.

Permission Filter Optional filter that applies permission constraints dynamically based on session or object roles. So that the list items are filtered by the user’s OBAC or ABAC permissions.

Permission filter is not active at the moment. Follow Mindbricks updates to be able to use it.

Pagination Options

Contains settings to configure pagination behavior for list APIs. Includes options like page size, offset, cursor support, and total count inclusion.

Business Logic Workflow

[1] Step : startBusinessApi

Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Reads request and Redis parameters, applies defaults, and writes them to context for downstream processing.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Transforms and normalizes parameters, derives dependent values, and reshapes inputs for the main list query.


[4] Step : checkParameters

Executes validation logic on required and custom parameters, enforcing business rules and cross-field consistency.


[5] Step : checkBasicAuth

Performs role-based access checks and applies dynamic membership or session-based restrictions.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildWhereClause

Constructs the main query WHERE clause and applies optional filters or scoped access controls.

You can use the following settings to change some behavior of this step. whereClause

[7] Step : mainListOperation

Executes the paginated database query, retrieves the list, and stores results in context for enrichment.

You can use the following settings to change some behavior of this step. selectClause, listOptions, paginationOptions

[8] Step : buildOutput

Assembles the list response, sanitizes sensitive fields, applies transformations, and injects extra context if needed.


[9] Step : sendResponse

Sends the paginated list to the client through the controller.


[10] Step : raiseApiEvent

Triggers optional post-workflow events, such as Kafka messages, logs, or system notifications.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The listAuditLogs api has got no visible parameters.

REST Request

To access the api you can use the REST controller with the path GET /v1/auditlogs

  axios({
    method: 'GET',
    url: '/v1/auditlogs',
    data: {
    
    },
    params: {
    
        }
  });

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the auditLogs object in the respones. However, some properties may be omitted based on the object’s internal logic.

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "auditLogs",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"auditLogs": [
		{
			"id": "ID",
			"actionType": "String",
			"actorUserId": "ID",
			"targetType": "String",
			"targetId": "ID",
			"details": "Text",
			"actionAt": "Date",
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID",
			"isActive": true
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

AgentHub Service

Service Design Specification

Service Design Specification

auteurlabb-agenthub-service documentation Version: 1.0.0

Scope

This document provides a structured architectural overview of the agentHub microservice, detailing its configuration, data model, authorization logic, business rules, and API design. It has been automatically generated based on the service definition within Mindbricks, ensuring that the information reflects the source of truth used during code generation and deployment.

The document is intended to serve multiple audiences:

Note for Frontend Developers: While this document is valuable for understanding business logic and data interactions, please refer to the Service API Documentation for endpoint-level specifications and integration details.

Note for Backend Developers: Since the code for this service is automatically generated by Mindbricks, you typically won’t need to implement or modify it manually. However, this document is especially valuable when you’re building other services—whether within Mindbricks or externally—that need to interact with or depend on this service. It provides a clear reference to the service’s data contracts, business rules, and API structure, helping ensure compatibility and correct integration.

AgentHub Service Settings

AI Agent Hub

Service Overview

This service is configured to listen for HTTP requests on port 3006, serving both the main API interface and default administrative endpoints.

The following routes are available by default:

The service uses a PostgreSQL database for data storage, with the database name set to auteurlabb-agenthub-service.

This service is accessible via the following environment-specific URLs:

Authentication & Security

This service requires user authentication for access. It supports both JWT and RSA-based authentication mechanisms, ensuring secure user sessions and data integrity. If a crud route also is configured to require login, it will check a valid JWT token in the request query/header/bearer/cookie. If the token is valid, it will extract the user information from the token and make the fetched session data available in the request context.

Service Data Objects

The service uses a PostgreSQL database for data storage, with the database name set to auteurlabb-agenthub-service.

Data deletion is managed using a soft delete strategy. Instead of removing records from the database, they are flagged as inactive by setting the isActive field to false.

Object Name Description Public Access
sys_agentOverride Runtime overrides for design-time agents. Null fields use the design default. accessProtected
sys_agentExecution Agent execution log. Records each agent invocation with input, output, and performance metrics. accessProtected
sys_toolCatalog Cached tool catalog discovered from project services. Refreshed periodically. accessProtected

sys_agentOverride Data Object

Object Overview

Description: Runtime overrides for design-time agents. Null fields use the design default.

This object represents a core data structure within the service and acts as the blueprint for database interaction, API generation, and business logic enforcement. It is defined using the ObjectSettings pattern, which governs its behavior, access control, caching strategy, and integration points with other systems such as Stripe and Redis.

Core Configuration

Properties Schema

Property Type Required Description
agentName String Yes Design-time agent name this override applies to.
provider String No Override AI provider (e.g., openai, anthropic).
model String No Override model name.
systemPrompt Text No Override system prompt.
temperature Double No Override temperature (0-2).
maxTokens Integer No Override max tokens.
responseFormat String No Override response format (text/json).
selectedTools Object No Array of tool names from the catalog that this agent can use.
guardrails Object No Override guardrails: { maxToolCalls, timeout, maxTokenBudget }.
enabled Boolean Yes Enable or disable this agent.
updatedBy ID No User who last updated this override.

Default Values

Default values are automatically assigned to properties when a new object is created, if no value is provided in the request body. Since default values are applied on db level, they should be literal values, not expressions.If you want to use expressions, you can use transposed parameters in any business API to set default values dynamically.

Always Create with Default Values

Some of the default values are set to be always used when creating a new object, even if the property value is provided in the request body. It ensures that the property is always initialized with a default value when the object is created.

Constant Properties

agentName

Constant properties are defined to be immutable after creation, meaning they cannot be updated or changed once set. They are typically used for properties that should remain constant throughout the object’s lifecycle. A property is set to be constant if the Allow Update option is set to false.

Auto Update Properties

agentName provider model systemPrompt temperature maxTokens responseFormat selectedTools guardrails enabled updatedBy

An update crud API created with the option Auto Params enabled will automatically update these properties with the provided values in the request body. If you want to update any property in your own business logic not by user input, you can set the Allow Auto Update option to false. These properties will be added to the update API’s body parameters and can be updated by the user if any value is provided in the request body.

Elastic Search Indexing

agentName enabled

Properties that are indexed in Elastic Search will be searchable via the Elastic Search API. While all properties are stored in the elastic search index of the data object, only those marked for Elastic Search indexing will be available for search queries.

Database Indexing

agentName enabled

Properties that are indexed in the database will be optimized for query performance, allowing for faster data retrieval. Make a property indexed in the database if you want to use it frequently in query filters or sorting.

Unique Properties

agentName

Unique properties are enforced to have distinct values across all instances of the data object, preventing duplicate entries. Note that a unique property is automatically indexed in the database so you will not need to set the Indexed in DB option.

Session Data Properties

updatedBy

Session data properties are used to store data that is specific to the user session, allowing for personalized experiences and temporary data storage. If a property is configured as session data, it will be automatically mapped to the related field in the user session during CRUD operations. Note that session data properties can not be mutated by the user, but only by the system.

sys_agentExecution Data Object

Object Overview

Description: Agent execution log. Records each agent invocation with input, output, and performance metrics.

This object represents a core data structure within the service and acts as the blueprint for database interaction, API generation, and business logic enforcement. It is defined using the ObjectSettings pattern, which governs its behavior, access control, caching strategy, and integration points with other systems such as Stripe and Redis.

Core Configuration

Properties Schema

Property Type Required Description
agentName String Yes Agent that was executed.
agentType Enum Yes Whether this was a design-time or dynamic agent.
source Enum Yes How the agent was triggered.
userId ID No User who triggered the execution.
input Object No Request input (truncated for large payloads).
output Object No Response output (truncated for large payloads).
toolCalls Integer No Number of tool calls made during execution.
tokenUsage Object No Token usage: { prompt, completion, total }.
durationMs Integer No Execution time in milliseconds.
status Enum Yes Execution status.
error Text No Error message if execution failed.

Default Values

Default values are automatically assigned to properties when a new object is created, if no value is provided in the request body. Since default values are applied on db level, they should be literal values, not expressions.If you want to use expressions, you can use transposed parameters in any business API to set default values dynamically.

Constant Properties

agentName agentType source userId input output toolCalls tokenUsage durationMs status error

Constant properties are defined to be immutable after creation, meaning they cannot be updated or changed once set. They are typically used for properties that should remain constant throughout the object’s lifecycle. A property is set to be constant if the Allow Update option is set to false.

Auto Update Properties

agentName agentType source userId input output toolCalls tokenUsage durationMs status error

An update crud API created with the option Auto Params enabled will automatically update these properties with the provided values in the request body. If you want to update any property in your own business logic not by user input, you can set the Allow Auto Update option to false. These properties will be added to the update API’s body parameters and can be updated by the user if any value is provided in the request body.

Enum Properties

Enum properties are defined with a set of allowed values, ensuring that only valid options can be assigned to them. The enum options value will be stored as strings in the database, but when a data object is created an addtional property with the same name plus an idx suffix will be created, which will hold the index of the selected enum option. You can use the index property to sort by the enum value or when your enum options represent a sequence of values.

Elastic Search Indexing

agentName agentType source userId toolCalls durationMs status

Properties that are indexed in Elastic Search will be searchable via the Elastic Search API. While all properties are stored in the elastic search index of the data object, only those marked for Elastic Search indexing will be available for search queries.

Database Indexing

agentName agentType source userId status

Properties that are indexed in the database will be optimized for query performance, allowing for faster data retrieval. Make a property indexed in the database if you want to use it frequently in query filters or sorting.

Filter Properties

agentName agentType source userId status

Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API’s that have “Auto Params” enabled.

sys_toolCatalog Data Object

Object Overview

Description: Cached tool catalog discovered from project services. Refreshed periodically.

This object represents a core data structure within the service and acts as the blueprint for database interaction, API generation, and business logic enforcement. It is defined using the ObjectSettings pattern, which governs its behavior, access control, caching strategy, and integration points with other systems such as Stripe and Redis.

Core Configuration

Properties Schema

Property Type Required Description
toolName String Yes Full tool name (e.g., service:apiName).
serviceName String Yes Source service name.
description Text No Tool description.
parameters Object No JSON Schema of tool parameters.
lastRefreshed Date No When this tool was last discovered/refreshed.

Default Values

Default values are automatically assigned to properties when a new object is created, if no value is provided in the request body. Since default values are applied on db level, they should be literal values, not expressions.If you want to use expressions, you can use transposed parameters in any business API to set default values dynamically.

Auto Update Properties

toolName serviceName description parameters lastRefreshed

An update crud API created with the option Auto Params enabled will automatically update these properties with the provided values in the request body. If you want to update any property in your own business logic not by user input, you can set the Allow Auto Update option to false. These properties will be added to the update API’s body parameters and can be updated by the user if any value is provided in the request body.

Elastic Search Indexing

toolName serviceName description

Properties that are indexed in Elastic Search will be searchable via the Elastic Search API. While all properties are stored in the elastic search index of the data object, only those marked for Elastic Search indexing will be available for search queries.

Database Indexing

toolName serviceName

Properties that are indexed in the database will be optimized for query performance, allowing for faster data retrieval. Make a property indexed in the database if you want to use it frequently in query filters or sorting.

Unique Properties

toolName

Unique properties are enforced to have distinct values across all instances of the data object, preventing duplicate entries. Note that a unique property is automatically indexed in the database so you will not need to set the Indexed in DB option.

Filter Properties

serviceName

Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API’s that have “Auto Params” enabled.

Business Logic

agentHub has got 9 Business APIs to manage its internal and crud logic. For the details of each business API refer to its chapter.


This document was generated from the service architecture definition and should be kept in sync with implementation changes.


REST API GUIDE

REST API GUIDE

auteurlabb-agenthub-service

Version: 1.0.0

AI Agent Hub

Architectural Design Credit and Contact Information

The architectural design of this microservice is credited to . For inquiries, feedback, or further information regarding the architecture, please direct your communication to:

Email:

We encourage open communication and welcome any questions or discussions related to the architectural aspects of this microservice.

Documentation Scope

Welcome to the official documentation for the AgentHub Service’s REST API. This document is designed to provide a comprehensive guide to interfacing with our AgentHub Service exclusively through RESTful API endpoints.

Intended Audience

This documentation is intended for developers and integrators who are looking to interact with the AgentHub Service via HTTP requests for purposes such as creating, updating, deleting and querying AgentHub objects.

Overview

Within these pages, you will find detailed information on how to effectively utilize the REST API, including authentication methods, request and response formats, endpoint descriptions, and examples of common use cases.

Beyond REST It’s important to note that the AgentHub Service also supports alternative methods of interaction, such as gRPC and messaging via a Message Broker. These communication methods are beyond the scope of this document. For information regarding these protocols, please refer to their respective documentation.

Authentication And Authorization

To ensure secure access to the AgentHub service’s protected endpoints, a project-wide access token is required. This token serves as the primary method for authenticating requests to our service. However, it’s important to note that access control varies across different routes:

Protected API: Certain API (routes) require specific authorization levels. Access to these routes is contingent upon the possession of a valid access token that meets the route-specific authorization criteria. Unauthorized requests to these routes will be rejected.

**Public API **: The service also includes public API (routes) that are accessible without authentication. These public endpoints are designed for open access and do not require an access token.

Token Locations

When including your access token in a request, ensure it is placed in one of the following specified locations. The service will sequentially search these locations for the token, utilizing the first one it encounters.

Location Token Name / Param Name
Query access_token
Authorization Header Bearer
Header auteurlabb-access-token
Cookie auteurlabb-access-token

Please ensure the token is correctly placed in one of these locations, using the appropriate label as indicated. The service prioritizes these locations in the order listed, processing the first token it successfully identifies.

Api Definitions

This section outlines the API endpoints available within the AgentHub service. Each endpoint can receive parameters through various methods, meticulously described in the following definitions. It’s important to understand the flexibility in how parameters can be included in requests to effectively interact with the AgentHub service.

This service is configured to listen for HTTP requests on port 3006, serving both the main API interface and default administrative endpoints.

The following routes are available by default:

This service is accessible via the following environment-specific URLs:

Parameter Inclusion Methods: Parameters can be incorporated into API requests in several ways, each with its designated location. Understanding these methods is crucial for correctly constructing your requests:

Query Parameters: Included directly in the URL’s query string.

Path Parameters: Embedded within the URL’s path.

Body Parameters: Sent within the JSON body of the request.

Session Parameters: Automatically read from the session object. This method is used for parameters that are intrinsic to the user’s session, such as userId. When using an API that involves session parameters, you can omit these from your request. The service will automatically bind them to the API layer, provided that a session is associated with your request.

Note on Session Parameters: Session parameters represent a unique method of parameter inclusion, relying on the context of the user’s session. A common example of a session parameter is userId, which the service automatically associates with your request when a session exists. This feature ensures seamless integration of user-specific data without manual input for each request.

By adhering to the specified parameter inclusion methods, you can effectively utilize the AgentHub service’s API endpoints. For detailed information on each endpoint, including required parameters and their accepted locations, refer to the individual API definitions below.

Common Parameters

The AgentHub service’s business API support several common parameters designed to modify and enhance the behavior of API requests. These parameters are not individually listed in the API route definitions to avoid repetition. Instead, refer to this section to understand how to leverage these common behaviors across different routes. Note that all common parameters should be included in the query part of the URL.

Supported Common Parameters:

By utilizing these common parameters, you can tailor the behavior of API requests to suit your specific requirements, ensuring optimal performance and usability of the AgentHub service.

Error Response

If a request encounters an issue, whether due to a logical fault or a technical problem, the service responds with a standardized JSON error structure. The HTTP status code within this response indicates the nature of the error, utilizing commonly recognized codes for clarity:

Each error response is structured to provide meaningful insight into the problem, assisting in diagnosing and resolving issues efficiently.

{
  "result": "ERR",
  "status": 400,
  "message": "errMsg_organizationIdisNotAValidID",
  "errCode": 400,
  "date": "2024-03-19T12:13:54.124Z",
  "detail": "String"
}

Object Structure of a Successfull Response

When the AgentHub service processes requests successfully, it wraps the requested resource(s) within a JSON envelope. This envelope not only contains the data but also includes essential metadata, such as configuration details and pagination information, to enrich the response and provide context to the client.

Key Characteristics of the Response Envelope:

Design Considerations: The structure of a API’s response data is meticulously crafted during the service’s architectural planning. This design ensures that responses adequately reflect the intended data relationships and service logic, providing clients with rich and meaningful information.

Brief Data: Certain API’s return a condensed version of the object data, intentionally selecting only specific fields deemed useful for that request. In such instances, the API documentation will detail the properties included in the response, guiding developers on what to expect.

API Response Structure

The API utilizes a standardized JSON envelope to encapsulate responses. This envelope is designed to consistently deliver both the requested data and essential metadata, ensuring that clients can efficiently interpret and utilize the response.

HTTP Status Codes:

Success Response Format:

For successful operations, the response includes a "status": "OK" property, signaling the successful execution of the request. The structure of a successful response is outlined below:

{
  "status":"OK",
  "statusCode": 200,   
  "elapsedMs":126,
  "ssoTime":120,
  "source": "db",
  "cacheKey": "hexCode",
  "userId": "ID",
  "sessionId": "ID",
  "requestId": "ID",
  "dataName":"products",
  "method":"GET",
  "action":"list",
  "appVersion":"Version",
  "rowCount":3
  "products":[{},{},{}],
  "paging": {
    "pageNumber":1, 
    "pageRowCount":25, 
    "totalRowCount":3,
    "pageCount":1
  },
  "filters": [],
  "uiPermissions": []
}

Handling Errors:

For details on handling error scenarios and understanding the structure of error responses, please refer to the “Error Response” section provided earlier in this documentation. It outlines how error conditions are communicated, including the use of HTTP status codes and standardized JSON structures for error messages.

Resources

AgentHub service provides the following resources which are stored in its own database as a data object. Note that a resource for an api access is a data object for the service.

Sys_agentOverride resource

Resource Definition : Runtime overrides for design-time agents. Null fields use the design default. Sys_agentOverride Resource Properties

Name Type Required Default Definition
agentName String Design-time agent name this override applies to.
provider String Override AI provider (e.g., openai, anthropic).
model String Override model name.
systemPrompt Text Override system prompt.
temperature Double Override temperature (0-2).
maxTokens Integer Override max tokens.
responseFormat String Override response format (text/json).
selectedTools Object Array of tool names from the catalog that this agent can use.
guardrails Object Override guardrails: { maxToolCalls, timeout, maxTokenBudget }.
enabled Boolean Enable or disable this agent.
updatedBy ID User who last updated this override.

Sys_agentExecution resource

Resource Definition : Agent execution log. Records each agent invocation with input, output, and performance metrics. Sys_agentExecution Resource Properties

Name Type Required Default Definition
agentName String Agent that was executed.
agentType Enum Whether this was a design-time or dynamic agent.
source Enum How the agent was triggered.
userId ID User who triggered the execution.
input Object Request input (truncated for large payloads).
output Object Response output (truncated for large payloads).
toolCalls Integer Number of tool calls made during execution.
tokenUsage Object Token usage: { prompt, completion, total }.
durationMs Integer Execution time in milliseconds.
status Enum Execution status.
error Text Error message if execution failed.

Enum Properties

Enum properties are represented as strings in the database. The values are mapped to their corresponding names in the application layer.

agentType Enum Property

Property Definition : Whether this was a design-time or dynamic agent.Enum Options

Name Value Index
design "design"" 0
dynamic "dynamic"" 1
source Enum Property

Property Definition : How the agent was triggered.Enum Options

Name Value Index
rest "rest"" 0
sse "sse"" 1
kafka "kafka"" 2
agent "agent"" 3
status Enum Property

Property Definition : Execution status.Enum Options

Name Value Index
success "success"" 0
error "error"" 1
timeout "timeout"" 2

Sys_toolCatalog resource

Resource Definition : Cached tool catalog discovered from project services. Refreshed periodically. Sys_toolCatalog Resource Properties

Name Type Required Default Definition
toolName String Full tool name (e.g., service:apiName).
serviceName String Source service name.
description Text Tool description.
parameters Object JSON Schema of tool parameters.
lastRefreshed Date When this tool was last discovered/refreshed.

Business Api

Get Agentoverride API

[Default get API] — This is the designated default get API for the sys_agentOverride data object. Frontend generators and AI agents should use this API for standard CRUD operations.

Rest Route

The getAgentOverride API REST controller can be triggered via the following route:

/v1/agentoverride/:sys_agentOverrideId

Rest Request Parameters

The getAgentOverride api has got 1 regular request parameter

Parameter Type Required Population
sys_agentOverrideId ID true request.params?.[“sys_agentOverrideId”]
sys_agentOverrideId : This id paremeter is used to query the required data object.

REST Request To access the api you can use the REST controller with the path GET /v1/agentoverride/:sys_agentOverrideId

  axios({
    method: 'GET',
    url: `/v1/agentoverride/${sys_agentOverrideId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_agentOverride",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"sys_agentOverride": {
		"id": "ID",
		"agentName": "String",
		"provider": "String",
		"model": "String",
		"systemPrompt": "Text",
		"temperature": "Double",
		"maxTokens": "Integer",
		"responseFormat": "String",
		"selectedTools": "Object",
		"guardrails": "Object",
		"enabled": "Boolean",
		"updatedBy": "ID",
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"isActive": true
	}
}

List Agentoverrides API

[Default list API] — This is the designated default list API for the sys_agentOverride data object. Frontend generators and AI agents should use this API for standard CRUD operations.

Rest Route

The listAgentOverrides API REST controller can be triggered via the following route:

/v1/agentoverrides

Rest Request Parameters The listAgentOverrides api has got no request parameters.

REST Request To access the api you can use the REST controller with the path GET /v1/agentoverrides

  axios({
    method: 'GET',
    url: '/v1/agentoverrides',
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_agentOverrides",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"sys_agentOverrides": [
		{
			"id": "ID",
			"agentName": "String",
			"provider": "String",
			"model": "String",
			"systemPrompt": "Text",
			"temperature": "Double",
			"maxTokens": "Integer",
			"responseFormat": "String",
			"selectedTools": "Object",
			"guardrails": "Object",
			"enabled": "Boolean",
			"updatedBy": "ID",
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID",
			"isActive": true
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Update Agentoverride API

[Default update API] — This is the designated default update API for the sys_agentOverride data object. Frontend generators and AI agents should use this API for standard CRUD operations.

Rest Route

The updateAgentOverride API REST controller can be triggered via the following route:

/v1/agentoverride/:sys_agentOverrideId

Rest Request Parameters

The updateAgentOverride api has got 10 regular request parameters

Parameter Type Required Population
sys_agentOverrideId ID true request.params?.[“sys_agentOverrideId”]
provider String request.body?.[“provider”]
model String request.body?.[“model”]
systemPrompt Text request.body?.[“systemPrompt”]
temperature Double request.body?.[“temperature”]
maxTokens Integer request.body?.[“maxTokens”]
responseFormat String request.body?.[“responseFormat”]
selectedTools Object request.body?.[“selectedTools”]
guardrails Object request.body?.[“guardrails”]
enabled Boolean request.body?.[“enabled”]
sys_agentOverrideId : This id paremeter is used to select the required data object that will be updated
provider : Override AI provider (e.g., openai, anthropic).
model : Override model name.
systemPrompt : Override system prompt.
temperature : Override temperature (0-2).
maxTokens : Override max tokens.
responseFormat : Override response format (text/json).
selectedTools : Array of tool names from the catalog that this agent can use.
guardrails : Override guardrails: { maxToolCalls, timeout, maxTokenBudget }.
enabled : Enable or disable this agent.

REST Request To access the api you can use the REST controller with the path PATCH /v1/agentoverride/:sys_agentOverrideId

  axios({
    method: 'PATCH',
    url: `/v1/agentoverride/${sys_agentOverrideId}`,
    data: {
            provider:"String",  
            model:"String",  
            systemPrompt:"Text",  
            temperature:"Double",  
            maxTokens:"Integer",  
            responseFormat:"String",  
            selectedTools:"Object",  
            guardrails:"Object",  
            enabled:"Boolean",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_agentOverride",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"sys_agentOverride": {
		"id": "ID",
		"agentName": "String",
		"provider": "String",
		"model": "String",
		"systemPrompt": "Text",
		"temperature": "Double",
		"maxTokens": "Integer",
		"responseFormat": "String",
		"selectedTools": "Object",
		"guardrails": "Object",
		"enabled": "Boolean",
		"updatedBy": "ID",
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"isActive": true
	}
}

Create Agentoverride API

[Default create API] — This is the designated default create API for the sys_agentOverride data object. Frontend generators and AI agents should use this API for standard CRUD operations.

Rest Route

The createAgentOverride API REST controller can be triggered via the following route:

/v1/agentoverride

Rest Request Parameters

The createAgentOverride api has got 9 regular request parameters

Parameter Type Required Population
agentName String true request.body?.[“agentName”]
provider String false request.body?.[“provider”]
model String false request.body?.[“model”]
systemPrompt Text false request.body?.[“systemPrompt”]
temperature Double false request.body?.[“temperature”]
maxTokens Integer false request.body?.[“maxTokens”]
responseFormat String false request.body?.[“responseFormat”]
selectedTools Object false request.body?.[“selectedTools”]
guardrails Object false request.body?.[“guardrails”]
agentName : Design-time agent name this override applies to.
provider : Override AI provider (e.g., openai, anthropic).
model : Override model name.
systemPrompt : Override system prompt.
temperature : Override temperature (0-2).
maxTokens : Override max tokens.
responseFormat : Override response format (text/json).
selectedTools : Array of tool names from the catalog that this agent can use.
guardrails : Override guardrails: { maxToolCalls, timeout, maxTokenBudget }.

REST Request To access the api you can use the REST controller with the path POST /v1/agentoverride

  axios({
    method: 'POST',
    url: '/v1/agentoverride',
    data: {
            agentName:"String",  
            provider:"String",  
            model:"String",  
            systemPrompt:"Text",  
            temperature:"Double",  
            maxTokens:"Integer",  
            responseFormat:"String",  
            selectedTools:"Object",  
            guardrails:"Object",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_agentOverride",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"sys_agentOverride": {
		"id": "ID",
		"agentName": "String",
		"provider": "String",
		"model": "String",
		"systemPrompt": "Text",
		"temperature": "Double",
		"maxTokens": "Integer",
		"responseFormat": "String",
		"selectedTools": "Object",
		"guardrails": "Object",
		"enabled": "Boolean",
		"updatedBy": "ID",
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"isActive": true
	}
}

Delete Agentoverride API

[Default delete API] — This is the designated default delete API for the sys_agentOverride data object. Frontend generators and AI agents should use this API for standard CRUD operations.

Rest Route

The deleteAgentOverride API REST controller can be triggered via the following route:

/v1/agentoverride/:sys_agentOverrideId

Rest Request Parameters

The deleteAgentOverride api has got 1 regular request parameter

Parameter Type Required Population
sys_agentOverrideId ID true request.params?.[“sys_agentOverrideId”]
sys_agentOverrideId : This id paremeter is used to select the required data object that will be deleted

REST Request To access the api you can use the REST controller with the path DELETE /v1/agentoverride/:sys_agentOverrideId

  axios({
    method: 'DELETE',
    url: `/v1/agentoverride/${sys_agentOverrideId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_agentOverride",
	"method": "DELETE",
	"action": "delete",
	"appVersion": "Version",
	"rowCount": 1,
	"sys_agentOverride": {
		"id": "ID",
		"agentName": "String",
		"provider": "String",
		"model": "String",
		"systemPrompt": "Text",
		"temperature": "Double",
		"maxTokens": "Integer",
		"responseFormat": "String",
		"selectedTools": "Object",
		"guardrails": "Object",
		"enabled": "Boolean",
		"updatedBy": "ID",
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"isActive": false
	}
}

List Toolcatalog API

[Default list API] — This is the designated default list API for the sys_toolCatalog data object. Frontend generators and AI agents should use this API for standard CRUD operations.

Rest Route

The listToolCatalog API REST controller can be triggered via the following route:

/v1/toolcatalog

Rest Request Parameters

Filter Parameters

The listToolCatalog api supports 1 optional filter parameter for filtering list results:

serviceName (String): Source service name.

REST Request To access the api you can use the REST controller with the path GET /v1/toolcatalog

  axios({
    method: 'GET',
    url: '/v1/toolcatalog',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section above)
        // serviceName: '<value>' // Filter by serviceName
            }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_toolCatalogs",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"sys_toolCatalogs": [
		{
			"id": "ID",
			"toolName": "String",
			"serviceName": "String",
			"description": "Text",
			"parameters": "Object",
			"lastRefreshed": "Date",
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID",
			"isActive": true
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Get Toolcatalogentry API

[Default get API] — This is the designated default get API for the sys_toolCatalog data object. Frontend generators and AI agents should use this API for standard CRUD operations.

Rest Route

The getToolCatalogEntry API REST controller can be triggered via the following route:

/v1/toolcatalogentry/:sys_toolCatalogId

Rest Request Parameters

The getToolCatalogEntry api has got 1 regular request parameter

Parameter Type Required Population
sys_toolCatalogId ID true request.params?.[“sys_toolCatalogId”]
sys_toolCatalogId : This id paremeter is used to query the required data object.

REST Request To access the api you can use the REST controller with the path GET /v1/toolcatalogentry/:sys_toolCatalogId

  axios({
    method: 'GET',
    url: `/v1/toolcatalogentry/${sys_toolCatalogId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_toolCatalog",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"sys_toolCatalog": {
		"id": "ID",
		"toolName": "String",
		"serviceName": "String",
		"description": "Text",
		"parameters": "Object",
		"lastRefreshed": "Date",
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"isActive": true
	}
}

List Agentexecutions API

[Default list API] — This is the designated default list API for the sys_agentExecution data object. Frontend generators and AI agents should use this API for standard CRUD operations.

Rest Route

The listAgentExecutions API REST controller can be triggered via the following route:

/v1/agentexecutions

Rest Request Parameters

Filter Parameters

The listAgentExecutions api supports 5 optional filter parameters for filtering list results:

agentName (String): Agent that was executed.

agentType (Enum): Whether this was a design-time or dynamic agent.

source (Enum): How the agent was triggered.

userId (ID): User who triggered the execution.

status (Enum): Execution status.

REST Request To access the api you can use the REST controller with the path GET /v1/agentexecutions

  axios({
    method: 'GET',
    url: '/v1/agentexecutions',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section above)
        // agentName: '<value>' // Filter by agentName
        // agentType: '<value>' // Filter by agentType
        // source: '<value>' // Filter by source
        // userId: '<value>' // Filter by userId
        // status: '<value>' // Filter by status
            }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_agentExecutions",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"sys_agentExecutions": [
		{
			"id": "ID",
			"agentName": "String",
			"agentType": "Enum",
			"agentType_idx": "Integer",
			"source": "Enum",
			"source_idx": "Integer",
			"userId": "ID",
			"input": "Object",
			"output": "Object",
			"toolCalls": "Integer",
			"tokenUsage": "Object",
			"durationMs": "Integer",
			"status": "Enum",
			"status_idx": "Integer",
			"error": "Text",
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID",
			"isActive": true
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Get Agentexecution API

[Default get API] — This is the designated default get API for the sys_agentExecution data object. Frontend generators and AI agents should use this API for standard CRUD operations.

Rest Route

The getAgentExecution API REST controller can be triggered via the following route:

/v1/agentexecution/:sys_agentExecutionId

Rest Request Parameters

The getAgentExecution api has got 1 regular request parameter

Parameter Type Required Population
sys_agentExecutionId ID true request.params?.[“sys_agentExecutionId”]
sys_agentExecutionId : This id paremeter is used to query the required data object.

REST Request To access the api you can use the REST controller with the path GET /v1/agentexecution/:sys_agentExecutionId

  axios({
    method: 'GET',
    url: `/v1/agentexecution/${sys_agentExecutionId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_agentExecution",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"sys_agentExecution": {
		"id": "ID",
		"agentName": "String",
		"agentType": "Enum",
		"agentType_idx": "Integer",
		"source": "Enum",
		"source_idx": "Integer",
		"userId": "ID",
		"input": "Object",
		"output": "Object",
		"toolCalls": "Integer",
		"tokenUsage": "Object",
		"durationMs": "Integer",
		"status": "Enum",
		"status_idx": "Integer",
		"error": "Text",
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"isActive": true
	}
}

Authentication Specific Routes

Common Routes

Route: currentuser

Route Definition: Retrieves the currently authenticated user’s session information.

Route Type: sessionInfo

Access Route: GET /currentuser

Parameters

This route does not require any request parameters.

Behavior

// Sample GET /currentuser call
axios.get("/currentuser", {
  headers: {
    "Authorization": "Bearer your-jwt-token"
  }
});

Success Response Returns the session object, including user-related data and token information.

{
  "sessionId": "9cf23fa8-07d4-4e7c-80a6-ec6d6ac96bb9",
  "userId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38",
  "email": "user@example.com",
  "fullname": "John Doe",
  "roleId": "user",
  "tenantId": "abc123",
  "accessToken": "jwt-token-string",
  ...
}

Error Response 401 Unauthorized: No active session found.

{
  "status": "ERR",
  "message": "No login found"
}

Notes

Route: permissions

*Route Definition*: Retrieves all effective permission records assigned to the currently authenticated user.

*Route Type*: permissionFetch

Access Route: GET /permissions

Parameters

This route does not require any request parameters.

Behavior

// Sample GET /permissions call
axios.get("/permissions", {
  headers: {
    "Authorization": "Bearer your-jwt-token"
  }
});

Success Response

Returns an array of permission objects.

[
  {
    "id": "perm1",
    "permissionName": "adminPanel.access",
    "roleId": "admin",
    "subjectUserId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38",
    "subjectUserGroupId": null,
    "objectId": null,
    "canDo": true,
    "tenantCodename": "store123"
  },
  {
    "id": "perm2",
    "permissionName": "orders.manage",
    "roleId": null,
    "subjectUserId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38",
    "subjectUserGroupId": null,
    "objectId": null,
    "canDo": true,
    "tenantCodename": "store123"
  }
]

Each object reflects a single permission grant, aligned with the givenPermissions model:

Error Responses

{
  "status": "ERR",
  "message": "No login found"
}

Notes

Tip: Applications can cache permission results client-side or server-side, but should occasionally refresh by calling this endpoint, especially after login or permission-changing operations.

Route: permissions/:permissionName

Route Definition: Checks whether the current user has access to a specific permission, and provides a list of scoped object exceptions or inclusions.

Route Type: permissionScopeCheck

Access Route: GET /permissions/:permissionName

Parameters

Parameter Type Required Population
permissionName String Yes request.params.permissionName

Behavior

// Sample GET /permissions/orders.manage
axios.get("/permissions/orders.manage", {
  headers: {
    "Authorization": "Bearer your-jwt-token"
  }
});

Success Response

{
  "canDo": true,
  "exceptions": [
    "a1f2e3d4-xxxx-yyyy-zzzz-object1",
    "b2c3d4e5-xxxx-yyyy-zzzz-object2"
  ]
}

Copyright

All sources, documents and other digital materials are copyright of .

About Us

For more information please visit our website: .

. .


EVENT GUIDE

EVENT GUIDE

auteurlabb-agenthub-service

AI Agent Hub

Architectural Design Credit and Contact Information

The architectural design of this microservice is credited to . For inquiries, feedback, or further information regarding the architecture, please direct your communication to:

Email:

We encourage open communication and welcome any questions or discussions related to the architectural aspects of this microservice.

Documentation Scope

Welcome to the official documentation for the AgentHub Service Event descriptions. This guide is dedicated to detailing how to subscribe to and listen for state changes within the AgentHub Service, offering an exclusive focus on event subscription mechanisms.

Intended Audience

This documentation is aimed at developers and integrators looking to monitor AgentHub Service state changes. It is especially relevant for those wishing to implement or enhance business logic based on interactions with AgentHub objects.

Overview

This section provides detailed instructions on monitoring service events, covering payload structures and demonstrating typical use cases through examples.

Authentication and Authorization

Access to the AgentHub service’s events is facilitated through the project’s Kafka server, which is not accessible to the public. Subscription to a Kafka topic requires being on the same network and possessing valid Kafka user credentials. This document presupposes that readers have existing access to the Kafka server.

Additionally, the service offers a public subscription option via REST for real-time data management in frontend applications, secured through REST API authentication and authorization mechanisms. To subscribe to service events via the REST API, please consult the Realtime REST API Guide.

Database Events

Database events are triggered at the database layer, automatically and atomically, in response to any modifications at the data level. These events serve to notify subscribers about the creation, update, or deletion of objects within the database, distinct from any overarching business logic.

Listening to database events is particularly beneficial for those focused on tracking changes at the database level. A typical use case for subscribing to database events is to replicate the data store of one service within another service’s scope, ensuring data consistency and syncronization across services.

For example, while a business operation such as “approve membership” might generate a high-level business event like membership-approved, the underlying database changes could involve multiple state updates to different entities. These might be published as separate events, such as dbevent-member-updated and dbevent-user-updated, reflecting the granular changes at the database level.

Such detailed eventing provides a robust foundation for building responsive, data-driven applications, enabling fine-grained observability and reaction to the dynamics of the data landscape. It also facilitates the architectural pattern of event sourcing, where state changes are captured as a sequence of events, allowing for high-fidelity data replication and history replay for analytical or auditing purposes.

DbEvent sys_agentOverride-created

Event topic: auteurlabb-agenthub-service-dbevent-sys_agentoverride-created

This event is triggered upon the creation of a sys_agentOverride data object in the database. The event payload encompasses the newly created data, encapsulated within the root of the paylod.

Event payload:

{"id":"ID","agentName":"String","provider":"String","model":"String","systemPrompt":"Text","temperature":"Double","maxTokens":"Integer","responseFormat":"String","selectedTools":"Object","guardrails":"Object","enabled":"Boolean","updatedBy":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

DbEvent sys_agentOverride-updated

Event topic: auteurlabb-agenthub-service-dbevent-sys_agentoverride-updated

Activation of this event follows the update of a sys_agentOverride data object. The payload contains the updated information under the sys_agentOverride attribute, along with the original data prior to update, labeled as old_sys_agentOverride and also you can find the old and new versions of updated-only portion of the data…

Event payload:

{
old_sys_agentOverride:{"id":"ID","agentName":"String","provider":"String","model":"String","systemPrompt":"Text","temperature":"Double","maxTokens":"Integer","responseFormat":"String","selectedTools":"Object","guardrails":"Object","enabled":"Boolean","updatedBy":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},
sys_agentOverride:{"id":"ID","agentName":"String","provider":"String","model":"String","systemPrompt":"Text","temperature":"Double","maxTokens":"Integer","responseFormat":"String","selectedTools":"Object","guardrails":"Object","enabled":"Boolean","updatedBy":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},
oldDataValues,
newDataValues
}

DbEvent sys_agentOverride-deleted

Event topic: auteurlabb-agenthub-service-dbevent-sys_agentoverride-deleted

This event announces the deletion of a sys_agentOverride data object, covering both hard deletions (permanent removal) and soft deletions (where the isActive attribute is set to false). Regardless of the deletion type, the event payload will present the data as it was immediately before deletion, highlighting an isActive status of false for soft deletions.

Event payload:

{"id":"ID","agentName":"String","provider":"String","model":"String","systemPrompt":"Text","temperature":"Double","maxTokens":"Integer","responseFormat":"String","selectedTools":"Object","guardrails":"Object","enabled":"Boolean","updatedBy":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":false}

DbEvent sys_agentExecution-created

Event topic: auteurlabb-agenthub-service-dbevent-sys_agentexecution-created

This event is triggered upon the creation of a sys_agentExecution data object in the database. The event payload encompasses the newly created data, encapsulated within the root of the paylod.

Event payload:

{"id":"ID","agentName":"String","agentType":"Enum","agentType_idx":"Integer","source":"Enum","source_idx":"Integer","userId":"ID","input":"Object","output":"Object","toolCalls":"Integer","tokenUsage":"Object","durationMs":"Integer","status":"Enum","status_idx":"Integer","error":"Text","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

DbEvent sys_agentExecution-updated

Event topic: auteurlabb-agenthub-service-dbevent-sys_agentexecution-updated

Activation of this event follows the update of a sys_agentExecution data object. The payload contains the updated information under the sys_agentExecution attribute, along with the original data prior to update, labeled as old_sys_agentExecution and also you can find the old and new versions of updated-only portion of the data…

Event payload:

{
old_sys_agentExecution:{"id":"ID","agentName":"String","agentType":"Enum","agentType_idx":"Integer","source":"Enum","source_idx":"Integer","userId":"ID","input":"Object","output":"Object","toolCalls":"Integer","tokenUsage":"Object","durationMs":"Integer","status":"Enum","status_idx":"Integer","error":"Text","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},
sys_agentExecution:{"id":"ID","agentName":"String","agentType":"Enum","agentType_idx":"Integer","source":"Enum","source_idx":"Integer","userId":"ID","input":"Object","output":"Object","toolCalls":"Integer","tokenUsage":"Object","durationMs":"Integer","status":"Enum","status_idx":"Integer","error":"Text","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},
oldDataValues,
newDataValues
}

DbEvent sys_agentExecution-deleted

Event topic: auteurlabb-agenthub-service-dbevent-sys_agentexecution-deleted

This event announces the deletion of a sys_agentExecution data object, covering both hard deletions (permanent removal) and soft deletions (where the isActive attribute is set to false). Regardless of the deletion type, the event payload will present the data as it was immediately before deletion, highlighting an isActive status of false for soft deletions.

Event payload:

{"id":"ID","agentName":"String","agentType":"Enum","agentType_idx":"Integer","source":"Enum","source_idx":"Integer","userId":"ID","input":"Object","output":"Object","toolCalls":"Integer","tokenUsage":"Object","durationMs":"Integer","status":"Enum","status_idx":"Integer","error":"Text","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":false}

DbEvent sys_toolCatalog-created

Event topic: auteurlabb-agenthub-service-dbevent-sys_toolcatalog-created

This event is triggered upon the creation of a sys_toolCatalog data object in the database. The event payload encompasses the newly created data, encapsulated within the root of the paylod.

Event payload:

{"id":"ID","toolName":"String","serviceName":"String","description":"Text","parameters":"Object","lastRefreshed":"Date","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

DbEvent sys_toolCatalog-updated

Event topic: auteurlabb-agenthub-service-dbevent-sys_toolcatalog-updated

Activation of this event follows the update of a sys_toolCatalog data object. The payload contains the updated information under the sys_toolCatalog attribute, along with the original data prior to update, labeled as old_sys_toolCatalog and also you can find the old and new versions of updated-only portion of the data…

Event payload:

{
old_sys_toolCatalog:{"id":"ID","toolName":"String","serviceName":"String","description":"Text","parameters":"Object","lastRefreshed":"Date","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},
sys_toolCatalog:{"id":"ID","toolName":"String","serviceName":"String","description":"Text","parameters":"Object","lastRefreshed":"Date","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},
oldDataValues,
newDataValues
}

DbEvent sys_toolCatalog-deleted

Event topic: auteurlabb-agenthub-service-dbevent-sys_toolcatalog-deleted

This event announces the deletion of a sys_toolCatalog data object, covering both hard deletions (permanent removal) and soft deletions (where the isActive attribute is set to false). Regardless of the deletion type, the event payload will present the data as it was immediately before deletion, highlighting an isActive status of false for soft deletions.

Event payload:

{"id":"ID","toolName":"String","serviceName":"String","description":"Text","parameters":"Object","lastRefreshed":"Date","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":false}

ElasticSearch Index Events

Within the AgentHub service, most data objects are mirrored in ElasticSearch indices, ensuring these indices remain syncronized with their database counterparts through creation, updates, and deletions. These indices serve dual purposes: they act as a data source for external services and furnish aggregated data tailored to enhance frontend user experiences. Consequently, an ElasticSearch index might encapsulate data in its original form or aggregate additional information from other data objects.

These aggregations can include both one-to-one and one-to-many relationships not only with database objects within the same service but also across different services. This capability allows developers to access comprehensive, aggregated data efficiently. By subscribing to ElasticSearch index events, developers are notified when an index is updated and can directly obtain the aggregated entity within the event payload, bypassing the need for separate ElasticSearch queries.

It’s noteworthy that some services may augment another service’s index by appending to the entity’s extends object. In such scenarios, an *-extended event will contain only the newly added data. Should you require the complete dataset, you would need to retrieve the full ElasticSearch index entity using the provided ID.

This approach to indexing and event handling facilitates a modular, interconnected architecture where services can seamlessly integrate and react to changes, enriching the overall data ecosystem and enabling more dynamic, responsive applications.

Index Event sys_agentoverride-created

Event topic: elastic-index-auteurlabb_sys_agentoverride-created

Event payload:

{"id":"ID","agentName":"String","provider":"String","model":"String","systemPrompt":"Text","temperature":"Double","maxTokens":"Integer","responseFormat":"String","selectedTools":"Object","guardrails":"Object","enabled":"Boolean","updatedBy":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event sys_agentoverride-updated

Event topic: elastic-index-auteurlabb_sys_agentoverride-created

Event payload:

{"id":"ID","agentName":"String","provider":"String","model":"String","systemPrompt":"Text","temperature":"Double","maxTokens":"Integer","responseFormat":"String","selectedTools":"Object","guardrails":"Object","enabled":"Boolean","updatedBy":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event sys_agentoverride-deleted

Event topic: elastic-index-auteurlabb_sys_agentoverride-deleted

Event payload:

{"id":"ID","agentName":"String","provider":"String","model":"String","systemPrompt":"Text","temperature":"Double","maxTokens":"Integer","responseFormat":"String","selectedTools":"Object","guardrails":"Object","enabled":"Boolean","updatedBy":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event sys_agentoverride-extended

Event topic: elastic-index-auteurlabb_sys_agentoverride-extended

Event payload:

{
  id: id,
  extends: {
    [extendName]: "Object",
    [extendName + "_count"]: "Number",
  },
}

Route Events

Route events are emitted following the successful execution of a route. While most routes perform CRUD (Create, Read, Update, Delete) operations on data objects, resulting in route events that closely resemble database events, there are distinctions worth noting. A single route execution might trigger multiple CRUD actions and ElasticSearch indexing operations. However, for those primarily concerned with the overarching business logic and its outcomes, listening to the consolidated route event, published once at the conclusion of the route’s execution, is more pertinent.

Moreover, routes often deliver aggregated data beyond the primary database object, catering to specific client needs. For instance, creating a data object via a route might not only return the entity’s data but also route-specific metrics, such as the executing user’s permissions related to the entity. Alternatively, a route might automatically generate default child entities following the creation of a parent object. Consequently, the route event encapsulates a unified dataset encompassing both the parent and its children, in contrast to individual events triggered for each entity created. Therefore, subscribing to route events can offer a richer, more contextually relevant set of information aligned with business logic.

The payload of a route event mirrors the REST response JSON of the route, providing a direct and comprehensive reflection of the data and metadata communicated to the client. This ensures that subscribers to route events receive a payload that encapsulates both the primary data involved and any additional information deemed significant at the business level, facilitating a deeper understanding and integration of the service’s functional outcomes.

Route Event agentoverride-retrived

Event topic : auteurlabb-agenthub-service-agentoverride-retrived

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the sys_agentOverride data object itself.

The following JSON included in the payload illustrates the fullest representation of the sys_agentOverride object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_agentOverride","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_agentOverride":{"id":"ID","agentName":"String","provider":"String","model":"String","systemPrompt":"Text","temperature":"Double","maxTokens":"Integer","responseFormat":"String","selectedTools":"Object","guardrails":"Object","enabled":"Boolean","updatedBy":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true}}

Route Event agentoverrides-listed

Event topic : auteurlabb-agenthub-service-agentoverrides-listed

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the sys_agentOverrides data object itself.

The following JSON included in the payload illustrates the fullest representation of the sys_agentOverrides object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_agentOverrides","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_agentOverrides":[{"id":"ID","agentName":"String","provider":"String","model":"String","systemPrompt":"Text","temperature":"Double","maxTokens":"Integer","responseFormat":"String","selectedTools":"Object","guardrails":"Object","enabled":"Boolean","updatedBy":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]}

Route Event agentoverride-updated

Event topic : auteurlabb-agenthub-service-agentoverride-updated

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the sys_agentOverride data object itself.

The following JSON included in the payload illustrates the fullest representation of the sys_agentOverride object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_agentOverride","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"sys_agentOverride":{"id":"ID","agentName":"String","provider":"String","model":"String","systemPrompt":"Text","temperature":"Double","maxTokens":"Integer","responseFormat":"String","selectedTools":"Object","guardrails":"Object","enabled":"Boolean","updatedBy":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true}}

Route Event agentoverride-created

Event topic : auteurlabb-agenthub-service-agentoverride-created

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the sys_agentOverride data object itself.

The following JSON included in the payload illustrates the fullest representation of the sys_agentOverride object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_agentOverride","method":"POST","action":"create","appVersion":"Version","rowCount":1,"sys_agentOverride":{"id":"ID","agentName":"String","provider":"String","model":"String","systemPrompt":"Text","temperature":"Double","maxTokens":"Integer","responseFormat":"String","selectedTools":"Object","guardrails":"Object","enabled":"Boolean","updatedBy":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true}}

Route Event agentoverride-deleted

Event topic : auteurlabb-agenthub-service-agentoverride-deleted

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the sys_agentOverride data object itself.

The following JSON included in the payload illustrates the fullest representation of the sys_agentOverride object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_agentOverride","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"sys_agentOverride":{"id":"ID","agentName":"String","provider":"String","model":"String","systemPrompt":"Text","temperature":"Double","maxTokens":"Integer","responseFormat":"String","selectedTools":"Object","guardrails":"Object","enabled":"Boolean","updatedBy":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":false}}

Route Event toolcatalog-listed

Event topic : auteurlabb-agenthub-service-toolcatalog-listed

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the sys_toolCatalogs data object itself.

The following JSON included in the payload illustrates the fullest representation of the sys_toolCatalogs object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_toolCatalogs","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_toolCatalogs":[{"id":"ID","toolName":"String","serviceName":"String","description":"Text","parameters":"Object","lastRefreshed":"Date","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]}

Route Event toolcatalogentry-retrived

Event topic : auteurlabb-agenthub-service-toolcatalogentry-retrived

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the sys_toolCatalog data object itself.

The following JSON included in the payload illustrates the fullest representation of the sys_toolCatalog object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_toolCatalog","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_toolCatalog":{"id":"ID","toolName":"String","serviceName":"String","description":"Text","parameters":"Object","lastRefreshed":"Date","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true}}

Route Event agentexecutions-listed

Event topic : auteurlabb-agenthub-service-agentexecutions-listed

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the sys_agentExecutions data object itself.

The following JSON included in the payload illustrates the fullest representation of the sys_agentExecutions object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_agentExecutions","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_agentExecutions":[{"id":"ID","agentName":"String","agentType":"Enum","agentType_idx":"Integer","source":"Enum","source_idx":"Integer","userId":"ID","input":"Object","output":"Object","toolCalls":"Integer","tokenUsage":"Object","durationMs":"Integer","status":"Enum","status_idx":"Integer","error":"Text","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]}

Route Event agentexecution-retrived

Event topic : auteurlabb-agenthub-service-agentexecution-retrived

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the sys_agentExecution data object itself.

The following JSON included in the payload illustrates the fullest representation of the sys_agentExecution object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_agentExecution","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_agentExecution":{"id":"ID","agentName":"String","agentType":"Enum","agentType_idx":"Integer","source":"Enum","source_idx":"Integer","userId":"ID","input":"Object","output":"Object","toolCalls":"Integer","tokenUsage":"Object","durationMs":"Integer","status":"Enum","status_idx":"Integer","error":"Text","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true}}

Index Event sys_agentexecution-created

Event topic: elastic-index-auteurlabb_sys_agentexecution-created

Event payload:

{"id":"ID","agentName":"String","agentType":"Enum","agentType_idx":"Integer","source":"Enum","source_idx":"Integer","userId":"ID","input":"Object","output":"Object","toolCalls":"Integer","tokenUsage":"Object","durationMs":"Integer","status":"Enum","status_idx":"Integer","error":"Text","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event sys_agentexecution-updated

Event topic: elastic-index-auteurlabb_sys_agentexecution-created

Event payload:

{"id":"ID","agentName":"String","agentType":"Enum","agentType_idx":"Integer","source":"Enum","source_idx":"Integer","userId":"ID","input":"Object","output":"Object","toolCalls":"Integer","tokenUsage":"Object","durationMs":"Integer","status":"Enum","status_idx":"Integer","error":"Text","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event sys_agentexecution-deleted

Event topic: elastic-index-auteurlabb_sys_agentexecution-deleted

Event payload:

{"id":"ID","agentName":"String","agentType":"Enum","agentType_idx":"Integer","source":"Enum","source_idx":"Integer","userId":"ID","input":"Object","output":"Object","toolCalls":"Integer","tokenUsage":"Object","durationMs":"Integer","status":"Enum","status_idx":"Integer","error":"Text","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event sys_agentexecution-extended

Event topic: elastic-index-auteurlabb_sys_agentexecution-extended

Event payload:

{
  id: id,
  extends: {
    [extendName]: "Object",
    [extendName + "_count"]: "Number",
  },
}

Route Events

Route events are emitted following the successful execution of a route. While most routes perform CRUD (Create, Read, Update, Delete) operations on data objects, resulting in route events that closely resemble database events, there are distinctions worth noting. A single route execution might trigger multiple CRUD actions and ElasticSearch indexing operations. However, for those primarily concerned with the overarching business logic and its outcomes, listening to the consolidated route event, published once at the conclusion of the route’s execution, is more pertinent.

Moreover, routes often deliver aggregated data beyond the primary database object, catering to specific client needs. For instance, creating a data object via a route might not only return the entity’s data but also route-specific metrics, such as the executing user’s permissions related to the entity. Alternatively, a route might automatically generate default child entities following the creation of a parent object. Consequently, the route event encapsulates a unified dataset encompassing both the parent and its children, in contrast to individual events triggered for each entity created. Therefore, subscribing to route events can offer a richer, more contextually relevant set of information aligned with business logic.

The payload of a route event mirrors the REST response JSON of the route, providing a direct and comprehensive reflection of the data and metadata communicated to the client. This ensures that subscribers to route events receive a payload that encapsulates both the primary data involved and any additional information deemed significant at the business level, facilitating a deeper understanding and integration of the service’s functional outcomes.

Route Event agentoverride-retrived

Event topic : auteurlabb-agenthub-service-agentoverride-retrived

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the sys_agentOverride data object itself.

The following JSON included in the payload illustrates the fullest representation of the sys_agentOverride object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_agentOverride","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_agentOverride":{"id":"ID","agentName":"String","provider":"String","model":"String","systemPrompt":"Text","temperature":"Double","maxTokens":"Integer","responseFormat":"String","selectedTools":"Object","guardrails":"Object","enabled":"Boolean","updatedBy":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true}}

Route Event agentoverrides-listed

Event topic : auteurlabb-agenthub-service-agentoverrides-listed

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the sys_agentOverrides data object itself.

The following JSON included in the payload illustrates the fullest representation of the sys_agentOverrides object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_agentOverrides","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_agentOverrides":[{"id":"ID","agentName":"String","provider":"String","model":"String","systemPrompt":"Text","temperature":"Double","maxTokens":"Integer","responseFormat":"String","selectedTools":"Object","guardrails":"Object","enabled":"Boolean","updatedBy":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]}

Route Event agentoverride-updated

Event topic : auteurlabb-agenthub-service-agentoverride-updated

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the sys_agentOverride data object itself.

The following JSON included in the payload illustrates the fullest representation of the sys_agentOverride object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_agentOverride","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"sys_agentOverride":{"id":"ID","agentName":"String","provider":"String","model":"String","systemPrompt":"Text","temperature":"Double","maxTokens":"Integer","responseFormat":"String","selectedTools":"Object","guardrails":"Object","enabled":"Boolean","updatedBy":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true}}

Route Event agentoverride-created

Event topic : auteurlabb-agenthub-service-agentoverride-created

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the sys_agentOverride data object itself.

The following JSON included in the payload illustrates the fullest representation of the sys_agentOverride object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_agentOverride","method":"POST","action":"create","appVersion":"Version","rowCount":1,"sys_agentOverride":{"id":"ID","agentName":"String","provider":"String","model":"String","systemPrompt":"Text","temperature":"Double","maxTokens":"Integer","responseFormat":"String","selectedTools":"Object","guardrails":"Object","enabled":"Boolean","updatedBy":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true}}

Route Event agentoverride-deleted

Event topic : auteurlabb-agenthub-service-agentoverride-deleted

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the sys_agentOverride data object itself.

The following JSON included in the payload illustrates the fullest representation of the sys_agentOverride object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_agentOverride","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"sys_agentOverride":{"id":"ID","agentName":"String","provider":"String","model":"String","systemPrompt":"Text","temperature":"Double","maxTokens":"Integer","responseFormat":"String","selectedTools":"Object","guardrails":"Object","enabled":"Boolean","updatedBy":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":false}}

Route Event toolcatalog-listed

Event topic : auteurlabb-agenthub-service-toolcatalog-listed

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the sys_toolCatalogs data object itself.

The following JSON included in the payload illustrates the fullest representation of the sys_toolCatalogs object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_toolCatalogs","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_toolCatalogs":[{"id":"ID","toolName":"String","serviceName":"String","description":"Text","parameters":"Object","lastRefreshed":"Date","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]}

Route Event toolcatalogentry-retrived

Event topic : auteurlabb-agenthub-service-toolcatalogentry-retrived

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the sys_toolCatalog data object itself.

The following JSON included in the payload illustrates the fullest representation of the sys_toolCatalog object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_toolCatalog","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_toolCatalog":{"id":"ID","toolName":"String","serviceName":"String","description":"Text","parameters":"Object","lastRefreshed":"Date","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true}}

Route Event agentexecutions-listed

Event topic : auteurlabb-agenthub-service-agentexecutions-listed

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the sys_agentExecutions data object itself.

The following JSON included in the payload illustrates the fullest representation of the sys_agentExecutions object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_agentExecutions","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_agentExecutions":[{"id":"ID","agentName":"String","agentType":"Enum","agentType_idx":"Integer","source":"Enum","source_idx":"Integer","userId":"ID","input":"Object","output":"Object","toolCalls":"Integer","tokenUsage":"Object","durationMs":"Integer","status":"Enum","status_idx":"Integer","error":"Text","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]}

Route Event agentexecution-retrived

Event topic : auteurlabb-agenthub-service-agentexecution-retrived

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the sys_agentExecution data object itself.

The following JSON included in the payload illustrates the fullest representation of the sys_agentExecution object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_agentExecution","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_agentExecution":{"id":"ID","agentName":"String","agentType":"Enum","agentType_idx":"Integer","source":"Enum","source_idx":"Integer","userId":"ID","input":"Object","output":"Object","toolCalls":"Integer","tokenUsage":"Object","durationMs":"Integer","status":"Enum","status_idx":"Integer","error":"Text","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true}}

Index Event sys_toolcatalog-created

Event topic: elastic-index-auteurlabb_sys_toolcatalog-created

Event payload:

{"id":"ID","toolName":"String","serviceName":"String","description":"Text","parameters":"Object","lastRefreshed":"Date","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event sys_toolcatalog-updated

Event topic: elastic-index-auteurlabb_sys_toolcatalog-created

Event payload:

{"id":"ID","toolName":"String","serviceName":"String","description":"Text","parameters":"Object","lastRefreshed":"Date","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event sys_toolcatalog-deleted

Event topic: elastic-index-auteurlabb_sys_toolcatalog-deleted

Event payload:

{"id":"ID","toolName":"String","serviceName":"String","description":"Text","parameters":"Object","lastRefreshed":"Date","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event sys_toolcatalog-extended

Event topic: elastic-index-auteurlabb_sys_toolcatalog-extended

Event payload:

{
  id: id,
  extends: {
    [extendName]: "Object",
    [extendName + "_count"]: "Number",
  },
}

Route Events

Route events are emitted following the successful execution of a route. While most routes perform CRUD (Create, Read, Update, Delete) operations on data objects, resulting in route events that closely resemble database events, there are distinctions worth noting. A single route execution might trigger multiple CRUD actions and ElasticSearch indexing operations. However, for those primarily concerned with the overarching business logic and its outcomes, listening to the consolidated route event, published once at the conclusion of the route’s execution, is more pertinent.

Moreover, routes often deliver aggregated data beyond the primary database object, catering to specific client needs. For instance, creating a data object via a route might not only return the entity’s data but also route-specific metrics, such as the executing user’s permissions related to the entity. Alternatively, a route might automatically generate default child entities following the creation of a parent object. Consequently, the route event encapsulates a unified dataset encompassing both the parent and its children, in contrast to individual events triggered for each entity created. Therefore, subscribing to route events can offer a richer, more contextually relevant set of information aligned with business logic.

The payload of a route event mirrors the REST response JSON of the route, providing a direct and comprehensive reflection of the data and metadata communicated to the client. This ensures that subscribers to route events receive a payload that encapsulates both the primary data involved and any additional information deemed significant at the business level, facilitating a deeper understanding and integration of the service’s functional outcomes.

Route Event agentoverride-retrived

Event topic : auteurlabb-agenthub-service-agentoverride-retrived

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the sys_agentOverride data object itself.

The following JSON included in the payload illustrates the fullest representation of the sys_agentOverride object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_agentOverride","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_agentOverride":{"id":"ID","agentName":"String","provider":"String","model":"String","systemPrompt":"Text","temperature":"Double","maxTokens":"Integer","responseFormat":"String","selectedTools":"Object","guardrails":"Object","enabled":"Boolean","updatedBy":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true}}

Route Event agentoverrides-listed

Event topic : auteurlabb-agenthub-service-agentoverrides-listed

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the sys_agentOverrides data object itself.

The following JSON included in the payload illustrates the fullest representation of the sys_agentOverrides object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_agentOverrides","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_agentOverrides":[{"id":"ID","agentName":"String","provider":"String","model":"String","systemPrompt":"Text","temperature":"Double","maxTokens":"Integer","responseFormat":"String","selectedTools":"Object","guardrails":"Object","enabled":"Boolean","updatedBy":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]}

Route Event agentoverride-updated

Event topic : auteurlabb-agenthub-service-agentoverride-updated

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the sys_agentOverride data object itself.

The following JSON included in the payload illustrates the fullest representation of the sys_agentOverride object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_agentOverride","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"sys_agentOverride":{"id":"ID","agentName":"String","provider":"String","model":"String","systemPrompt":"Text","temperature":"Double","maxTokens":"Integer","responseFormat":"String","selectedTools":"Object","guardrails":"Object","enabled":"Boolean","updatedBy":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true}}

Route Event agentoverride-created

Event topic : auteurlabb-agenthub-service-agentoverride-created

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the sys_agentOverride data object itself.

The following JSON included in the payload illustrates the fullest representation of the sys_agentOverride object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_agentOverride","method":"POST","action":"create","appVersion":"Version","rowCount":1,"sys_agentOverride":{"id":"ID","agentName":"String","provider":"String","model":"String","systemPrompt":"Text","temperature":"Double","maxTokens":"Integer","responseFormat":"String","selectedTools":"Object","guardrails":"Object","enabled":"Boolean","updatedBy":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true}}

Route Event agentoverride-deleted

Event topic : auteurlabb-agenthub-service-agentoverride-deleted

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the sys_agentOverride data object itself.

The following JSON included in the payload illustrates the fullest representation of the sys_agentOverride object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_agentOverride","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"sys_agentOverride":{"id":"ID","agentName":"String","provider":"String","model":"String","systemPrompt":"Text","temperature":"Double","maxTokens":"Integer","responseFormat":"String","selectedTools":"Object","guardrails":"Object","enabled":"Boolean","updatedBy":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":false}}

Route Event toolcatalog-listed

Event topic : auteurlabb-agenthub-service-toolcatalog-listed

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the sys_toolCatalogs data object itself.

The following JSON included in the payload illustrates the fullest representation of the sys_toolCatalogs object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_toolCatalogs","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_toolCatalogs":[{"id":"ID","toolName":"String","serviceName":"String","description":"Text","parameters":"Object","lastRefreshed":"Date","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]}

Route Event toolcatalogentry-retrived

Event topic : auteurlabb-agenthub-service-toolcatalogentry-retrived

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the sys_toolCatalog data object itself.

The following JSON included in the payload illustrates the fullest representation of the sys_toolCatalog object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_toolCatalog","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_toolCatalog":{"id":"ID","toolName":"String","serviceName":"String","description":"Text","parameters":"Object","lastRefreshed":"Date","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true}}

Route Event agentexecutions-listed

Event topic : auteurlabb-agenthub-service-agentexecutions-listed

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the sys_agentExecutions data object itself.

The following JSON included in the payload illustrates the fullest representation of the sys_agentExecutions object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_agentExecutions","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_agentExecutions":[{"id":"ID","agentName":"String","agentType":"Enum","agentType_idx":"Integer","source":"Enum","source_idx":"Integer","userId":"ID","input":"Object","output":"Object","toolCalls":"Integer","tokenUsage":"Object","durationMs":"Integer","status":"Enum","status_idx":"Integer","error":"Text","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]}

Route Event agentexecution-retrived

Event topic : auteurlabb-agenthub-service-agentexecution-retrived

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the sys_agentExecution data object itself.

The following JSON included in the payload illustrates the fullest representation of the sys_agentExecution object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_agentExecution","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_agentExecution":{"id":"ID","agentName":"String","agentType":"Enum","agentType_idx":"Integer","source":"Enum","source_idx":"Integer","userId":"ID","input":"Object","output":"Object","toolCalls":"Integer","tokenUsage":"Object","durationMs":"Integer","status":"Enum","status_idx":"Integer","error":"Text","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true}}

Copyright

All sources, documents and other digital materials are copyright of .

About Us

For more information please visit our website: .

. .


Data Objects

Service Design Specification - Object Design for sys_agentOverride

Service Design Specification - Object Design for sys_agentOverride

auteurlabb-agenthub-service documentation

Document Overview

This document outlines the object design for the sys_agentOverride model in our application. It includes details about the model’s attributes, relationships, and any specific validation or business logic that applies.

sys_agentOverride Data Object

Object Overview

Description: Runtime overrides for design-time agents. Null fields use the design default.

This object represents a core data structure within the service and acts as the blueprint for database interaction, API generation, and business logic enforcement. It is defined using the ObjectSettings pattern, which governs its behavior, access control, caching strategy, and integration points with other systems such as Stripe and Redis.

Core Configuration

Properties Schema

Property Type Required Description
agentName String Yes Design-time agent name this override applies to.
provider String No Override AI provider (e.g., openai, anthropic).
model String No Override model name.
systemPrompt Text No Override system prompt.
temperature Double No Override temperature (0-2).
maxTokens Integer No Override max tokens.
responseFormat String No Override response format (text/json).
selectedTools Object No Array of tool names from the catalog that this agent can use.
guardrails Object No Override guardrails: { maxToolCalls, timeout, maxTokenBudget }.
enabled Boolean Yes Enable or disable this agent.
updatedBy ID No User who last updated this override.

Default Values

Default values are automatically assigned to properties when a new object is created, if no value is provided in the request body. Since default values are applied on db level, they should be literal values, not expressions.If you want to use expressions, you can use transposed parameters in any business API to set default values dynamically.

Always Create with Default Values

Some of the default values are set to be always used when creating a new object, even if the property value is provided in the request body. It ensures that the property is always initialized with a default value when the object is created.

Constant Properties

agentName

Constant properties are defined to be immutable after creation, meaning they cannot be updated or changed once set. They are typically used for properties that should remain constant throughout the object’s lifecycle. A property is set to be constant if the Allow Update option is set to false.

Auto Update Properties

agentName provider model systemPrompt temperature maxTokens responseFormat selectedTools guardrails enabled updatedBy

An update crud API created with the option Auto Params enabled will automatically update these properties with the provided values in the request body. If you want to update any property in your own business logic not by user input, you can set the Allow Auto Update option to false. These properties will be added to the update API’s body parameters and can be updated by the user if any value is provided in the request body.

Elastic Search Indexing

agentName enabled

Properties that are indexed in Elastic Search will be searchable via the Elastic Search API. While all properties are stored in the elastic search index of the data object, only those marked for Elastic Search indexing will be available for search queries.

Database Indexing

agentName enabled

Properties that are indexed in the database will be optimized for query performance, allowing for faster data retrieval. Make a property indexed in the database if you want to use it frequently in query filters or sorting.

Unique Properties

agentName

Unique properties are enforced to have distinct values across all instances of the data object, preventing duplicate entries. Note that a unique property is automatically indexed in the database so you will not need to set the Indexed in DB option.

Session Data Properties

updatedBy

Session data properties are used to store data that is specific to the user session, allowing for personalized experiences and temporary data storage. If a property is configured as session data, it will be automatically mapped to the related field in the user session during CRUD operations. Note that session data properties can not be mutated by the user, but only by the system.


Service Design Specification - Object Design for sys_agentExecution

Service Design Specification - Object Design for sys_agentExecution

auteurlabb-agenthub-service documentation

Document Overview

This document outlines the object design for the sys_agentExecution model in our application. It includes details about the model’s attributes, relationships, and any specific validation or business logic that applies.

sys_agentExecution Data Object

Object Overview

Description: Agent execution log. Records each agent invocation with input, output, and performance metrics.

This object represents a core data structure within the service and acts as the blueprint for database interaction, API generation, and business logic enforcement. It is defined using the ObjectSettings pattern, which governs its behavior, access control, caching strategy, and integration points with other systems such as Stripe and Redis.

Core Configuration

Properties Schema

Property Type Required Description
agentName String Yes Agent that was executed.
agentType Enum Yes Whether this was a design-time or dynamic agent.
source Enum Yes How the agent was triggered.
userId ID No User who triggered the execution.
input Object No Request input (truncated for large payloads).
output Object No Response output (truncated for large payloads).
toolCalls Integer No Number of tool calls made during execution.
tokenUsage Object No Token usage: { prompt, completion, total }.
durationMs Integer No Execution time in milliseconds.
status Enum Yes Execution status.
error Text No Error message if execution failed.

Default Values

Default values are automatically assigned to properties when a new object is created, if no value is provided in the request body. Since default values are applied on db level, they should be literal values, not expressions.If you want to use expressions, you can use transposed parameters in any business API to set default values dynamically.

Constant Properties

agentName agentType source userId input output toolCalls tokenUsage durationMs status error

Constant properties are defined to be immutable after creation, meaning they cannot be updated or changed once set. They are typically used for properties that should remain constant throughout the object’s lifecycle. A property is set to be constant if the Allow Update option is set to false.

Auto Update Properties

agentName agentType source userId input output toolCalls tokenUsage durationMs status error

An update crud API created with the option Auto Params enabled will automatically update these properties with the provided values in the request body. If you want to update any property in your own business logic not by user input, you can set the Allow Auto Update option to false. These properties will be added to the update API’s body parameters and can be updated by the user if any value is provided in the request body.

Enum Properties

Enum properties are defined with a set of allowed values, ensuring that only valid options can be assigned to them. The enum options value will be stored as strings in the database, but when a data object is created an addtional property with the same name plus an idx suffix will be created, which will hold the index of the selected enum option. You can use the index property to sort by the enum value or when your enum options represent a sequence of values.

Elastic Search Indexing

agentName agentType source userId toolCalls durationMs status

Properties that are indexed in Elastic Search will be searchable via the Elastic Search API. While all properties are stored in the elastic search index of the data object, only those marked for Elastic Search indexing will be available for search queries.

Database Indexing

agentName agentType source userId status

Properties that are indexed in the database will be optimized for query performance, allowing for faster data retrieval. Make a property indexed in the database if you want to use it frequently in query filters or sorting.

Filter Properties

agentName agentType source userId status

Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API’s that have “Auto Params” enabled.


Service Design Specification - Object Design for sys_toolCatalog

Service Design Specification - Object Design for sys_toolCatalog

auteurlabb-agenthub-service documentation

Document Overview

This document outlines the object design for the sys_toolCatalog model in our application. It includes details about the model’s attributes, relationships, and any specific validation or business logic that applies.

sys_toolCatalog Data Object

Object Overview

Description: Cached tool catalog discovered from project services. Refreshed periodically.

This object represents a core data structure within the service and acts as the blueprint for database interaction, API generation, and business logic enforcement. It is defined using the ObjectSettings pattern, which governs its behavior, access control, caching strategy, and integration points with other systems such as Stripe and Redis.

Core Configuration

Properties Schema

Property Type Required Description
toolName String Yes Full tool name (e.g., service:apiName).
serviceName String Yes Source service name.
description Text No Tool description.
parameters Object No JSON Schema of tool parameters.
lastRefreshed Date No When this tool was last discovered/refreshed.

Default Values

Default values are automatically assigned to properties when a new object is created, if no value is provided in the request body. Since default values are applied on db level, they should be literal values, not expressions.If you want to use expressions, you can use transposed parameters in any business API to set default values dynamically.

Auto Update Properties

toolName serviceName description parameters lastRefreshed

An update crud API created with the option Auto Params enabled will automatically update these properties with the provided values in the request body. If you want to update any property in your own business logic not by user input, you can set the Allow Auto Update option to false. These properties will be added to the update API’s body parameters and can be updated by the user if any value is provided in the request body.

Elastic Search Indexing

toolName serviceName description

Properties that are indexed in Elastic Search will be searchable via the Elastic Search API. While all properties are stored in the elastic search index of the data object, only those marked for Elastic Search indexing will be available for search queries.

Database Indexing

toolName serviceName

Properties that are indexed in the database will be optimized for query performance, allowing for faster data retrieval. Make a property indexed in the database if you want to use it frequently in query filters or sorting.

Unique Properties

toolName

Unique properties are enforced to have distinct values across all instances of the data object, preventing duplicate entries. Note that a unique property is automatically indexed in the database so you will not need to set the Indexed in DB option.

Filter Properties

serviceName

Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API’s that have “Auto Params” enabled.


Business APIs

Business API Design Specification - Get Agentoverride

Business API Design Specification - Get Agentoverride

A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic.

While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized.

This document provides an in-depth explanation of the architectural design of the getAgentOverride Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side.

Main Data Object and CRUD Operation

The getAgentOverride Business API is designed to handle a get operation on the Sys_agentOverride data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The getAgentOverride Business API includes a REST controller that can be triggered via the following route:

/v1/agentoverride/:sys_agentOverrideId

By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the Parameters section.

MCP Tool

REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This getAgentOverride Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The getAgentOverride Business API has 1 parameter that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client.

Business API parameters can be:

Regular Parameters

Name Type Required Default Location Data Path
sys_agentOverrideId ID Yes - urlpath sys_agentOverrideId
Description: This id paremeter is used to query the required data object.

Parameter Transformations

Some parameters are post-processed using transform scripts after being read from the request but before validation or workflow execution. Only parameters with a transform script are listed below.

No parameters are transformed in this API.

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the getAgentOverride Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Select Clause

Specifies which fields will be selected from the main data object during a get or list operation. Leave blank to select all properties. This applies only to get and list type APIs.",

``

Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({id:this.sys_agentOverrideId}), {"path":"services[4].businessLogic[0].whereClause.fullWhereClause"})

Get Options

Use these options to set get specific settings.

setAsRead: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed.

No setAsread field-value pair is configured.

Business Logic Workflow

[1] Step : startBusinessApi

Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Extracts parameters from request and Redis, applies defaults, and writes them to context.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Executes parameter transformation scripts, applies type coercion, merges derived values, and reshapes inputs for downstream milestones.


[4] Step : checkParameters

Validates required and custom parameters, enforcing business-specific rules and constraints.


[5] Step : checkBasicAuth

Performs login, role, and permission checks, and applies dynamic object-level access rules.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildWhereClause

Builds the WHERE clause for fetching the object and applies additional scoped filters if configured.

You can use the following settings to change some behavior of this step. whereClause

[7] Step : mainGetOperation

Executes the database fetch, retrieves the object, and stores it in context for enrichment or further checks.

You can use the following settings to change some behavior of this step. selectClause, getOptions

[8] Step : checkInstance

Performs instance-level validations, such as ownership, existence, or access conditions.


[9] Step : buildOutput

Assembles the response from the object, applies masking, formatting, and injects additional metadata if needed.


[10] Step : sendResponse

Delivers the response to the controller for client delivery.


[11] Step : raiseApiEvent

Triggers optional API-level events after workflow completion, sending messages to integrations like Kafka if configured.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The getAgentOverride api has got 1 regular client parameter

Parameter Type Required Population
sys_agentOverrideId ID true request.params?.[“sys_agentOverrideId”]

REST Request

To access the api you can use the REST controller with the path GET /v1/agentoverride/:sys_agentOverrideId

  axios({
    method: 'GET',
    url: `/v1/agentoverride/${sys_agentOverrideId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the sys_agentOverride object in the respones. However, some properties may be omitted based on the object’s internal logic.

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_agentOverride",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"sys_agentOverride": {
		"id": "ID",
		"agentName": "String",
		"provider": "String",
		"model": "String",
		"systemPrompt": "Text",
		"temperature": "Double",
		"maxTokens": "Integer",
		"responseFormat": "String",
		"selectedTools": "Object",
		"guardrails": "Object",
		"enabled": "Boolean",
		"updatedBy": "ID",
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"isActive": true
	}
}

Business API Design Specification - List Agentoverrides

Business API Design Specification - List Agentoverrides

A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic.

While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized.

This document provides an in-depth explanation of the architectural design of the listAgentOverrides Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side.

Main Data Object and CRUD Operation

The listAgentOverrides Business API is designed to handle a list operation on the Sys_agentOverride data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The listAgentOverrides Business API includes a REST controller that can be triggered via the following route:

/v1/agentoverrides

By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the Parameters section.

MCP Tool

REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This listAgentOverrides Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The listAgentOverrides Business API does not require any parameters to be provided from the controllers.

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the listAgentOverrides Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Select Clause

Specifies which fields will be selected from the main data object during a get or list operation. Leave blank to select all properties. This applies only to get and list type APIs.",

``

Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

null

List Options

Defines list-specific options including filtering logic, default sorting, and result customization for APIs that return multiple records.

List Sort By Sort order definitions for the result set. Multiple fields can be provided with direction (asc/desc).

Specific sort order is not configure, natural order (ascending id) will be used.

List Group By Grouping definitions for the result set. This is typically used for visual or report-based grouping.

The list is not grouped.

setAsRead: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed.

No setAsread field-value pair is configured.

Permission Filter Optional filter that applies permission constraints dynamically based on session or object roles. So that the list items are filtered by the user’s OBAC or ABAC permissions.

Permission filter is not active at the moment. Follow Mindbricks updates to be able to use it.

Pagination Options

Contains settings to configure pagination behavior for list APIs. Includes options like page size, offset, cursor support, and total count inclusion.

Business Logic Workflow

[1] Step : startBusinessApi

Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Reads request and Redis parameters, applies defaults, and writes them to context for downstream processing.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Transforms and normalizes parameters, derives dependent values, and reshapes inputs for the main list query.


[4] Step : checkParameters

Executes validation logic on required and custom parameters, enforcing business rules and cross-field consistency.


[5] Step : checkBasicAuth

Performs role-based access checks and applies dynamic membership or session-based restrictions.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildWhereClause

Constructs the main query WHERE clause and applies optional filters or scoped access controls.

You can use the following settings to change some behavior of this step. whereClause

[7] Step : mainListOperation

Executes the paginated database query, retrieves the list, and stores results in context for enrichment.

You can use the following settings to change some behavior of this step. selectClause, listOptions, paginationOptions

[8] Step : buildOutput

Assembles the list response, sanitizes sensitive fields, applies transformations, and injects extra context if needed.


[9] Step : sendResponse

Sends the paginated list to the client through the controller.


[10] Step : raiseApiEvent

Triggers optional post-workflow events, such as Kafka messages, logs, or system notifications.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The listAgentOverrides api has got no visible parameters.

REST Request

To access the api you can use the REST controller with the path GET /v1/agentoverrides

  axios({
    method: 'GET',
    url: '/v1/agentoverrides',
    data: {
    
    },
    params: {
    
        }
  });

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the sys_agentOverrides object in the respones. However, some properties may be omitted based on the object’s internal logic.

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_agentOverrides",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"sys_agentOverrides": [
		{
			"id": "ID",
			"agentName": "String",
			"provider": "String",
			"model": "String",
			"systemPrompt": "Text",
			"temperature": "Double",
			"maxTokens": "Integer",
			"responseFormat": "String",
			"selectedTools": "Object",
			"guardrails": "Object",
			"enabled": "Boolean",
			"updatedBy": "ID",
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID",
			"isActive": true
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Business API Design Specification - Update Agentoverride

Business API Design Specification - Update Agentoverride

A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic.

While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized.

This document provides an in-depth explanation of the architectural design of the updateAgentOverride Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side.

Main Data Object and CRUD Operation

The updateAgentOverride Business API is designed to handle a update operation on the Sys_agentOverride data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The updateAgentOverride Business API includes a REST controller that can be triggered via the following route:

/v1/agentoverride/:sys_agentOverrideId

By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the Parameters section.

MCP Tool

REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This updateAgentOverride Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The updateAgentOverride Business API has 11 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client.

Business API parameters can be:

Regular Parameters

Name Type Required Default Location Data Path
sys_agentOverrideId ID Yes - urlpath sys_agentOverrideId
Description: This id paremeter is used to select the required data object that will be updated
provider String No - body provider
Description: Override AI provider (e.g., openai, anthropic).
model String No - body model
Description: Override model name.
systemPrompt Text No - body systemPrompt
Description: Override system prompt.
temperature Double No - body temperature
Description: Override temperature (0-2).
maxTokens Integer No - body maxTokens
Description: Override max tokens.
responseFormat String No - body responseFormat
Description: Override response format (text/json).
selectedTools Object No - body selectedTools
Description: Array of tool names from the catalog that this agent can use.
guardrails Object No - body guardrails
Description: Override guardrails: { maxToolCalls, timeout, maxTokenBudget }.
enabled Boolean No - body enabled
Description: Enable or disable this agent.
updatedBy ID No - session userId
Description: User who last updated this override.

Parameter Transformations

Some parameters are post-processed using transform scripts after being read from the request but before validation or workflow execution. Only parameters with a transform script are listed below.

No parameters are transformed in this API.

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the updateAgentOverride Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({id:this.sys_agentOverrideId}), {"path":"services[4].businessLogic[2].whereClause.fullWhereClause"})

Data Clause

Defines custom field-value assignments used to modify or augment the default payload for create and update operations. These settings override values derived from the session or parameters if explicitly provided.", Note that a default data clause is always prepared by Mindbricks using data property settings, however any property in the data clause can be override by Data Clause Settings.

An update data clause populates all update-allowed properties of a data object, however the null properties (that are not provided by client) are ignored in db layer.

Custom Data Clause Override No custom data clause override configured

Actual Data Clause

The business api will use the following data clause. Note that any calculated value will be added to the data clause in the api manager.

{
  provider: this.provider,
  model: this.model,
  systemPrompt: this.systemPrompt,
  temperature: this.temperature,
  maxTokens: this.maxTokens,
  responseFormat: this.responseFormat,
  selectedTools: this.selectedTools ? (typeof this.selectedTools == 'string' ? JSON.parse(this.selectedTools) : this.selectedTools) : null,
  guardrails: this.guardrails ? (typeof this.guardrails == 'string' ? JSON.parse(this.guardrails) : this.guardrails) : null,
  enabled: this.enabled,
  updatedBy: this.updatedBy,
}

Business Logic Workflow

[1] Step : startBusinessApi

Manager initializes context, prepares request and session objects, and sets up internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Manager reads parameters from the request or Redis, applies defaults, and writes them into context for downstream milestones.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Manager executes parameter transform scripts and derives any helper values or reshaped payloads into the context.


[4] Step : checkParameters

Manager validates required parameters, checks ID formats (UUID/ObjectId), and ensures all preconditions for update are met.


[5] Step : checkBasicAuth

Manager performs login verification, role, and permission checks, enforcing tenant and access rules before update.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildWhereClause

Manager constructs the WHERE clause used to identify the record to update, applying ownership and parent checks if necessary.

You can use the following settings to change some behavior of this step. whereClause

[7] Step : fetchInstance

Manager fetches the existing record from the database and writes it to the context for validation or enrichment.


[8] Step : checkInstance

Manager performs instance-level validations, including ownership, existence, lock status, or other pre-update checks.


[9] Step : buildDataClause

Manager prepares the data clause for the update, applying transformations or enhancements before persisting.

You can use the following settings to change some behavior of this step. dataClause

[10] Step : mainUpdateOperation

Manager executes the update operation with the WHERE and data clauses. Database-level events are raised if configured.


[11] Step : buildOutput

Manager assembles the response object from the update result, masking fields or injecting additional metadata.


[12] Step : sendResponse

Manager sends the response back to the controller for delivery to the client.


[13] Step : raiseApiEvent

Manager triggers API-level events, sending relevant messages to Kafka or other integrations if configured.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The updateAgentOverride api has got 10 regular client parameters

Parameter Type Required Population
sys_agentOverrideId ID true request.params?.[“sys_agentOverrideId”]
provider String request.body?.[“provider”]
model String request.body?.[“model”]
systemPrompt Text request.body?.[“systemPrompt”]
temperature Double request.body?.[“temperature”]
maxTokens Integer request.body?.[“maxTokens”]
responseFormat String request.body?.[“responseFormat”]
selectedTools Object request.body?.[“selectedTools”]
guardrails Object request.body?.[“guardrails”]
enabled Boolean request.body?.[“enabled”]

REST Request

To access the api you can use the REST controller with the path PATCH /v1/agentoverride/:sys_agentOverrideId

  axios({
    method: 'PATCH',
    url: `/v1/agentoverride/${sys_agentOverrideId}`,
    data: {
            provider:"String",  
            model:"String",  
            systemPrompt:"Text",  
            temperature:"Double",  
            maxTokens:"Integer",  
            responseFormat:"String",  
            selectedTools:"Object",  
            guardrails:"Object",  
            enabled:"Boolean",  
    
    },
    params: {
    
        }
  });

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the sys_agentOverride object in the respones. However, some properties may be omitted based on the object’s internal logic.

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_agentOverride",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"sys_agentOverride": {
		"id": "ID",
		"agentName": "String",
		"provider": "String",
		"model": "String",
		"systemPrompt": "Text",
		"temperature": "Double",
		"maxTokens": "Integer",
		"responseFormat": "String",
		"selectedTools": "Object",
		"guardrails": "Object",
		"enabled": "Boolean",
		"updatedBy": "ID",
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"isActive": true
	}
}

Business API Design Specification - Create Agentoverride

Business API Design Specification - Create Agentoverride

A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic.

While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized.

This document provides an in-depth explanation of the architectural design of the createAgentOverride Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side.

Main Data Object and CRUD Operation

The createAgentOverride Business API is designed to handle a create operation on the Sys_agentOverride data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The createAgentOverride Business API includes a REST controller that can be triggered via the following route:

/v1/agentoverride

By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the Parameters section.

MCP Tool

REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This createAgentOverride Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The createAgentOverride Business API has 11 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client.

Business API parameters can be:

Regular Parameters

Name Type Required Default Location Data Path
sys_agentOverrideId ID No - body sys_agentOverrideId
Description: This id paremeter is used to create the data object with a given specific id. Leave null for automatic id.
agentName String Yes - body agentName
Description: Design-time agent name this override applies to.
provider String No - body provider
Description: Override AI provider (e.g., openai, anthropic).
model String No - body model
Description: Override model name.
systemPrompt Text No - body systemPrompt
Description: Override system prompt.
temperature Double No - body temperature
Description: Override temperature (0-2).
maxTokens Integer No - body maxTokens
Description: Override max tokens.
responseFormat String No - body responseFormat
Description: Override response format (text/json).
selectedTools Object No - body selectedTools
Description: Array of tool names from the catalog that this agent can use.
guardrails Object No - body guardrails
Description: Override guardrails: { maxToolCalls, timeout, maxTokenBudget }.
updatedBy ID No - session userId
Description: User who last updated this override.

Parameter Transformations

Some parameters are post-processed using transform scripts after being read from the request but before validation or workflow execution. Only parameters with a transform script are listed below.

No parameters are transformed in this API.

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the createAgentOverride Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Data Clause

Defines custom field-value assignments used to modify or augment the default payload for create and update operations. These settings override values derived from the session or parameters if explicitly provided.", Note that a default data clause is always prepared by Mindbricks using data property settings, however any property in the data clause can be override by Data Clause Settings.

Custom Data Clause Override No custom data clause override configured

Actual Data Clause

The business api will use the following data clause. Note that any calculated value will be added to the data clause in the api manager.

{
  id: this.sys_agentOverrideId,
  agentName: this.agentName,
  provider: this.provider,
  model: this.model,
  systemPrompt: this.systemPrompt,
  temperature: this.temperature,
  maxTokens: this.maxTokens,
  responseFormat: this.responseFormat,
  selectedTools: this.selectedTools ? (typeof this.selectedTools == 'string' ? JSON.parse(this.selectedTools) : this.selectedTools) : null,
  guardrails: this.guardrails ? (typeof this.guardrails == 'string' ? JSON.parse(this.guardrails) : this.guardrails) : null,
  updatedBy: this.updatedBy,
}

Business Logic Workflow

[1] Step : startBusinessApi

Manager initializes context, populates session and request objects, prepares internal structures for parameter handling and workflow execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Manager reads input parameters, normalizes missing values, applies default type casting, and stores them in the API context.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Manager transforms parameters, computes derived values, flattens or remaps arrays/objects, and adjusts formats for downstream processing.


[4] Step : checkParameters

Manager executes built-in validations: required field checks, type enforcement, and basic business rules. Prevents operation if validation fails.


[5] Step : checkBasicAuth

Manager performs authentication and authorization checks: verifies session, user roles, permissions, and tenant restrictions.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildDataClause

Manager constructs the final data object for creation, fills auto-generated fields (IDs, timestamps, owner fields), and ensures schema consistency.

You can use the following settings to change some behavior of this step. dataClause

[7] Step : mainCreateOperation

Manager executes the database insert operation, updates indexes/caches, and triggers internal post-processing like linked default records.


[8] Step : buildOutput

Manager shapes the response: masks sensitive fields, resolves linked references, and formats output according to API contract.


[9] Step : sendResponse

Manager sends the response to the client and finalizes internal tasks like flushing logs or updating session state.


[10] Step : raiseApiEvent

Manager triggers API-level events (Kafka, WebSocket, async workflows) as the final internal step.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The createAgentOverride api has got 9 regular client parameters

Parameter Type Required Population
agentName String true request.body?.[“agentName”]
provider String false request.body?.[“provider”]
model String false request.body?.[“model”]
systemPrompt Text false request.body?.[“systemPrompt”]
temperature Double false request.body?.[“temperature”]
maxTokens Integer false request.body?.[“maxTokens”]
responseFormat String false request.body?.[“responseFormat”]
selectedTools Object false request.body?.[“selectedTools”]
guardrails Object false request.body?.[“guardrails”]

REST Request

To access the api you can use the REST controller with the path POST /v1/agentoverride

  axios({
    method: 'POST',
    url: '/v1/agentoverride',
    data: {
            agentName:"String",  
            provider:"String",  
            model:"String",  
            systemPrompt:"Text",  
            temperature:"Double",  
            maxTokens:"Integer",  
            responseFormat:"String",  
            selectedTools:"Object",  
            guardrails:"Object",  
    
    },
    params: {
    
        }
  });

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the sys_agentOverride object in the respones. However, some properties may be omitted based on the object’s internal logic.

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_agentOverride",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"sys_agentOverride": {
		"id": "ID",
		"agentName": "String",
		"provider": "String",
		"model": "String",
		"systemPrompt": "Text",
		"temperature": "Double",
		"maxTokens": "Integer",
		"responseFormat": "String",
		"selectedTools": "Object",
		"guardrails": "Object",
		"enabled": "Boolean",
		"updatedBy": "ID",
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"isActive": true
	}
}

Business API Design Specification - Delete Agentoverride

Business API Design Specification - Delete Agentoverride

A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic.

While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized.

This document provides an in-depth explanation of the architectural design of the deleteAgentOverride Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side.

Main Data Object and CRUD Operation

The deleteAgentOverride Business API is designed to handle a delete operation on the Sys_agentOverride data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The deleteAgentOverride Business API includes a REST controller that can be triggered via the following route:

/v1/agentoverride/:sys_agentOverrideId

By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the Parameters section.

MCP Tool

REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This deleteAgentOverride Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The deleteAgentOverride Business API has 1 parameter that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client.

Business API parameters can be:

Regular Parameters

Name Type Required Default Location Data Path
sys_agentOverrideId ID Yes - urlpath sys_agentOverrideId
Description: This id paremeter is used to select the required data object that will be deleted

Parameter Transformations

Some parameters are post-processed using transform scripts after being read from the request but before validation or workflow execution. Only parameters with a transform script are listed below.

No parameters are transformed in this API.

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the deleteAgentOverride Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({id:this.sys_agentOverrideId}), {"path":"services[4].businessLogic[4].whereClause.fullWhereClause"})

Delete Options

Use these options to set delete specific settings.

useSoftDelete: If true, the record will be marked as deleted (isActive: false) instead of removed. The implementation depends on the data object’s soft delete configuration.

Business Logic Workflow

[1] Step : startBusinessApi

Manager initializes context, prepares request/session objects, and sets up internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Manager reads and normalizes parameters, applies defaults, and stores them in the context for downstream steps.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Manager executes parameter transform scripts, computes derived values, and remaps objects or arrays as needed for later processing.


[4] Step : checkParameters

Manager runs built-in validations including required field checks, type enforcement, and deletion preconditions. Stops execution if validation fails.


[5] Step : checkBasicAuth

Manager validates session, user roles, permissions, and tenant-specific access rules to enforce basic auth restrictions.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildWhereClause

Manager generates the query conditions, applies ownership and parent checks, and ensures the clause is correct for the delete operation.

You can use the following settings to change some behavior of this step. whereClause

[7] Step : fetchInstance

Manager fetches the target record, applies filters from WHERE clause, and writes the instance to the context for further checks.


[8] Step : checkInstance

Manager performs object-level validations such as lock status, soft-delete eligibility, and multi-step approval enforcement.


[9] Step : mainDeleteOperation

Manager executes the delete query, updates related indexes/caches, and handles soft/hard delete logic according to configuration.

You can use the following settings to change some behavior of this step. deleteOptions

[10] Step : buildOutput

Manager shapes the response payload, masks sensitive fields, and formats related cleanup results for output.


[11] Step : sendResponse

Manager delivers the response to the client and finalizes any temporary internal structures.


[12] Step : raiseApiEvent

Manager triggers asynchronous API events, notifies queues or streams, and performs final cleanup for the workflow.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The deleteAgentOverride api has got 1 regular client parameter

Parameter Type Required Population
sys_agentOverrideId ID true request.params?.[“sys_agentOverrideId”]

REST Request

To access the api you can use the REST controller with the path DELETE /v1/agentoverride/:sys_agentOverrideId

  axios({
    method: 'DELETE',
    url: `/v1/agentoverride/${sys_agentOverrideId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the sys_agentOverride object in the respones. However, some properties may be omitted based on the object’s internal logic.

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_agentOverride",
	"method": "DELETE",
	"action": "delete",
	"appVersion": "Version",
	"rowCount": 1,
	"sys_agentOverride": {
		"id": "ID",
		"agentName": "String",
		"provider": "String",
		"model": "String",
		"systemPrompt": "Text",
		"temperature": "Double",
		"maxTokens": "Integer",
		"responseFormat": "String",
		"selectedTools": "Object",
		"guardrails": "Object",
		"enabled": "Boolean",
		"updatedBy": "ID",
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"isActive": false
	}
}

Business API Design Specification - List Toolcatalog

Business API Design Specification - List Toolcatalog

A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic.

While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized.

This document provides an in-depth explanation of the architectural design of the listToolCatalog Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side.

Main Data Object and CRUD Operation

The listToolCatalog Business API is designed to handle a list operation on the Sys_toolCatalog data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The listToolCatalog Business API includes a REST controller that can be triggered via the following route:

/v1/toolcatalog

By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the Parameters section.

MCP Tool

REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This listToolCatalog Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The listToolCatalog Business API has 1 parameter that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client.

Business API parameters can be:

Filter Parameters

The listToolCatalog api supports 1 optional filter parameter for filtering list results using URL query parameters. These parameters are only available for list type APIs.

serviceName Filter

Type: String
Description: Source service name.
Location: Query Parameter

Usage:

Non-Array Property (Case-Insensitive Partial Matching):

Examples:

// Find records with "john" in the field (case-insensitive partial match)
GET /v1/toolcatalog?serviceName=john
// Matches: "John", "Johnny", "johnson", "McJohn", etc.

// Find records with multiple values (use multiple parameters)
GET /v1/toolcatalog?serviceName=laptop&serviceName=phone&serviceName=tablet
// Matches records containing "laptop", "phone", or "tablet" anywhere in the field

// Find records without this field
GET /v1/toolcatalog?serviceName=null

Parameter Transformations

Some parameters are post-processed using transform scripts after being read from the request but before validation or workflow execution. Only parameters with a transform script are listed below.

No parameters are transformed in this API.

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the listToolCatalog Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Select Clause

Specifies which fields will be selected from the main data object during a get or list operation. Leave blank to select all properties. This applies only to get and list type APIs.",

``

Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

null

List Options

Defines list-specific options including filtering logic, default sorting, and result customization for APIs that return multiple records.

List Sort By Sort order definitions for the result set. Multiple fields can be provided with direction (asc/desc).

Specific sort order is not configure, natural order (ascending id) will be used.

List Group By Grouping definitions for the result set. This is typically used for visual or report-based grouping.

The list is not grouped.

setAsRead: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed.

No setAsread field-value pair is configured.

Permission Filter Optional filter that applies permission constraints dynamically based on session or object roles. So that the list items are filtered by the user’s OBAC or ABAC permissions.

Permission filter is not active at the moment. Follow Mindbricks updates to be able to use it.

Pagination Options

Contains settings to configure pagination behavior for list APIs. Includes options like page size, offset, cursor support, and total count inclusion.

Business Logic Workflow

[1] Step : startBusinessApi

Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Reads request and Redis parameters, applies defaults, and writes them to context for downstream processing.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Transforms and normalizes parameters, derives dependent values, and reshapes inputs for the main list query.


[4] Step : checkParameters

Executes validation logic on required and custom parameters, enforcing business rules and cross-field consistency.


[5] Step : checkBasicAuth

Performs role-based access checks and applies dynamic membership or session-based restrictions.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildWhereClause

Constructs the main query WHERE clause and applies optional filters or scoped access controls.

You can use the following settings to change some behavior of this step. whereClause

[7] Step : mainListOperation

Executes the paginated database query, retrieves the list, and stores results in context for enrichment.

You can use the following settings to change some behavior of this step. selectClause, listOptions, paginationOptions

[8] Step : buildOutput

Assembles the list response, sanitizes sensitive fields, applies transformations, and injects extra context if needed.


[9] Step : sendResponse

Sends the paginated list to the client through the controller.


[10] Step : raiseApiEvent

Triggers optional post-workflow events, such as Kafka messages, logs, or system notifications.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The listToolCatalog api has 1 filter parameter available for filtering list results. See the Filter Parameters section above for detailed usage examples.

Filter Parameter Type Array Property Description
serviceName String No Source service name.

REST Request

To access the api you can use the REST controller with the path GET /v1/toolcatalog

  axios({
    method: 'GET',
    url: '/v1/toolcatalog',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section for usage examples)
        // serviceName: '<value>' // Filter by serviceName
            }
  });

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the sys_toolCatalogs object in the respones. However, some properties may be omitted based on the object’s internal logic.

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_toolCatalogs",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"sys_toolCatalogs": [
		{
			"id": "ID",
			"toolName": "String",
			"serviceName": "String",
			"description": "Text",
			"parameters": "Object",
			"lastRefreshed": "Date",
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID",
			"isActive": true
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Business API Design Specification - Get Toolcatalogentry

Business API Design Specification - Get Toolcatalogentry

A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic.

While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized.

This document provides an in-depth explanation of the architectural design of the getToolCatalogEntry Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side.

Main Data Object and CRUD Operation

The getToolCatalogEntry Business API is designed to handle a get operation on the Sys_toolCatalog data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The getToolCatalogEntry Business API includes a REST controller that can be triggered via the following route:

/v1/toolcatalogentry/:sys_toolCatalogId

By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the Parameters section.

MCP Tool

REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This getToolCatalogEntry Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The getToolCatalogEntry Business API has 1 parameter that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client.

Business API parameters can be:

Regular Parameters

Name Type Required Default Location Data Path
sys_toolCatalogId ID Yes - urlpath sys_toolCatalogId
Description: This id paremeter is used to query the required data object.

Parameter Transformations

Some parameters are post-processed using transform scripts after being read from the request but before validation or workflow execution. Only parameters with a transform script are listed below.

No parameters are transformed in this API.

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the getToolCatalogEntry Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Select Clause

Specifies which fields will be selected from the main data object during a get or list operation. Leave blank to select all properties. This applies only to get and list type APIs.",

``

Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({id:this.sys_toolCatalogId}), {"path":"services[4].businessLogic[6].whereClause.fullWhereClause"})

Get Options

Use these options to set get specific settings.

setAsRead: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed.

No setAsread field-value pair is configured.

Business Logic Workflow

[1] Step : startBusinessApi

Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Extracts parameters from request and Redis, applies defaults, and writes them to context.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Executes parameter transformation scripts, applies type coercion, merges derived values, and reshapes inputs for downstream milestones.


[4] Step : checkParameters

Validates required and custom parameters, enforcing business-specific rules and constraints.


[5] Step : checkBasicAuth

Performs login, role, and permission checks, and applies dynamic object-level access rules.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildWhereClause

Builds the WHERE clause for fetching the object and applies additional scoped filters if configured.

You can use the following settings to change some behavior of this step. whereClause

[7] Step : mainGetOperation

Executes the database fetch, retrieves the object, and stores it in context for enrichment or further checks.

You can use the following settings to change some behavior of this step. selectClause, getOptions

[8] Step : checkInstance

Performs instance-level validations, such as ownership, existence, or access conditions.


[9] Step : buildOutput

Assembles the response from the object, applies masking, formatting, and injects additional metadata if needed.


[10] Step : sendResponse

Delivers the response to the controller for client delivery.


[11] Step : raiseApiEvent

Triggers optional API-level events after workflow completion, sending messages to integrations like Kafka if configured.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The getToolCatalogEntry api has got 1 regular client parameter

Parameter Type Required Population
sys_toolCatalogId ID true request.params?.[“sys_toolCatalogId”]

REST Request

To access the api you can use the REST controller with the path GET /v1/toolcatalogentry/:sys_toolCatalogId

  axios({
    method: 'GET',
    url: `/v1/toolcatalogentry/${sys_toolCatalogId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the sys_toolCatalog object in the respones. However, some properties may be omitted based on the object’s internal logic.

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_toolCatalog",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"sys_toolCatalog": {
		"id": "ID",
		"toolName": "String",
		"serviceName": "String",
		"description": "Text",
		"parameters": "Object",
		"lastRefreshed": "Date",
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"isActive": true
	}
}

Business API Design Specification - List Agentexecutions

Business API Design Specification - List Agentexecutions

A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic.

While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized.

This document provides an in-depth explanation of the architectural design of the listAgentExecutions Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side.

Main Data Object and CRUD Operation

The listAgentExecutions Business API is designed to handle a list operation on the Sys_agentExecution data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The listAgentExecutions Business API includes a REST controller that can be triggered via the following route:

/v1/agentexecutions

By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the Parameters section.

MCP Tool

REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This listAgentExecutions Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The listAgentExecutions Business API has 5 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client.

Business API parameters can be:

Filter Parameters

The listAgentExecutions api supports 5 optional filter parameters for filtering list results using URL query parameters. These parameters are only available for list type APIs.

agentName Filter

Type: String
Description: Agent that was executed.
Location: Query Parameter

Usage:

Non-Array Property (Case-Insensitive Partial Matching):

Examples:

// Find records with "john" in the field (case-insensitive partial match)
GET /v1/agentexecutions?agentName=john
// Matches: "John", "Johnny", "johnson", "McJohn", etc.

// Find records with multiple values (use multiple parameters)
GET /v1/agentexecutions?agentName=laptop&agentName=phone&agentName=tablet
// Matches records containing "laptop", "phone", or "tablet" anywhere in the field

// Find records without this field
GET /v1/agentexecutions?agentName=null

agentType Filter

Type: Enum
Description: Whether this was a design-time or dynamic agent.
Location: Query Parameter

Usage:

Examples:

// Get records with specific enum value
GET /v1/agentexecutions?agentType=active

// Get records with multiple enum values (use multiple parameters)
GET /v1/agentexecutions?agentType=active&agentType=pending

// Get records without this field
GET /v1/agentexecutions?agentType=null

source Filter

Type: Enum
Description: How the agent was triggered.
Location: Query Parameter

Usage:

Examples:

// Get records with specific enum value
GET /v1/agentexecutions?source=active

// Get records with multiple enum values (use multiple parameters)
GET /v1/agentexecutions?source=active&source=pending

// Get records without this field
GET /v1/agentexecutions?source=null

userId Filter

Type: ID
Description: User who triggered the execution.
Location: Query Parameter

Usage:

Non-Array Property:

Examples:

// Get records with a specific ID
GET /v1/agentexecutions?userId=550e8400-e29b-41d4-a716-446655440000

// Get records with multiple IDs (use multiple parameters)
GET /v1/agentexecutions?userId=550e8400-e29b-41d4-a716-446655440000&userId=660e8400-e29b-41d4-a716-446655440001

// Get records without this field
GET /v1/agentexecutions?userId=null

status Filter

Type: Enum
Description: Execution status.
Location: Query Parameter

Usage:

Examples:

// Get records with specific enum value
GET /v1/agentexecutions?status=active

// Get records with multiple enum values (use multiple parameters)
GET /v1/agentexecutions?status=active&status=pending

// Get records without this field
GET /v1/agentexecutions?status=null

Parameter Transformations

Some parameters are post-processed using transform scripts after being read from the request but before validation or workflow execution. Only parameters with a transform script are listed below.

No parameters are transformed in this API.

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the listAgentExecutions Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Select Clause

Specifies which fields will be selected from the main data object during a get or list operation. Leave blank to select all properties. This applies only to get and list type APIs.",

``

Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

null

List Options

Defines list-specific options including filtering logic, default sorting, and result customization for APIs that return multiple records.

List Sort By Sort order definitions for the result set. Multiple fields can be provided with direction (asc/desc).

Specific sort order is not configure, natural order (ascending id) will be used.

List Group By Grouping definitions for the result set. This is typically used for visual or report-based grouping.

The list is not grouped.

setAsRead: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed.

No setAsread field-value pair is configured.

Permission Filter Optional filter that applies permission constraints dynamically based on session or object roles. So that the list items are filtered by the user’s OBAC or ABAC permissions.

Permission filter is not active at the moment. Follow Mindbricks updates to be able to use it.

Pagination Options

Contains settings to configure pagination behavior for list APIs. Includes options like page size, offset, cursor support, and total count inclusion.

Business Logic Workflow

[1] Step : startBusinessApi

Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Reads request and Redis parameters, applies defaults, and writes them to context for downstream processing.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Transforms and normalizes parameters, derives dependent values, and reshapes inputs for the main list query.


[4] Step : checkParameters

Executes validation logic on required and custom parameters, enforcing business rules and cross-field consistency.


[5] Step : checkBasicAuth

Performs role-based access checks and applies dynamic membership or session-based restrictions.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildWhereClause

Constructs the main query WHERE clause and applies optional filters or scoped access controls.

You can use the following settings to change some behavior of this step. whereClause

[7] Step : mainListOperation

Executes the paginated database query, retrieves the list, and stores results in context for enrichment.

You can use the following settings to change some behavior of this step. selectClause, listOptions, paginationOptions

[8] Step : buildOutput

Assembles the list response, sanitizes sensitive fields, applies transformations, and injects extra context if needed.


[9] Step : sendResponse

Sends the paginated list to the client through the controller.


[10] Step : raiseApiEvent

Triggers optional post-workflow events, such as Kafka messages, logs, or system notifications.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The listAgentExecutions api has 5 filter parameters available for filtering list results. See the Filter Parameters section above for detailed usage examples.

Filter Parameter Type Array Property Description
agentName String No Agent that was executed.
agentType Enum No Whether this was a design-time or dynamic agent.
source Enum No How the agent was triggered.
userId ID No User who triggered the execution.
status Enum No Execution status.

REST Request

To access the api you can use the REST controller with the path GET /v1/agentexecutions

  axios({
    method: 'GET',
    url: '/v1/agentexecutions',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section for usage examples)
        // agentName: '<value>' // Filter by agentName
        // agentType: '<value>' // Filter by agentType
        // source: '<value>' // Filter by source
        // userId: '<value>' // Filter by userId
        // status: '<value>' // Filter by status
            }
  });

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the sys_agentExecutions object in the respones. However, some properties may be omitted based on the object’s internal logic.

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_agentExecutions",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"sys_agentExecutions": [
		{
			"id": "ID",
			"agentName": "String",
			"agentType": "Enum",
			"agentType_idx": "Integer",
			"source": "Enum",
			"source_idx": "Integer",
			"userId": "ID",
			"input": "Object",
			"output": "Object",
			"toolCalls": "Integer",
			"tokenUsage": "Object",
			"durationMs": "Integer",
			"status": "Enum",
			"status_idx": "Integer",
			"error": "Text",
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID",
			"isActive": true
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Business API Design Specification - Get Agentexecution

Business API Design Specification - Get Agentexecution

A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic.

While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized.

This document provides an in-depth explanation of the architectural design of the getAgentExecution Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side.

Main Data Object and CRUD Operation

The getAgentExecution Business API is designed to handle a get operation on the Sys_agentExecution data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The getAgentExecution Business API includes a REST controller that can be triggered via the following route:

/v1/agentexecution/:sys_agentExecutionId

By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the Parameters section.

MCP Tool

REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This getAgentExecution Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The getAgentExecution Business API has 1 parameter that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client.

Business API parameters can be:

Regular Parameters

Name Type Required Default Location Data Path
sys_agentExecutionId ID Yes - urlpath sys_agentExecutionId
Description: This id paremeter is used to query the required data object.

Parameter Transformations

Some parameters are post-processed using transform scripts after being read from the request but before validation or workflow execution. Only parameters with a transform script are listed below.

No parameters are transformed in this API.

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the getAgentExecution Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Select Clause

Specifies which fields will be selected from the main data object during a get or list operation. Leave blank to select all properties. This applies only to get and list type APIs.",

``

Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({id:this.sys_agentExecutionId}), {"path":"services[4].businessLogic[8].whereClause.fullWhereClause"})

Get Options

Use these options to set get specific settings.

setAsRead: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed.

No setAsread field-value pair is configured.

Business Logic Workflow

[1] Step : startBusinessApi

Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Extracts parameters from request and Redis, applies defaults, and writes them to context.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Executes parameter transformation scripts, applies type coercion, merges derived values, and reshapes inputs for downstream milestones.


[4] Step : checkParameters

Validates required and custom parameters, enforcing business-specific rules and constraints.


[5] Step : checkBasicAuth

Performs login, role, and permission checks, and applies dynamic object-level access rules.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildWhereClause

Builds the WHERE clause for fetching the object and applies additional scoped filters if configured.

You can use the following settings to change some behavior of this step. whereClause

[7] Step : mainGetOperation

Executes the database fetch, retrieves the object, and stores it in context for enrichment or further checks.

You can use the following settings to change some behavior of this step. selectClause, getOptions

[8] Step : checkInstance

Performs instance-level validations, such as ownership, existence, or access conditions.


[9] Step : buildOutput

Assembles the response from the object, applies masking, formatting, and injects additional metadata if needed.


[10] Step : sendResponse

Delivers the response to the controller for client delivery.


[11] Step : raiseApiEvent

Triggers optional API-level events after workflow completion, sending messages to integrations like Kafka if configured.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The getAgentExecution api has got 1 regular client parameter

Parameter Type Required Population
sys_agentExecutionId ID true request.params?.[“sys_agentExecutionId”]

REST Request

To access the api you can use the REST controller with the path GET /v1/agentexecution/:sys_agentExecutionId

  axios({
    method: 'GET',
    url: `/v1/agentexecution/${sys_agentExecutionId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the sys_agentExecution object in the respones. However, some properties may be omitted based on the object’s internal logic.

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_agentExecution",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"sys_agentExecution": {
		"id": "ID",
		"agentName": "String",
		"agentType": "Enum",
		"agentType_idx": "Integer",
		"source": "Enum",
		"source_idx": "Integer",
		"userId": "ID",
		"input": "Object",
		"output": "Object",
		"toolCalls": "Integer",
		"tokenUsage": "Object",
		"durationMs": "Integer",
		"status": "Enum",
		"status_idx": "Integer",
		"error": "Text",
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"isActive": true
	}
}

Bff Service

Service Design Specification

Service Design Specification

BFF Service Documentation Version: 1.0.2


Scope

This document provides a comprehensive architectural overview of the BFF Service, a Backend-for-Frontend layer designed to unify access to backend ElasticSearch indices and event-driven aggregation logic. The service offers a full REST API suite and listens to Kafka topics to synchronize enriched views.

This document is intended for:

For endpoint-level specifications, refer to the REST API Guide. For listener-level behavior, refer to the Event API Guide.


Service Settings


API Routes Overview

The BFF service exposes a dynamic REST API interface that provides full access to ElasticSearch indices. These include list, count, filter, and schema-based interactions for both stored and virtual views.

For full documentation of REST routes, including supported methods and examples, refer to the REST API Guide.


Kafka Event Listeners

The BFF service listens to ElasticSearch-related Kafka topics to maintain enriched and denormalized indices. These listeners trigger view aggregation functions upon receiving create, update, or delete events for primary and related entities.

For detailed behavior, payloads, and listener-to-function mappings, refer to the Event Guide.


Aggregation Strategy

Each view is either:

For each stored view:

Final document is saved to: <project_codename>_<view.newIndexName>


Middleware

Error Handling

Request Validation

Async Wrapper


Elasticsearch Utilities


Cron Repair Logic

Runs periodically to ensure data integrity:


Environment Variables

Variable Description
HTTP_PORT Service port
KAFKA_BROKER Kafka broker host
ELASTIC_URL Elasticsearch base URL
CORS_ORIGIN Allowed frontend origin (optional)
NODE_ENV Environment (dev, prod)
SERVICE_URL Used for injected API face config
SERVICE_SHORT_NAME Used in injected auth URL

App Lifecycle

  1. Loads env: .env, .prod.env, etc.

  2. Bootstraps Express app with:

    • CORS setup
    • JSON + cookie parsers
    • Dynamic routes
    • Swagger and API Face
  3. Starts:

    • Kafka listeners
    • Cron repair jobs
    • Full enrichment pipelines
  4. Handles SIGINT to close server cleanly


Testing Strategy

Unit Tests

Integration Tests

Load Tests (Optional)



REST API GUIDE

REST API GUIDE

BFF SERVICE

Version: 1.0.2

BFF service is a microservice that acts as a bridge between the client and the backend services. It provides a unified API for the client to interact with multiple backend services, simplifying the communication process and improving performance.

Architectural Design Credit and Contact Information

The architectural design of this microservice is credited to.
For inquiries, feedback, or further information regarding the architecture, please direct your communication to:

Email:

We encourage open communication and welcome any questions or discussions related to the architectural aspects of this microservice.

Documentation Scope

Welcome to the official documentation for the BFF Service’s REST API. This document is designed to provide a comprehensive guide to interfacing with our BFF Service exclusively through RESTful API endpoints.

Intended Audience

This documentation is intended for developers and integrators who are looking to interact with the BFF Service via HTTP requests for purposes such as listing, filtering, and searching data.

Overview

Within these pages, you will find detailed information on how to effectively utilize the REST API, including authentication methods, request and response formats, endpoint descriptions, and examples of common use cases.

Beyond REST
It’s important to note that the BFF Service also supports alternative methods of interaction, such as gRPC and messaging via a Message Broker. These communication methods are beyond the scope of this document. For information regarding these protocols, please refer to their respective documentation.


Resources

Elastic Index Resource

Resource Definition: A virtual resource representing dynamic search data from a specified index.


Route: List Records

Route Definition: Returns a paginated list from the elastic index. Route Type: list
Default access route: POST /:indexName/list

Parameters

Parameter Type Required Population
indexName String Yes path.param
page Number No query.page
limit Number No query.limit
sortBy String No query.sortBy
sortOrder String No query.sortOrder
q String No query.q
filters Object Yes body
axios({
  method: "POST",
  url: `/${indexName}/list`,
  data: {
    filters: "Object"
  },
  params: {
    page: "Number",
    limit: "Number",
    sortBy: "String",
    sortOrder: "String",
    q: "String"
  }
});

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property.

---

Default access route: GET /:indexName/list

Parameters

Parameter Type Required Population
indexName String Yes path.param
page Number No query.page
limit Number No query.limit
sortBy String No query.sortBy
sortOrder String No query.sortOrder
q String No query.q
axios({
  method: "GET",
  url: `/${indexName}/list`,
  data:{},
  params: {
    page: "Number",
    limit: "Number",
    sortBy: "String",
    sortOrder: "String",
    q: "String"
  }
});

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a “status”: “OK” property.

Route: Count Records

Route Definition: Counts matching documents in the elastic index. Route Type: count
Default access route: POST /:indexName/count

Parameters

Parameter Type Required Population
indexName String Yes path.param
q String No query.q
filters Object Yes body
axios({
  method: "POST",
  url: `/${indexName}/count`,
  data: {
    filters: "Object"
  },
  params: {
    q: "String"
  }
});

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a “status”: “OK” property.


Default access route: GET /:indexName/count

Parameters

Parameter Type Required Population
indexName String Yes path.param
q String No query.q
axios({
  method: "GET",
  url: `/${indexName}/count`,
  data:{},
  params: {
    q: "String"
  }
});

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a “status”: “OK” property.

Route: Get Index Schema

Route Definition: Returns the schema for the elastic index. Route Type: get
Default access route: GET /:indexName/schema

Parameters

Parameter Type Required Population
indexName String Yes path.param
axios({
  method: "GET",
  url: `/${indexName}/schema`,
  data:{},
  params: {}
});

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a “status”: “OK” property.

Route: Filters

GET /:indexName/filters

Route Type: get

Parameters

Parameter Type Required Population
indexName String Yes path.param
page Number No query.page
limit Number No query.limit
axios({
  method: "GET",
  url: `/${indexName}/filters`,
  data:{},
  params: {
    page: "Number",
    limit: "Number"
  }
});

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a “status”: “OK” property.

POST /:indexName/filters

Route Type: create

Parameters

Parameter Type Required Population
indexName String Yes path.param
filters Object Yes body
axios({
  method: "POST",
  url: `/${indexName}/filters`,
  data: {
    filterName: "String",
    conditions: "Object"
  },
  params: {}
});

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a “status”: “OK” property.

DELETE /:indexName/filters/:filterId

Route Type: delete

Parameters

Parameter Type Required Population
indexName String Yes path.param
filterId String Yes path.param
axios({
  method: "DELETE",
  url: `/${indexName}/filters/${filterId}`,
  data:{},
  params: {}
});

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a “status”: “OK” property.

Route: Get One Record

Route Type: get
Default access route: GET /:indexName/:id

Parameters

Parameter Type Required Population
indexName String Yes path.param
id ID Yes path.param
axios({
  method: "GET",
  url: `/${indexName}/${id}`,
  data:{},
  params: {}

});

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a “status”: “OK” property.

Route: Get All Aggregated Records

Route Definition: Retrieves a full list of aggregated view data. Route Type: list Default access route: GET /projectDetailsView

Example:

axios({
  method: "GET",
  url: `/projectDetailsView`,
  data: {},
  params: {}
});

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a “status”: “OK” property.

Route: Get Single Aggregated Record

Route Definition: Retrieves a specific aggregated document by ID. Route Type: get Default access route: GET /projectDetailsView/:id

Parameters

Parameter Type Required Population
id ID Yes path.param
axios({
  method: "GET",
  url: `/projectDetailsView/${id}`,
  data: {},
  params: {}
});

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a “status”: “OK” property.

Route: Get All Aggregated Records

Route Definition: Retrieves a full list of aggregated view data. Route Type: list Default access route: GET /userProfileView

Example:

axios({
  method: "GET",
  url: `/userProfileView`,
  data: {},
  params: {}
});

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a “status”: “OK” property.

Route: Get Single Aggregated Record

Route Definition: Retrieves a specific aggregated document by ID. Route Type: get Default access route: GET /userProfileView/:id

Parameters

Parameter Type Required Population
id ID Yes path.param
axios({
  method: "GET",
  url: `/userProfileView/${id}`,
  data: {},
  params: {}
});

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a “status”: “OK” property.

Route: Get All Aggregated Records

Route Definition: Retrieves a full list of aggregated view data. Route Type: list Default access route: GET /messageThreadView

Example:

axios({
  method: "GET",
  url: `/messageThreadView`,
  data: {},
  params: {}
});

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a “status”: “OK” property.

Route: Get Single Aggregated Record

Route Definition: Retrieves a specific aggregated document by ID. Route Type: get Default access route: GET /messageThreadView/:id

Parameters

Parameter Type Required Population
id ID Yes path.param
axios({
  method: "GET",
  url: `/messageThreadView/${id}`,
  data: {},
  params: {}
});

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a “status”: “OK” property.

Route: Get All Aggregated Records

Route Definition: Retrieves a full list of aggregated view data. Route Type: list Default access route: GET /accessGrantNotificationView

Example:

axios({
  method: "GET",
  url: `/accessGrantNotificationView`,
  data: {},
  params: {}
});

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a “status”: “OK” property.

Route: Get Single Aggregated Record

Route Definition: Retrieves a specific aggregated document by ID. Route Type: get Default access route: GET /accessGrantNotificationView/:id

Parameters

Parameter Type Required Population
id ID Yes path.param
axios({
  method: "GET",
  url: `/accessGrantNotificationView/${id}`,
  data: {},
  params: {}
});

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a “status”: “OK” property.

Route: Get All Aggregated Records

Route Definition: Retrieves a full list of aggregated view data. Route Type: list Default access route: GET /approvalRequestNotificationView

Example:

axios({
  method: "GET",
  url: `/approvalRequestNotificationView`,
  data: {},
  params: {}
});

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a “status”: “OK” property.

Route: Get Single Aggregated Record

Route Definition: Retrieves a specific aggregated document by ID. Route Type: get Default access route: GET /approvalRequestNotificationView/:id

Parameters

Parameter Type Required Population
id ID Yes path.param
axios({
  method: "GET",
  url: `/approvalRequestNotificationView/${id}`,
  data: {},
  params: {}
});

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a “status”: “OK” property.

Route: Get All Aggregated Records

Route Definition: Retrieves a full list of aggregated view data. Route Type: list Default access route: GET /projectFeaturedNotificationView

Example:

axios({
  method: "GET",
  url: `/projectFeaturedNotificationView`,
  data: {},
  params: {}
});

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a “status”: “OK” property.

Route: Get Single Aggregated Record

Route Definition: Retrieves a specific aggregated document by ID. Route Type: get Default access route: GET /projectFeaturedNotificationView/:id

Parameters

Parameter Type Required Population
id ID Yes path.param
axios({
  method: "GET",
  url: `/projectFeaturedNotificationView/${id}`,
  data: {},
  params: {}
});

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a “status”: “OK” property.

Route: Get All Aggregated Records

Route Definition: Retrieves a full list of aggregated view data. Route Type: list Default access route: GET /userSuspensionNotificationView

Example:

axios({
  method: "GET",
  url: `/userSuspensionNotificationView`,
  data: {},
  params: {}
});

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a “status”: “OK” property.

Route: Get Single Aggregated Record

Route Definition: Retrieves a specific aggregated document by ID. Route Type: get Default access route: GET /userSuspensionNotificationView/:id

Parameters

Parameter Type Required Population
id ID Yes path.param
axios({
  method: "GET",
  url: `/userSuspensionNotificationView/${id}`,
  data: {},
  params: {}
});

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a “status”: “OK” property.

Route: Get All Aggregated Records

Route Definition: Retrieves a full list of aggregated view data. Route Type: list Default access route: GET /systemAnnouncementNotificationView

Example:

axios({
  method: "GET",
  url: `/systemAnnouncementNotificationView`,
  data: {},
  params: {}
});

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a “status”: “OK” property.

Route: Get Single Aggregated Record

Route Definition: Retrieves a specific aggregated document by ID. Route Type: get Default access route: GET /systemAnnouncementNotificationView/:id

Parameters

Parameter Type Required Population
id ID Yes path.param
axios({
  method: "GET",
  url: `/systemAnnouncementNotificationView/${id}`,
  data: {},
  params: {}
});

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a “status”: “OK” property.

Route: List Records

Route Definition: Returns a paginated list from the elastic index. Route Type: list
Default access route: POST /filmProjectListView/list

Parameters

Parameter Type Required Population
page Number No query.page
limit Number No query.limit
sortBy String No query.sortBy
sortOrder String No query.sortOrder
q String No query.q
filters Object Yes body
axios({
  method: "POST",
  url: `/filmProjectListView/list`,
  data: {
    filters: "Object"
  },
  params: {
    page: "Number",
    limit: "Number",
    sortBy: "String",
    sortOrder: "String",
    q: "String"
  }
});

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a “status”: “OK” property.

Default access route: GET /filmProjectListView/list

Parameters

Parameter Type Required Population
page Number No query.page
limit Number No query.limit
sortBy String No query.sortBy
sortOrder String No query.sortOrder
q String No query.q
axios({
  method: "GET",
  url: `/filmProjectListView/list`,
  data:{},
  params: {
    page: "Number",
    limit: "Number",
    sortBy: "String",
    sortOrder: "String",
    q: "String"
  }
});

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a “status”: “OK” property.

Route: Count Records

Route Definition: Counts matching documents in the elastic index. Route Type: count
Default access route: POST /filmProjectListView/count

Parameters

Parameter Type Required Population
q String No query.q
filters Object Yes body
axios({
  method: "POST",
  url: `/filmProjectListView/count`,
  data: {
    filters: "Object"
  },
  params: {
    q: "String"
  }
});

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a “status”: “OK” property.


Default access route: GET /filmProjectListView/count

Parameters

Parameter Type Required Population
q String No query.q
axios({
  method: "GET",
  url: `/filmProjectListView/count`,
  data:{},
  params: {
    q: "String"
  }
});

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a “status”: “OK” property.

Route: Get Index Schema

Route Definition: Returns the schema for the elastic index. Route Type: get Default access route: GET /filmProjectListView/schema

axios({
  method: "GET",
  url: `/filmProjectListView/schema`,
  data:{},
  params: {}
});

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a “status”: “OK” property.

Route: Filters

GET /filmProjectListView/filters

Route Type: get

Parameters

Parameter Type Required Population
page Number No query.page
limit Number No query.limit
axios({
  method: "GET",
  url: `/filmProjectListView/filters`,
  data:{},
  params: {
    page: "Number",
    limit: "Number"
  }
});

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a “status”: “OK” property.

POST /filmProjectListView/filters

Route Type: create

Parameters

Parameter Type Required Population
filters Object Yes body
axios({
  method: "POST",
  url: `/filmProjectListView/filters`,
  data: {
    "filters":"Object"
  },
  params: {}
});

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a “status”: “OK” property.

DELETE /filmProjectListView/filters/:filterId

Route Type: delete

Parameters

Parameter Type Required Population
filterId ID Yes path.param
axios({
  method: "DELETE",
  url: `/filmProjectListView/filters/${filterId}`,
  data:{},
  params: {}
});

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a “status”: “OK” property.

Route: Get One Record

Route Type: get Default access route: GET /filmProjectListView/:id

Parameters

Parameter Type Required Population
id ID Yes path.param
axios({
  method: "GET",
  url: `/filmProjectListView/${id}`,
  data:{},
  params: {}
});

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a “status”: “OK” property.



EVENT API GUIDE

EVENT API GUIDE

BFF SERVICE

The BFF service is a microservice that acts as a bridge between the client and backend services. It provides a unified API for the client to interact with multiple backend services, simplifying the communication process and improving performance.

Architectural Design Credit and Contact Information

The architectural design of this microservice is credited to.
For inquiries, feedback, or further information regarding the architecture, please direct your communication to:

Email:

We encourage open communication and welcome any questions or discussions related to the architectural aspects of this microservice.

Documentation Scope

Welcome to the official documentation for the BFF Service Event Listeners. This guide details the Kafka-based event listeners responsible for reacting to ElasticSearch index events. It describes listener responsibilities, the topics they subscribe to, and expected payloads.

Intended Audience
This documentation is intended for developers, architects, and system administrators involved in the design, implementation, and maintenance of the BFF Service. It assumes familiarity with microservices architecture, the Kafka messaging system, and ElasticSearch.

Overview
Each ElasticSearch index operation (create, update, delete) emits a corresponding event to Kafka. These events are consumed by listeners responsible for executing aggregate functions to ensure index- and system-level consistency.

Kafka Event Listeners

Kafka Event Listener: filmproject-created

Event Topic: elastic-index-auteurlabb_filmproject-created

When a filmproject is created in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the filmProjectListViewAggregateData function to enrich and store the final document in the related index.

Expected Payload:

{
  "id": "String"
}

Kafka Event Listener: filmproject-updated

Event Topic: elastic-index-auteurlabb_filmproject-updated

When a filmproject is updated in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the filmProjectListViewAggregateData function to update the enriched document in the related index.

Expected Payload:

{
  "id": "String"
}

Kafka Event Listener: filmproject-deleted

Event Topic: elastic-index-auteurlabb>_filmproject-deleted

When a filmproject is deleted in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the filmProjectListViewAggregateData function to handle removal or cleanup in the related index.

Expected Payload:

{
  "id": "String"
}

Kafka Event Listener: user-created

Event Topic: elastic-index-user-created

When a user is created in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the ownerReFilmProjectListView function to update dependent documents in the related index.

Expected Payload:

{
  "id": "String"
}

Kafka Event Listener: user-updated

Event Topic: elastic-index-auteurlabb>_user-updated

When a user is updated in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the ownerReFilmProjectListView function to re-enrich dependent data in the related index.

Expected Payload:

{
  "id": "String"
}

Kafka Event Listener: user-deleted

Event Topic: elastic-index-auteurlabb>_user-deleted

When a user is deleted from the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the ownerReFilmProjectListView function to handle dependent data cleanup or updates.

Expected Payload:

{
  "id": "String"
}

Kafka Event Listener: user-created

Event Topic: elastic-index-user-created

When a user is created in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the studioReFilmProjectListView function to update dependent documents in the related index.

Expected Payload:

{
  "id": "String"
}

Kafka Event Listener: user-updated

Event Topic: elastic-index-auteurlabb>_user-updated

When a user is updated in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the studioReFilmProjectListView function to re-enrich dependent data in the related index.

Expected Payload:

{
  "id": "String"
}

Kafka Event Listener: user-deleted

Event Topic: elastic-index-auteurlabb>_user-deleted

When a user is deleted from the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the studioReFilmProjectListView function to handle dependent data cleanup or updates.

Expected Payload:

{
  "id": "String"
}

Notification Service

Service Design Specification

Service Design Specification

Notification Service Documentation Version: 1.0.2


Scope

This document provides a comprehensive architectural overview of the Notification Service, which is responsible for sending multi-channel notifications via Email, SMS, and Push. The service supports both REST and gRPC interfaces and utilizes an event-driven architecture through Kafka.

This document is intended for:

For detailed REST interface, refer to the [REST API Guide]. For Kafka-based publishing and consumption flows, refer to the [Event API Guide].


Service Settings


Interfaces Overview

REST API

Exposes endpoints to:

For full list and parameters, refer to the REST API Guide.

gRPC API

Defined via notification.sender.proto:

Kafka Events

For event structure and consumption logic, refer to the Event API Guide.


Provider Architecture

Each channel (SMS, Email, Push) is pluggable using a provider pattern. Providers can be toggled via env vars.

Email Providers

Push Providers

SMS Providers

Each provider implements a common send(payload) method and logs delivery result.


Storage Mode

Notifications can be optionally stored in the PostgreSQL database if STORED_NOTICE=true and notificationBody.isStored=true.

Stored data includes:


Aggregation & Templating

Notification body and title can be:

Template rendering supports interpolation with metadata. Separate template files exist for:


Middleware

Error Handling

Validation

Utilities


Lifecycle & Boot Process

  1. Loads configuration from .env using dotenv

  2. Initializes:

    • Express HTTP Server
    • gRPC Server (if GRPC_ACTIVE=true)
    • Kafka listeners
    • Redis connection
    • PostgreSQL connection
  3. Injects OpenAPI/Swagger via api-face

  4. Registers REST routes and middleware

  5. Launches any scheduled cron jobs

  6. Handles graceful shutdown via SIGINT


Environment Variables

Variable Description
HTTP_PORT Express HTTP port (default: 3000)
GRPC_PORT gRPC server port (default: 50051)
SERVICE_URL Used to build auth redirect paths
SERVICE_SHORT_NAME Used for auth hostname substitution
PG_USER, PG_PASS PostgreSQL credentials
REDIS_HOST Redis connection string
STORED_NOTICE Whether to persist notifications
SENDGRID_API_KEY SendGrid API token
SMTP_USER/PASS/PORT SMTP credentials
TWILIO_*, NETGSM_* SMS provider credentials
ONESIGNAL_API_KEY OneSignal Push key

Testing Strategy

Unit Tests

Integration Tests

End-to-End (Optional)


Observability & Logging


REST API GUIDE

REST API GUIDE

NOTIFICATION SERVICE

Version: 1.0.2

The Notification service is a microservice that allows sending notifications through SMS, Email, and Push channels. Providers can be configured dynamically through the .env file.

Architectural Design Credit and Contact Information

The architectural design of this microservice is credited to.
For inquiries, feedback, or further information regarding the architecture, please direct your communication to:

Email:

We encourage open communication and welcome any questions or discussions related to the architectural aspects of this microservice.

Documentation Scope

Welcome to the official documentation for the Notification Service REST API. This document provides a comprehensive overview of the available endpoints, how they work, and how to use them efficiently.

Intended Audience
This documentation is intended for developers, architects, and system administrators involved in the design, implementation, and maintenance of the Notification Service. It assumes familiarity with microservices architecture and RESTful APIs.

Overview

Within these pages, you will find detailed information on how to effectively utilize the REST API, including authentication methods, request and response formats, endpoint descriptions, and examples of common use cases.

Beyond REST
It’s important to note that the Notification Service also supports alternative methods of interaction, such as messaging via a Kafka message broker. These communication methods are beyond the scope of this document. For information regarding these protocols, please refer to their respective documentation.


Routes

Route: Register Device

Route Definition: Registers a device for a user.
Route Type: create
Default access route: POST /devices/register

Parameters

Parameter Type Required Population
device Object Yes body
userId ID Yes req.userId
axios({
  method: "POST",
  url: `/devices/register`,
  data: {
    device:"Object"
  },
  params:{}
});

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. Any validation errors will return status code 400 with an error message.

Route: Unregister Device

Route Definition: Removes a registered device.
Route Type: delete
Default access route: DELETE /devices/unregister/:deviceId

Parameters

Parameter Type Required Population
deviceId ID Yes path.param
userId ID Yes req.userId
axios({
  method: "DELETE",
  url: `/devices/unregister/${deviceId}`,
  data:{},
  params:{}
});

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. Any validation errors will return status code 400 with an error message.

Route: Get Notifications

Route Definition: Retrieves a paginated list of notifications.
Route Type: get
Default access route: GET /notifications

Parameters

Parameter Type Required Population
page Number No query.page
limit Number No query.limit
sortBy String No query.sortBy
userId ID Yes req.userId
axios({
  method: "GET",
  url: `/notifications`,
  data:{},
  params: {
    page: "Number",
    limit: "Number",
    sortBy: "String"
  }
});

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. Any validation errors will return status code 400 with an error message.

Route: Send Notification

Route Definition: Sends a notification to specified recipients.
Route Type: create
Default access route: POST /notifications

Parameters

Parameter Type Required Population
notification Object Yes body
axios({
  method: "POST",
  url: `/notifications`,
  data: {
    notification:"Object"
  },
  params:{}
});

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. Any validation errors will return status code 400 with an error message.

Route: Mark Notifications as Seen

Route Definition: Marks selected notifications as seen.
Route Type: update
Default access route: POST /notifications/seen

Parameters

Parameter Type Required Population
notificationIds Array Yes body
userId ID Yes req.userId
axios({
  method: "POST",
  url: `/notifications/seen`,
  data: {
    notificationIds:"Object"
  },
  params:{}
});

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. Any validation errors will return status code 400 with an error message.



EVENT API GUIDE

EVENT API GUIDE

NOTIFICATION SERVICE

The Notification service is a microservice that allows sending notifications through SMS, Email, and Push channels. Providers can be configured dynamically through the .env file.

Architectural Design Credit and Contact Information

The architectural design of this microservice is credited to.
For inquiries, feedback, or further information regarding the architecture, please direct your communication to:

Email:

We encourage open communication and welcome any questions or discussions related to the architectural aspects of this microservice.

Documentation Scope

Welcome to the official documentation for the Notification Service Event Publishers and Listeners. This document provides a comprehensive overview of the event-driven architecture employed in the Notification Service, detailing the various events that are published and consumed within the system.

Intended Audience
This documentation is intended for developers, architects, and system administrators involved in the design, implementation, and maintenance of the Notification Service. It assumes familiarity with microservices architecture and the Kafka messaging system.

Overview
This document outlines the key components of the Notification Service’s event-driven architecture, including the events that are published and consumed, the Kafka topics used, and the expected payloads for each event. It serves as a reference guide for understanding how events flow through the system and how different components interact with each other.

Kafka Event Publishers

Kafka Event Publisher: sendEmailNotification

Event Topic: auteurlabb-notification-service-notification-email

When a notification is sent through the Email channel, this publisher is responsible for sending the notification to the Kafka topic auteurlabb-notification-service-notification-email. The payload of the event includes the necessary information for sending the email, such as recipient details, subject, and message body.

Kafka Event Publisher: sendPushNotification

Event Topic: auteurlabb-notification-service-notification-push

When a notification is sent through the Push channel, this publisher is responsible for sending the notification to the Kafka topic auteurlabb-notification-service-notification-push. The payload of the event includes the necessary information for sending the push notification, such as recipient details, title, and message body.

Kafka Event Publisher: sendSmsNotification

Event Topic: auteurlabb-notification-service-notification-sms`

When a notification is sent through the SMS channel, this publisher is responsible for sending the notification to the Kafka topic auteurlabb-notification-service-notification-sms. The payload of the event includes the necessary information for sending the SMS, such as recipient details and message body.

Kafka Event Listeners

Kafka Event Listener: runEmailSenderListener

Event Topic: auteurlabb-notification-service-notification-email

When a notification is sent through the Email channel, this listener is triggered. It consumes messages from the auteurlabb-notification-service-notification-email topic, parses the payload, and uses the dynamically configured email provider to send the notification.

Kafka Event Listener: runPushSenderListener

Event Topic: auteurlabb-notification-service-notification-push

When a notification is sent through the Push channel, this listener is triggered. It consumes messages from the auteurlabb-notification-service-notification-push topic, parses the payload, and uses the dynamically configured push provider to send the notification.

Kafka Event Listener: runSmsSenderListener

Event Topic: auteurlabb-notification-service-notification-sms

When a notification is sent through the SMS channel, this listener is triggered. It consumes messages from the auteurlabb-notification-service-notification-sms topic, parses the payload, and uses the dynamically configured SMS provider to send the notification.

Kafka Event Listener: runstudioApprovalStatusChangedListener

Event Topic: auteurlabb-moderationadmin-service-dbevent-approvalrequest-updated

When a notification is sent through the auteurlabb-moderationadmin-service-dbevent-approvalrequest-updated topic, this listener is triggered. It processes the message, extracts required metadata, and constructs a notification payload using a predefined template ([object Object]).

It supports condition-based filtering and optionally enriches the payload by retrieving data from ElasticSearch if the dataView source is used (approvalRequestNotificationView).

The notification is sent to the target(s) identified in the payload or in the retrieved data source using the Notification Service.

Kafka Event Listener: runinvestorApprovalStatusChangedListener

Event Topic: auteurlabb-moderationadmin-service-dbevent-approvalrequest-updated

When a notification is sent through the auteurlabb-moderationadmin-service-dbevent-approvalrequest-updated topic, this listener is triggered. It processes the message, extracts required metadata, and constructs a notification payload using a predefined template ([object Object]).

It supports condition-based filtering and optionally enriches the payload by retrieving data from ElasticSearch if the dataView source is used (approvalRequestNotificationView).

The notification is sent to the target(s) identified in the payload or in the retrieved data source using the Notification Service.

Kafka Event Listener: runprojectApprovalStatusChangedListener

Event Topic: auteurlabb-moderationadmin-service-dbevent-approvalrequest-updated

When a notification is sent through the auteurlabb-moderationadmin-service-dbevent-approvalrequest-updated topic, this listener is triggered. It processes the message, extracts required metadata, and constructs a notification payload using a predefined template ([object Object]).

It supports condition-based filtering and optionally enriches the payload by retrieving data from ElasticSearch if the dataView source is used (approvalRequestNotificationView).

The notification is sent to the target(s) identified in the payload or in the retrieved data source using the Notification Service.

Kafka Event Listener: runaccessRequestReceivedListener

Event Topic: auteurlabb-projectportfolio-service-dbevent-accessgrant-created

When a notification is sent through the auteurlabb-projectportfolio-service-dbevent-accessgrant-created topic, this listener is triggered. It processes the message, extracts required metadata, and constructs a notification payload using a predefined template ([object Object]).

It supports condition-based filtering and optionally enriches the payload by retrieving data from ElasticSearch if the dataView source is used (accessGrantNotificationView).

The notification is sent to the target(s) identified in the payload or in the retrieved data source using the Notification Service.

Kafka Event Listener: runaccessGrantedListener

Event Topic: auteurlabb-projectportfolio-service-dbevent-accessgrant-updated

When a notification is sent through the auteurlabb-projectportfolio-service-dbevent-accessgrant-updated topic, this listener is triggered. It processes the message, extracts required metadata, and constructs a notification payload using a predefined template ([object Object]).

It supports condition-based filtering and optionally enriches the payload by retrieving data from ElasticSearch if the dataView source is used (accessGrantNotificationView).

The notification is sent to the target(s) identified in the payload or in the retrieved data source using the Notification Service.

Kafka Event Listener: runnewMessageReceivedListener

Event Topic: auteurlabb-messagingcenter-service-dbevent-message-created

When a notification is sent through the auteurlabb-messagingcenter-service-dbevent-message-created topic, this listener is triggered. It processes the message, extracts required metadata, and constructs a notification payload using a predefined template ([object Object]).

It supports condition-based filtering and optionally enriches the payload by retrieving data from ElasticSearch if the dataView source is used (messageThreadView).

The notification is sent to the target(s) identified in the payload or in the retrieved data source using the Notification Service.

Kafka Event Listener: runprojectFeaturedListener

Event Topic: auteurlabb-projectportfolio-service-dbevent-filmproject-updated

When a notification is sent through the auteurlabb-projectportfolio-service-dbevent-filmproject-updated topic, this listener is triggered. It processes the message, extracts required metadata, and constructs a notification payload using a predefined template ([object Object]).

It supports condition-based filtering and optionally enriches the payload by retrieving data from ElasticSearch if the dataView source is used (projectFeaturedNotificationView).

The notification is sent to the target(s) identified in the payload or in the retrieved data source using the Notification Service.

Kafka Event Listener: runuserSuspensionStatusChangedListener

Event Topic: auteurlabb-moderationadmin-service-dbevent-suspensionrecord-updated

When a notification is sent through the auteurlabb-moderationadmin-service-dbevent-suspensionrecord-updated topic, this listener is triggered. It processes the message, extracts required metadata, and constructs a notification payload using a predefined template ([object Object]).

It supports condition-based filtering and optionally enriches the payload by retrieving data from ElasticSearch if the dataView source is used (userSuspensionNotificationView).

The notification is sent to the target(s) identified in the payload or in the retrieved data source using the Notification Service.

Kafka Event Listener: runsystemAnnouncementCreatedListener

Event Topic: auteurlabb-moderationadmin-service-dbevent-auditlog-created

When a notification is sent through the auteurlabb-moderationadmin-service-dbevent-auditlog-created topic, this listener is triggered. It processes the message, extracts required metadata, and constructs a notification payload using a predefined template ([object Object]).

It supports condition-based filtering and optionally enriches the payload by retrieving data from ElasticSearch if the dataView source is used (systemAnnouncementNotificationView).

The notification is sent to the target(s) identified in the payload or in the retrieved data source using the Notification Service.

Kafka Event Listener: runemailVerificationListener

Event Topic: auteurlabb-user-service-email-verification-start

When a notification is sent through the auteurlabb-user-service-email-verification-start topic, this listener is triggered. It processes the message, extracts required metadata, and constructs a notification payload using a predefined template ([object Object]).

It supports condition-based filtering and optionally enriches the payload by retrieving data from ElasticSearch if the dataView source is used (``).

The notification is sent to the target(s) identified in the payload or in the retrieved data source using the Notification Service.

Kafka Event Listener: runmobileVerificationListener

Event Topic: auteurlabb-user-service-mobile-verification-start

When a notification is sent through the auteurlabb-user-service-mobile-verification-start topic, this listener is triggered. It processes the message, extracts required metadata, and constructs a notification payload using a predefined template ([object Object]).

It supports condition-based filtering and optionally enriches the payload by retrieving data from ElasticSearch if the dataView source is used (``).

The notification is sent to the target(s) identified in the payload or in the retrieved data source using the Notification Service.

Kafka Event Listener: runpasswordResetByEmailListener

Event Topic: auteurlabb-user-service-password-reset-by-email-start

When a notification is sent through the auteurlabb-user-service-password-reset-by-email-start topic, this listener is triggered. It processes the message, extracts required metadata, and constructs a notification payload using a predefined template ([object Object]).

It supports condition-based filtering and optionally enriches the payload by retrieving data from ElasticSearch if the dataView source is used (``).

The notification is sent to the target(s) identified in the payload or in the retrieved data source using the Notification Service.

Kafka Event Listener: runpasswordResetByMobileListener

Event Topic: auteurlabb-user-service-password-reset-by-mobile-start

When a notification is sent through the auteurlabb-user-service-password-reset-by-mobile-start topic, this listener is triggered. It processes the message, extracts required metadata, and constructs a notification payload using a predefined template ([object Object]).

It supports condition-based filtering and optionally enriches the payload by retrieving data from ElasticSearch if the dataView source is used (``).

The notification is sent to the target(s) identified in the payload or in the retrieved data source using the Notification Service.

Kafka Event Listener: runemail2FactorListener

Event Topic: auteurlabb-user-service-email-2FA-start

When a notification is sent through the auteurlabb-user-service-email-2FA-start topic, this listener is triggered. It processes the message, extracts required metadata, and constructs a notification payload using a predefined template ([object Object]).

It supports condition-based filtering and optionally enriches the payload by retrieving data from ElasticSearch if the dataView source is used (``).

The notification is sent to the target(s) identified in the payload or in the retrieved data source using the Notification Service.

Kafka Event Listener: runmobile2FactorListener

Event Topic: auteurlabb-user-service-mobile-2FA-start

When a notification is sent through the auteurlabb-user-service-mobile-2FA-start topic, this listener is triggered. It processes the message, extracts required metadata, and constructs a notification payload using a predefined template ([object Object]).

It supports condition-based filtering and optionally enriches the payload by retrieving data from ElasticSearch if the dataView source is used (``).

The notification is sent to the target(s) identified in the payload or in the retrieved data source using the Notification Service.


LLM Documents


Generated by Mindbricks Genesis Engine