Sahibinden Clone – Classifieds & Marketplace Platform - Complete Documentation

clonesahibinden is a scalable classified ads platform where users can register, list items across multiple categories such as vehicles, real estate, goods, and jobs, interact via messaging, and manage their listings with support for premium ad features and role-based moderation. The platform offers advanced category management, powerful search and filtering, and a comprehensive admin and moderation dashboard.

This document contains the full documentation for all services in the Sahibinden Clone – Classifieds & Marketplace Platform project. It is designed for comprehensive reference by both humans and AI agents.


Table of Contents

Getting Started

Frontend Prompts

AdminModeration Service

CategoryLocation Service

Conversation Service

Favorite Service

Listing Service

ListingImage Service

Payment Service

Auth Service

Bff Service

Notification Service

LLM Documents


Getting Started

Sahibinden Clone – Classifieds & Marketplace Platform

Sahibinden Clone – Classifieds & Marketplace Platform

Version : 1.0.13

clonesahibinden is a scalable classified ads platform where users can register, list items across multiple categories such as vehicles, real estate, goods, and jobs, interact via messaging, and manage their listings with support for premium ad features and role-based moderation. The platform offers advanced category management, powerful search and filtering, and a comprehensive admin and moderation dashboard.

How to Use Project Documents

The Clonesahibinden 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://clonesahibinden.prw.mindbricks.com/auth-api
Staging https://clonesahibinden-stage.mindbricks.co/auth-api
Production https://clonesahibinden.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 Clonesahibinden 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 Sahibinden Clone – Classifieds & Marketplace 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

adminModeration Service

Description: Admin and moderation service for logging, approval/denial, banning, role/config management, and audit actions. Orchestrates administrative and moderation business APIs, ensures every critical action is logged for traceability, and enables moderator/admin workflows.

Documentation:

Base URL Examples:

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

categoryLocation Service

Description: Manages the category and location hierarchies for listings. Provides CRUD with uniqueness enforcement, navigation endpoints for category/location trees, and supports efficient public browsing with heavy read optimization.

Documentation:

Base URL Examples:

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

conversation Service

Description: Manages user-to-user messaging threads tied to listings, with message storage, read/unread and moderation support.

Documentation:

Base URL Examples:

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

favorite Service

Description: Handles all user favorites for classified listings, including add/remove, listing user-specific collections, and providing favorited status for listings. Prevents duplicate favorites and maintains favorite counts on listings for optimal UX. Cascade-cleans favorites if user or listing is deleted.

Documentation:

Base URL Examples:

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

listing Service

Description: Manages classified listings, their lifecycle, premium features, status transitions, and provides filtering/search for marketplace ads. Integrates with users, categories, locations, and Stripe for premium ad upgrades. Enforces ad and user type business logic.

Documentation:

Base URL Examples:

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

listingImage Service

Description: Manages uploading, linking, ordering, and storing all images attached to classified listings. Enforces image file format, size, count, and metadata standards; supports multi-resolution handling and per-listing image count limits.

Documentation:

Base URL Examples:

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

payment Service

Description: Handles Stripe payment flow for one-time premium upgrades on classified listings. Creates and tracks payment transactions, manages Stripe Checkout session and webhooks, and notifies the listing service to update premium status. Exposes payment history endpoints for users and reconciliation for admin.

Documentation:

Base URL Examples:

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

Conclusion

This documentation set provides a comprehensive guide for understanding and consuming the Sahibinden Clone – Classifieds & Marketplace 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

Authentication Management

CLONESAHIBINDEN

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

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

This first document includes general information about the project and its authentication management. Please read it carefully and implement all requirements described here.

The project has 1 auth service, 1 notification service, 1 BFF service, and 7 business services, plus other helper services such as bucket and realtime. In this document you will be informed only about the auth service. The initial frontend will be generated to use this 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.

Project Introduction

clonesahibinden is a scalable classified ads platform where users can register, list items across multiple categories such as vehicles, real estate, goods, and jobs, interact via messaging, and manage their listings with support for premium ad features and role-based moderation. The platform offers advanced category management, powerful search and filtering, and a comprehensive admin and moderation dashboard.

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, the service base URL will be given in the service sections.

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 pages) 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.

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 shpuld 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 addtion 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.

Registration Management

User Registration

User registration is public in the application, ensure that the register and login pages include a deployment server selection option so that you can set the base URL for all services. Start with a home page and set up the registration , verification, and login flow.

Using the registeruser route of the auth API, send the required fields from your registration page. Please create a simple and polished registration page that includes only the necessary fields of the registration API.

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 6 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”]
mobile String false request.body?.[“mobile”]
userType Enum false request.body?.[“userType”]
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.
mobile : The mobile number defined by the the user that is being registered.
userType : Indicates whether the user is an individual or a corporate account.

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",  
            mobile:"String",  
            userType:"Enum",  
    
    },
    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",
		"mobile": "String",
		"mobileVerified": "Boolean",
		"emailVerified": "Boolean",
		"userType": "Enum",
		"userType_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 teh 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

After successful registration and completing any required verifications, the user can log in. Please create a minimal, polished login page where the user can enter email and password. 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 productiondeployment 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", {
  username: "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...."
}

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 first step, please ensure you have not made the following common mistakes:

  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, in this propmpt all auth apis should be called by /auth-api prefix after application’s base url.
  3. The /currentuser API returns a mix of session and user data. There is no id property —use userId and sessionId.
  4. Please note that, the deployemnt environment selector will only be used in the home page. If any page is called directly bypassign home page, the page will use the stored or default environment.

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


Verification Management

CLONESAHIBINDEN

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

This document is a part of a REST API guide for the clonesahibinden 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 7 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

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 pssword
{
  "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
}

** 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

CLONESAHIBINDEN

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

This document is a part of a REST API guide for the clonesahibinden 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, and also in this document the bucket service will be introduced to manage the avatar.

The project has 1 auth service, 1 notification service, 1 BFF service, and 7 business services, plus other helper services such as bucket and realtime. In this document you will use the auth service and bucket 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 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.

Bucket Management

This application has a bucket service used to store user files and other object-related files. The bucket service is login-agnostic, so for write operations or private reads, include a bucket token (provided by services) in the request’s Authorization header as a Bearer token.

Please note that all other business services require the access token in the Bearer header, while the bucket service expects a bucket token because it is login-agnostic. Ensure you manage the required token injection properly; any auth interceptor should not replace the bucket token with the access token.

To access the bucket service in each environement use the bucket service api urls below:

User Bucket This bucket stores public user files for each user.

When a user logs in—or in the /currentuser response—there is a userBucketToken to use when sending user-related public files to the bucket service.

{
  //...
  "userBucketToken": "e56d...."
}

To upload a file

POST {bucketServiceUrl}/upload

The request body is form-data which includes the bucketId and the file binary in the files field.

{
    bucketId: "{userId}-public-user-bucket",
    files: {binary}
}

Response status is 200 on success, e.g., body:

{
    "success": true,
    "data": [
        {
            "fileId": "9da03f6d-0409-41ad-bb06-225a244ae408",
            "originalName": "test (10).png",
            "mimeType": "image/png",
            "size": 604063,
            "status": "uploaded",
            "bucketName": "f7103b85-fcda-4dec-92c6-c336f71fd3a2-public-user-bucket",
            "isPublic": true,
            "downloadUrl": "https://babilcom.mindbricks.co/bucket/download/9da03f6d-0409-41ad-bb06-225a244ae408"
        }
    ]
}

To download a file from the bucket, you need its fileId. If you upload an avatar or other asset, ensure the download URL or the fileId is stored in the backend.

Buckets are mostly used in object creations that require an additional file, such as a product image or user avatar. After uploading your image to the bucket, insert the returned download URL into the related property of the target object record.

Application Bucket

This Clonesahibinden application also includes a common public bucket that anyone can read, but only users with the superAdmin, admin, or saasAdmin roles can write (upload) to it.

When a user with one of these admin roles is logged in, the /login response or the /currentuser response also returns an applicationBucketToken field, which is used when uploading any file to the application bucket.

{
  //...
  "applicationBucketToken": "e23fd...."
}

The common public application bucket ID is

"clonesahibinden-public-common-bucket"

In certain admin areas—such as product management pages—since the user already has the application bucket token, they will be able to upload related object images.

Please configure your UI to upload files to the application bucket using this bucket token whenever needed.

Object Buckets Some objects may also return a bucket token for uploading or accessing files related to that object. For example, in a project management application, when you fetch a project’s data, a public or private bucket token may be provided to upload or download project-related files.

These buckets will be used as described in the relevant object definitions.

Profile Page

Design a profile page to manage (view and edit) user information. The profile page should also be able to upload the user avatar to the user’s public bucket. For bucket information, see the Bucket Management section above.

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.

The avatar upload component should include an image-cropping component with zoom and pan capabilities. The frontend will send the image to the bucket after it is scaled and cropped.

Do not implement your own cropping component; instead, use the library component react-easy-crop by installing 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",
		"mobile": "String",
		"mobileVerified": "Boolean",
		"emailVerified": "Boolean",
		"userType": "Enum",
		"userType_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 5 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”]
mobile String false request.body?.[“mobile”]
userType Enum false request.body?.[“userType”]
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
mobile : A string value to represent the user’s mobile number.
userType : Indicates whether the user is an individual or a corporate account.

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",  
            mobile:"String",  
            userType:"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",
		"mobile": "String",
		"mobileVerified": "Boolean",
		"emailVerified": "Boolean",
		"userType": "Enum",
		"userType_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",
		"mobile": "String",
		"mobileVerified": "Boolean",
		"emailVerified": "Boolean",
		"userType": "Enum",
		"userType_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",
		"mobile": "String",
		"mobileVerified": "Boolean",
		"emailVerified": "Boolean",
		"userType": "Enum",
		"userType_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. The auth API and bucket API are different services, and both URLs should be set according to the selected environment (production, staging, preview).
  2. Note that any api call to the application backend is based on a service base url, in this propmpt all auth apis should be called by /auth-api prefix after application’s base url, and bucket apis should be called by /bucket prefix after base url.
  3. The auth API and bucket API use different tokens. The auth API requires the accessToken in the Bearer header; the bucket API requires bucket-specific tokens such as userBucketToken or other application-specific bucket tokens. You may need two separate Axios clients: one for auth (always using the access token) and one for bucket operations (using the relevant bucket token).
  4. 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.
  5. 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

CLONESAHIBINDEN

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

This document is the 2nd part of a REST API guide for the clonesahibinden 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 clonesahibinden 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: moderator

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

{
  "superAdmin": "'superAdmin'",
  "admin": "'admin'",
  "user": "'user'",
  "moderator": "'moderator'"
}

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 4 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.

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

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
        // mobile: '<value>' // Filter by mobile
            }
  });

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",
			"mobile": "String",
			"mobileVerified": "Boolean",
			"emailVerified": "Boolean",
			"userType": "Enum",
			"userType_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 and 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 2 optional filter parameters for filtering list results:

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

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

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
        // mobile: '<value>' // Filter by mobile
            }
  });

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",
			"mobile": "String",
			"mobileVerified": "Boolean",
			"emailVerified": "Boolean",
			"userType": "Enum",
			"userType_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

Creatng 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 (or mobileVerified if exists) 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 6 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”]
mobile String false request.body?.[“mobile”]
userType Enum false request.body?.[“userType”]
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
mobile : A string value to represent the user’s mobile number.
userType : Indicates whether the user is an individual or a corporate account.

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",  
            mobile:"String",  
            userType:"Enum",  
    
    },
    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",
		"mobile": "String",
		"mobileVerified": "Boolean",
		"emailVerified": "Boolean",
		"userType": "Enum",
		"userType_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Avatar Upload

Normally when user registers by his own, the avatar is uploaded to the logged in user’s public bucket, however in this user admin panel, if any avatar upload is needed, it should be uploaded to the application public bucket. To access this application bucket, the applicationBucketToken should be used in the bearer header, and the bucketId in the payload should be given as "clonesahibinden-public-common-bucket" .

Before the avatar upload, a specific componenet from react-easy-crop lib should be used for zoom, pan and crop. This component also requested in the PART 1 prompt for profile page, so ensure taht you reuse the previous code if exists.

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 5 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”]
mobile String false request.body?.[“mobile”]
userType Enum false request.body?.[“userType”]
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
mobile : A string value to represent the user’s mobile number.
userType : Indicates whether the user is an individual or a corporate account.

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",  
            mobile:"String",  
            userType:"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",
		"mobile": "String",
		"mobileVerified": "Boolean",
		"emailVerified": "Boolean",
		"userType": "Enum",
		"userType_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",
		"mobile": "String",
		"mobileVerified": "Boolean",
		"emailVerified": "Boolean",
		"userType": "Enum",
		"userType_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",
		"mobile": "String",
		"mobileVerified": "Boolean",
		"emailVerified": "Boolean",
		"userType": "Enum",
		"userType_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",
		"mobile": "String",
		"mobileVerified": "Boolean",
		"emailVerified": "Boolean",
		"userType": "Enum",
		"userType_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 and email.

Bucket Management

(This information is also given in PART 1 prompt.)

This application has a bucket service used to store user files and other object-related files. The bucket service is login-agnostic, so for write operations or private reads, include a bucket token (provided by services) in the request’s Authorization header as a Bearer token.

Please note that all other business services require the access token in the Bearer header, while the bucket service expects a bucket token because it is login-agnostic. Ensure you manage the required token injection properly; any auth interceptor should not replace the bucket token with the access token.

User Bucket This bucket stores public user files for each user.

When a user logs in—or in the /currentuser response—there is a userBucketToken to use when sending user-related public files to the bucket service.

{
  //...
  "userBucketToken": "e56d...."
}

To upload a file

POST {baseUrl}/bucket/upload

The request body is form-data which includes the bucketId and the file binary in the files field.

{
    bucketId: "{userId}-public-user-bucket",
    files: {binary}
}

Response status is 200 on success, e.g., body:

{
    "success": true,
    "data": [
        {
            "fileId": "9da03f6d-0409-41ad-bb06-225a244ae408",
            "originalName": "test (10).png",
            "mimeType": "image/png",
            "size": 604063,
            "status": "uploaded",
            "bucketName": "f7103b85-fcda-4dec-92c6-c336f71fd3a2-public-user-bucket",
            "isPublic": true,
            "downloadUrl": "https://babilcom.mindbricks.co/bucket/download/9da03f6d-0409-41ad-bb06-225a244ae408"
        }
    ]
}

To download a file from the bucket, you need its fileId. If you upload an avatar or other asset, ensure the download URL or the fileId is stored in the backend.

Buckets are mostly used in object creations that require an additional file, such as a product image or user avatar. After uploading your image to the bucket, insert the returned download URL into the related property of the target object record.

Application Bucket

This Clonesahibinden application also includes a common public bucket that anyone can read, but only users with the superAdmin, admin, or saasAdmin roles can write (upload) to it.

When a user with one of these admin roles is logged in, the /login response or the /currentuser response also returns an applicationBucketToken field, which is used when uploading any file to the application bucket.

{
  //...
  "applicationBucketToken": "e23fd...."
}

The common public application bucket ID is

"clonesahibinden-public-common-bucket"

In certain admin areas—such as product management pages—since the user already has the application bucket token, they will be able to upload related object images.

Please configure your UI to upload files to the application bucket using this bucket token whenever needed.

Object Buckets Some objects may also return a bucket token for uploading or accessing files related to that object. For example, in a project management application, when you fetch a project’s data, a public or private bucket token may be provided to upload or download project-related files.

These buckets will be used as described in the relevant object definitions.

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

CLONESAHIBINDEN

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

This document is a part of a REST API guide for the clonesahibinden 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 Clonesahibinden 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. This is the recommended approach for chat UIs as it provides immediate feedback.

const response = await fetch(`${mcpBffUrl}/api/chat/stream`, {
  method: 'POST',
  headers,
  body: JSON.stringify({
    message: "Create a new product called Widget",
    conversationId: conversationId,
  }),
});

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

while (true) {
  const { done, value } = await reader.read();
  if (done) break;
  
  const chunk = decoder.decode(value, { stream: true });
  const lines = chunk.split('\n');
  
  for (const line of lines) {
    if (line.startsWith('event: ')) {
      const eventType = line.slice(7).trim();
      // Handle event type
    }
    if (line.startsWith('data: ')) {
      const data = JSON.parse(line.slice(6));
      // Handle event data
    }
  }
}

SSE Event Types

The streaming endpoint emits the following event types:

Event Description Data
start Stream started { conversationId }
text AI text chunk { text: "partial response..." }
tool_start AI is calling a tool { toolName, toolArgs }
tool_executing Tool is being executed { toolName }
tool_result Tool execution completed { toolName, result }check for __frontendAction
error Error occurred { error: "message" }
done Stream completed { conversationId, fullResponse }

Handling __frontendAction in Tool Results

When the AI calls certain tools (e.g., payment, secret reveal), the tool result may contain a __frontendAction object. This signals the frontend to render a special UI component instead of displaying raw tool output.

// In your SSE handler for 'tool_result' events:
function handleToolResult(data) {
  const action = extractFrontendAction(data.result);
  if (action) {
    // Render ActionCard component with this action
    renderActionCard(action);
  } else {
    // Display raw tool result as JSON or formatted text
    displayToolResult(data);
  }
}

// Extract __frontendAction from various response formats
function extractFrontendAction(result) {
  if (!result) return null;
  if (result.__frontendAction) return result.__frontendAction;
  
  // Unwrap MCP wrapper format
  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": "fetchListOrder",
    "routePath": "/v1/_fetchlistorder",
    "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 clonesahibinden_).

const indices = await fetch(`${mcpBffUrl}/api/elastic/allIndices`, { headers });
// ["clonesahibinden_products", "clonesahibinden_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 clonesahibinden_ 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
adminModeration Admin and moderation service for logging, approval/denial, banning, role/config management, and audit actions. Orchestrates administrative and moderation business APIs, ensures every critical action is logged for traceability, and enables moderator/admin workflows.
categoryLocation Manages the category and location hierarchies for listings. Provides CRUD with uniqueness enforcement, navigation endpoints for category/location trees, and supports efficient public browsing with heavy read optimization.
conversation Manages user-to-user messaging threads tied to listings, with message storage, read/unread and moderation support.
favorite Handles all user favorites for classified listings, including add/remove, listing user-specific collections, and providing favorited status for listings. Prevents duplicate favorites and maintains favorite counts on listings for optimal UX. Cascade-cleans favorites if user or listing is deleted.
listing Manages classified listings, their lifecycle, premium features, status transitions, and provides filtering/search for marketplace ads. Integrates with users, categories, locations, and Stripe for premium ad upgrades. Enforces ad and user type business logic.
listingImage Manages uploading, linking, ordering, and storing all images attached to classified listings. Enforces image file format, size, count, and metadata standards; supports multi-resolution handling and per-listing image count limits.
payment Handles Stripe payment flow for one-time premium upgrades on classified listings. Creates and tracks payment transactions, manages Stripe Checkout session and webhooks, and notifies the listing service to update premium status. Exposes payment history endpoints for users and reconciliation for admin.

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.


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


AdminModeration Service

CLONESAHIBINDEN

FRONTEND GUIDE FOR AI CODING AGENTS - PART 6 - AdminModeration Service

This document is a part of a REST API guide for the clonesahibinden 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 adminModeration

Service Access

AdminModeration service management is handled through service specific base urls.

AdminModeration 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 adminModeration service, the base URLs are:

Scope

AdminModeration Service Description

Admin and moderation service for logging, approval/denial, banning, role/config management, and audit actions. Orchestrates administrative and moderation business APIs, ensures every critical action is logged for traceability, and enables moderator/admin workflows.

AdminModeration service provides apis and business logic for following data objects in clonesahibinden 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.

adminActionLog Data Object: Records every moderation/admin action: who, what, target, reason, metadata, and timestamp. Used for full audit compliance and enables appeals, overrides, and reporting. Immutable except for soft delete.

AdminModeration Service Frontend Description By The Backend Architect

This service exposes moderation/admin workflows (approve/deny/ban/role assign/etc.), drives all admin UI and logs, and provides full audit trail for compliance/appeal. All actions must be routed through APIs here for UI management. For each operation, expect immediate confirmation or actionable error feedback. Admin/facilitator/frontends can use listAdminActionLogs for reporting, filters by action/target/date/admin. Logs are immutable; update/delete not supported. Dashboard metrics/status endpoints can be routed here or via BFF as 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"
}

Bucket Management

(This information is also given in PART 1 prompt.)

This application has a bucket service used to store user files and other object-related files. The bucket service is login-agnostic, so for write operations or private reads, include a bucket token (provided by services) in the request’s Authorization header as a Bearer token.

Please note that all other business services require the access token in the Bearer header, while the bucket service expects a bucket token because it is login-agnostic. Ensure you manage the required token injection properly; any auth interceptor should not replace the bucket token with the access token.

User Bucket This bucket stores public user files for each user.

When a user logs in—or in the /currentuser response—there is a userBucketToken to use when sending user-related public files to the bucket service.

{
  //...
  "userBucketToken": "e56d...."
}

To upload a file

POST {baseUrl}/bucket/upload

The request body is form-data which includes the bucketId and the file binary in the files field.

{
    bucketId: "{userId}-public-user-bucket",
    files: {binary}
}

Response status is 200 on success, e.g., body:

{
    "success": true,
    "data": [
        {
            "fileId": "9da03f6d-0409-41ad-bb06-225a244ae408",
            "originalName": "test (10).png",
            "mimeType": "image/png",
            "size": 604063,
            "status": "uploaded",
            "bucketName": "f7103b85-fcda-4dec-92c6-c336f71fd3a2-public-user-bucket",
            "isPublic": true,
            "downloadUrl": "https://babilcom.mindbricks.co/bucket/download/9da03f6d-0409-41ad-bb06-225a244ae408"
        }
    ]
}

To download a file from the bucket, you need its fileId. If you upload an avatar or other asset, ensure the download URL or the fileId is stored in the backend.

Buckets are mostly used in object creations that require an additional file, such as a product image or user avatar. After uploading your image to the bucket, insert the returned download URL into the related property of the target object record.

Application Bucket

This Clonesahibinden application also includes a common public bucket that anyone can read, but only users with the superAdmin, admin, or saasAdmin roles can write (upload) to it.

When a user with one of these admin roles is logged in, the /login response or the /currentuser response also returns an applicationBucketToken field, which is used when uploading any file to the application bucket.

{
  //...
  "applicationBucketToken": "e23fd...."
}

The common public application bucket ID is

"clonesahibinden-public-common-bucket"

In certain admin areas—such as product management pages—since the user already has the application bucket token, they will be able to upload related object images.

Please configure your UI to upload files to the application bucket using this bucket token whenever needed.

Object Buckets Some objects may also return a bucket token for uploading or accessing files related to that object. For example, in a project management application, when you fetch a project’s data, a public or private bucket token may be provided to upload or download project-related files.

These buckets will be used as described in the relevant object definitions.

AdminActionLog Data Object

Records every moderation/admin action: who, what, target, reason, metadata, and timestamp. Used for full audit compliance and enables appeals, overrides, and reporting. Immutable except for soft delete.

AdminActionLog Data Object Frontend Description By The Backend Architect

An immutable log entry. Used for compliance, audit trail, admin dashboards. Not directly editable or deletable; only created by system/admin APIs. Each entry shows moderator/admin, action, affected entity, timestamp, reason, and expanded details in metadata for complex events.

AdminActionLog Data Object Properties

AdminActionLog 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
action String false Yes No Action performed (e.g., approveListing, denyListing, banUser, assignRole, etc.)
actionAt Date false Yes No Date and time the action was performed, UTC.
adminUserId ID false Yes No User ID of admin/moderator who initiated the action (refers to auth:user).
metadata Object false No No Extended details/JSON object with details relevant to the action (previous/new values, related entities, etc.)
reason String false No No Reason for action (required on denial, ban; optional for others).
targetId ID false Yes No ID of the affected resource/entity (listing, user, message, etc.)
targetType String false Yes No Kind of entity affected by the action (e.g., listing, user, conversationMessage, roleAssignment, category, etc.)

Relation Properties

adminUserId

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

Filter Properties

action actionAt adminUserId targetId targetType

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.

AdminActionLog Default APIs

Operation API Name Route Explicitly Set
Create createAdminActionLog /v1/adminactionlogs Auto
Update none - Auto
Delete none - Auto
Get getAdminActionLog /v1/adminactionlogs/:adminActionLogId Auto
List listAdminActionLogs /v1/adminactionlogs System

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 Adminactionlog API

Appends a new immutable moderation/admin audit log entry for every critical action (listing, user, message, role, etc). Used both by internal workflows and explicit admin APIs.

API Frontend Description By The Backend Architect

Frontends should not invoke directly; log entries are created automatically via moderation/admin actions (approve/deny/ban/etc). Accepts adminUserId (from session), action, targetType, targetId, reason (required on denial/ban), metadata (optional), actionAt (server time, auto).

Rest Route

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

/v1/adminactionlogs

Rest Request Parameters

The createAdminActionLog api has got 5 regular request parameters

Parameter Type Required Population
action String true request.body?.[“action”]
metadata Object false request.body?.[“metadata”]
reason String false request.body?.[“reason”]
targetId ID true request.body?.[“targetId”]
targetType String true request.body?.[“targetType”]
action : Action performed (e.g., approveListing, denyListing, banUser, assignRole, etc.)
metadata : Extended details/JSON object with details relevant to the action (previous/new values, related entities, etc.)
reason : Reason for action (required on denial, ban; optional for others).
targetId : ID of the affected resource/entity (listing, user, message, etc.)
targetType : Kind of entity affected by the action (e.g., listing, user, conversationMessage, roleAssignment, category, etc.)

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

  axios({
    method: 'POST',
    url: '/v1/adminactionlogs',
    data: {
            action:"String",  
            metadata:"Object",  
            reason:"String",  
            targetId:"ID",  
            targetType:"String",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "adminActionLog",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"adminActionLog": {
		"id": "ID",
		"action": "String",
		"actionAt": "Date",
		"adminUserId": "ID",
		"metadata": "Object",
		"reason": "String",
		"targetId": "ID",
		"targetType": "String",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Get Adminactionlog API

Retrieve a single moderation/admin action log entry by ID. Used for detailed audit review or appeals.

API Frontend Description By The Backend Architect

Admin/staff frontend can use to show full details of an individual moderation event for investigation, override, or dispute resolution. Only available to admin/moderator roles.

Rest Route

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

/v1/adminactionlogs/:adminActionLogId

Rest Request Parameters

The getAdminActionLog api has got 1 regular request parameter

Parameter Type Required Population
adminActionLogId ID true request.params?.[“adminActionLogId”]
adminActionLogId : 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/adminactionlogs/:adminActionLogId

  axios({
    method: 'GET',
    url: `/v1/adminactionlogs/${adminActionLogId}`,
    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": "adminActionLog",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"adminActionLog": {
		"adminUser": {
			"email": "String",
			"fullname": "String",
			"roleId": "String"
		},
		"isActive": true
	}
}

List Adminactionlogs API

List all moderation/admin action logs with full filter/sort for dashboard or traceability/audit needs. Supports filtering by action, targetType, targetId, adminUserId, actionAt.

API Frontend Description By The Backend Architect

Feeds moderation dashboard. Supports filtering/searching by action (approve, deny, ban, etc), affected entity, targetId, admin/mod, time range. Pagination enabled for large result sets. Intended for admin/mod use only.

Rest Route

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

/v1/adminactionlogs

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

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

  axios({
    method: 'GET',
    url: '/v1/adminactionlogs',
    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": "adminActionLogs",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"adminActionLogs": [
		{
			"adminUser": [
				{
					"email": "String",
					"fullname": "String",
					"roleId": "String"
				},
				{},
				{}
			],
			"isActive": true
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

_fetch Listadminactionlog API

System API to fetch list of adminActionLog records for frontend application. Auto-generated, not visible in design.

Rest Route

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

/v1/_fetchlistadminactionlog

Rest Request Parameters

Filter Parameters

The _fetchListAdminActionLog api supports 5 optional filter parameters for filtering list results:

action (String): Action performed (e.g., approveListing, denyListing, banUser, assignRole, etc.)

actionAt (Date): Date and time the action was performed, UTC.

adminUserId (ID): User ID of admin/moderator who initiated the action (refers to auth:user).

targetId (ID): ID of the affected resource/entity (listing, user, message, etc.)

targetType (String): Kind of entity affected by the action (e.g., listing, user, conversationMessage, roleAssignment, category, etc.)

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

  axios({
    method: 'GET',
    url: '/v1/_fetchlistadminactionlog',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section above)
        // action: '<value>' // Filter by action
        // actionAt: '<value>' // Filter by actionAt
        // adminUserId: '<value>' // Filter by adminUserId
        // targetId: '<value>' // Filter by targetId
        // targetType: '<value>' // Filter by targetType
            }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "adminActionLogs",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"adminActionLogs": [
		{
			"id": "ID",
			"action": "String",
			"actionAt": "Date",
			"adminUserId": "ID",
			"metadata": "Object",
			"reason": "String",
			"targetId": "ID",
			"targetType": "String",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID",
			"adminUser": [
				{
					"fullname": "String"
				},
				{},
				{}
			]
		},
		{},
		{}
	],
	"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.


CategoryLocation Service

CLONESAHIBINDEN

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

This document is a part of a REST API guide for the clonesahibinden 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 categoryLocation

Service Access

CategoryLocation service management is handled through service specific base urls.

CategoryLocation 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 categoryLocation service, the base URLs are:

Scope

CategoryLocation Service Description

Manages the category and location hierarchies for listings. Provides CRUD with uniqueness enforcement, navigation endpoints for category/location trees, and supports efficient public browsing with heavy read optimization.

CategoryLocation service provides apis and business logic for following data objects in clonesahibinden 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.

category Data Object: Represents a listing category; supports up to three levels of nesting for hierarchical browsing and filtering. Self-referencing parent-child relationship. Slug is unique for public URL routing. Sort order is unique within parent for ordered display.

location Data Object: Represents a hierarchical location of country/city/district for listings. Used for filtering/search/location field on all listings.

CategoryLocation Service Frontend Description By The Backend Architect

AI Prompt: The backend provides hierarchical listing/category/location endpoints for navigation, filtering, and selection. When rendering category or location selectors, provide the nested structure plus a count of descendant listings/categories for fast navigation. Editing/deletion endpoints are admin-only. When referencing categories/locations elsewhere (e.g., listing editor), use these APIs for search/dropdown population. All slugs are unique for SEO-friendly URLs.

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"
}

Bucket Management

(This information is also given in PART 1 prompt.)

This application has a bucket service used to store user files and other object-related files. The bucket service is login-agnostic, so for write operations or private reads, include a bucket token (provided by services) in the request’s Authorization header as a Bearer token.

Please note that all other business services require the access token in the Bearer header, while the bucket service expects a bucket token because it is login-agnostic. Ensure you manage the required token injection properly; any auth interceptor should not replace the bucket token with the access token.

User Bucket This bucket stores public user files for each user.

When a user logs in—or in the /currentuser response—there is a userBucketToken to use when sending user-related public files to the bucket service.

{
  //...
  "userBucketToken": "e56d...."
}

To upload a file

POST {baseUrl}/bucket/upload

The request body is form-data which includes the bucketId and the file binary in the files field.

{
    bucketId: "{userId}-public-user-bucket",
    files: {binary}
}

Response status is 200 on success, e.g., body:

{
    "success": true,
    "data": [
        {
            "fileId": "9da03f6d-0409-41ad-bb06-225a244ae408",
            "originalName": "test (10).png",
            "mimeType": "image/png",
            "size": 604063,
            "status": "uploaded",
            "bucketName": "f7103b85-fcda-4dec-92c6-c336f71fd3a2-public-user-bucket",
            "isPublic": true,
            "downloadUrl": "https://babilcom.mindbricks.co/bucket/download/9da03f6d-0409-41ad-bb06-225a244ae408"
        }
    ]
}

To download a file from the bucket, you need its fileId. If you upload an avatar or other asset, ensure the download URL or the fileId is stored in the backend.

Buckets are mostly used in object creations that require an additional file, such as a product image or user avatar. After uploading your image to the bucket, insert the returned download URL into the related property of the target object record.

Application Bucket

This Clonesahibinden application also includes a common public bucket that anyone can read, but only users with the superAdmin, admin, or saasAdmin roles can write (upload) to it.

When a user with one of these admin roles is logged in, the /login response or the /currentuser response also returns an applicationBucketToken field, which is used when uploading any file to the application bucket.

{
  //...
  "applicationBucketToken": "e23fd...."
}

The common public application bucket ID is

"clonesahibinden-public-common-bucket"

In certain admin areas—such as product management pages—since the user already has the application bucket token, they will be able to upload related object images.

Please configure your UI to upload files to the application bucket using this bucket token whenever needed.

Object Buckets Some objects may also return a bucket token for uploading or accessing files related to that object. For example, in a project management application, when you fetch a project’s data, a public or private bucket token may be provided to upload or download project-related files.

These buckets will be used as described in the relevant object definitions.

Category Data Object

Represents a listing category; supports up to three levels of nesting for hierarchical browsing and filtering. Self-referencing parent-child relationship. Slug is unique for public URL routing. Sort order is unique within parent for ordered display.

Category Data Object Frontend Description By The Backend Architect

AI Prompt: When rendering category selectors (dropdowns, trees) or category navigation lists, fetch via listCategories. Use sortOrder for display ordering. Show child count for expandable parents. Use slug field for SEO-friendly category URLs. Admins can create, edit, disable (isActive=false), or delete categories; most users view only. Parent selection enforced on create/update. Cannot create loops.

Category Data Object Properties

Category 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
description Text false No No Optional extended description for category (for admin display or frontend info).
icon String false No No Icon identifier (string or URL to a static asset) for this category.
name String false Yes No Category name, e.g. ‘Automobiles’, ‘Electronics’.
parentCategoryId ID false No No References parent category for hierarchy. Top-level (root) categories have null.
slug String false Yes No SEO-friendly unique slug for URL and search. Lowercase, hyphens only.
sortOrder Integer false Yes No Order for listing within siblings. Unique per parent.

Relation Properties

parentCategoryId

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: No

Filter Properties

name parentCategoryId slug

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.

Location Data Object

Represents a hierarchical location of country/city/district for listings. Used for filtering/search/location field on all listings.

Location Data Object Frontend Description By The Backend Architect

AI Prompt: Use listLocations to fetch hierarchical selectable location objects for search and listing creation forms. Filter in the frontend by country/city/district. Display latitude/longitude on map if needed. Admins can add, edit, delete or disable (isActive=false) locations. Public users may only browse.

Location Data Object Properties

Location 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
city String false Yes No City name.
country String false Yes No Country name (typically ‘Turkey’).
district String false Yes No District name, for fine-grained search.
latitude Double false No No Latitude for map/search.
longitude Double false No No Longitude for map/search.
postalCode String false No No Postal code for location.

Filter Properties

city country district

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.

Category Default APIs

Operation API Name Route Explicitly Set
Create createCategory /v1/categories Auto
Update updateCategory /v1/categories/:categoryId Auto
Delete deleteCategory /v1/categories/:categoryId Auto
Get getCategory /v1/categories/:categoryId Auto
List listCategories /v1/categories System

Location Default APIs

Operation API Name Route Explicitly Set
Create createLocation /v1/locations Auto
Update updateLocation /v1/locations/:locationId Auto
Delete deleteLocation /v1/locations/:locationId Auto
Get getLocation /v1/locations/:locationId Auto
List listLocations /v1/locations System

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 Category API

Creates a new category. Slug must be globally unique. Only admin may create categories.

API Frontend Description By The Backend Architect

Only admins can create categories. The slug field must be unique and URL-friendly. Parent selection (for nesting) is validated. Use for admin consoles and bulk management.

Rest Route

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

/v1/categories

Rest Request Parameters

The createCategory api has got 6 regular request parameters

Parameter Type Required Population
description Text false request.body?.[“description”]
icon String false request.body?.[“icon”]
name String true request.body?.[“name”]
parentCategoryId ID false request.body?.[“parentCategoryId”]
slug String true request.body?.[“slug”]
sortOrder Integer true request.body?.[“sortOrder”]
description : Optional extended description for category (for admin display or frontend info).
icon : Icon identifier (string or URL to a static asset) for this category.
name : Category name, e.g. ‘Automobiles’, ‘Electronics’.
parentCategoryId : References parent category for hierarchy. Top-level (root) categories have null.
slug : SEO-friendly unique slug for URL and search. Lowercase, hyphens only.
sortOrder : Order for listing within siblings. Unique per parent.

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

  axios({
    method: 'POST',
    url: '/v1/categories',
    data: {
            description:"Text",  
            icon:"String",  
            name:"String",  
            parentCategoryId:"ID",  
            slug:"String",  
            sortOrder:"Integer",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "category",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"category": {
		"id": "ID",
		"description": "Text",
		"icon": "String",
		"name": "String",
		"parentCategoryId": "ID",
		"slug": "String",
		"sortOrder": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Create Location API

Create a new location entry (country, city, district). Only admin allowed. Composite uniqueness enforced.

API Frontend Description By The Backend Architect

For admin use only. Location uniqueness validated on (country, city, district). For multi-level selectors, call this repeatedly to populate country/city/district lists.

Rest Route

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

/v1/locations

Rest Request Parameters

The createLocation api has got 6 regular request parameters

Parameter Type Required Population
city String true request.body?.[“city”]
country String true request.body?.[“country”]
district String true request.body?.[“district”]
latitude Double false request.body?.[“latitude”]
longitude Double false request.body?.[“longitude”]
postalCode String false request.body?.[“postalCode”]
city : City name.
country : Country name (typically ‘Turkey’).
district : District name, for fine-grained search.
latitude : Latitude for map/search.
longitude : Longitude for map/search.
postalCode : Postal code for location.

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

  axios({
    method: 'POST',
    url: '/v1/locations',
    data: {
            city:"String",  
            country:"String",  
            district:"String",  
            latitude:"Double",  
            longitude:"Double",  
            postalCode:"String",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "location",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"location": {
		"id": "ID",
		"city": "String",
		"country": "String",
		"district": "String",
		"latitude": "Double",
		"longitude": "Double",
		"postalCode": "String",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Delete Category API

Deletes a category by id (soft delete). Only admin allowed.

API Frontend Description By The Backend Architect

Admin-only. Deleting a parent category sets parentCategoryId to null on children. Category is soft-deleted for restoration if needed.

Rest Route

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

/v1/categories/:categoryId

Rest Request Parameters

The deleteCategory api has got 1 regular request parameter

Parameter Type Required Population
categoryId ID true request.params?.[“categoryId”]
categoryId : 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/categories/:categoryId

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

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "category",
	"method": "DELETE",
	"action": "delete",
	"appVersion": "Version",
	"rowCount": 1,
	"category": {
		"id": "ID",
		"description": "Text",
		"icon": "String",
		"name": "String",
		"parentCategoryId": "ID",
		"slug": "String",
		"sortOrder": "Integer",
		"isActive": false,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Delete Location API

Soft-delete a location for admin-only. Used for removing obsolete/corrected locations.

API Frontend Description By The Backend Architect

Admin-only. Set isActive=false to remove location from public selectors. If referenced elsewhere, deletion may be blocked until listings/categories updated.

Rest Route

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

/v1/locations/:locationId

Rest Request Parameters

The deleteLocation api has got 1 regular request parameter

Parameter Type Required Population
locationId ID true request.params?.[“locationId”]
locationId : 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/locations/:locationId

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

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "location",
	"method": "DELETE",
	"action": "delete",
	"appVersion": "Version",
	"rowCount": 1,
	"location": {
		"id": "ID",
		"city": "String",
		"country": "String",
		"district": "String",
		"latitude": "Double",
		"longitude": "Double",
		"postalCode": "String",
		"isActive": false,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Get Category API

Fetch a single category by id. Publicly accessible.

API Frontend Description By The Backend Architect

Get category details for a given id. Enrich response with child category count and parent info for navigation trees. Used for editing/viewing category details.

Rest Route

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

/v1/categories/:categoryId

Rest Request Parameters

The getCategory api has got 1 regular request parameter

Parameter Type Required Population
categoryId ID true request.params?.[“categoryId”]
categoryId : 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/categories/:categoryId

  axios({
    method: 'GET',
    url: `/v1/categories/${categoryId}`,
    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": "category",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"category": {
		"parentCategory": {
			"name": "String",
			"slug": "String"
		},
		"childCategories": {
			"name": "String",
			"slug": "String",
			"isActive": true
		},
		"isActive": true
	}
}

Get Location API

Get details of a location by id. Publicly accessible for search/forms. Used by listing creation editors, etc.

API Frontend Description By The Backend Architect

Fetch all fields for display or editing/location picker. Admins use for management forms; public users for navigation/filter search.

Rest Route

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

/v1/locations/:locationId

Rest Request Parameters

The getLocation api has got 1 regular request parameter

Parameter Type Required Population
locationId ID true request.params?.[“locationId”]
locationId : 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/locations/:locationId

  axios({
    method: 'GET',
    url: `/v1/locations/${locationId}`,
    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": "location",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"location": {
		"isActive": true
	}
}

List Categories API

Returns all categories (optionally filtered by parentCategoryId or isActive). Used for category trees, navigation, and dropdowns. Public.

API Frontend Description By The Backend Architect

Use this endpoint for building category selection/search trees, sidebars, or dropdowns. Accepts parentCategoryId as a filter for fetching children. Returns all data for public display. Pagination not enabled (few hundred at most). Children included via join. Optionally returns count of active children for expandable UI.

Rest Route

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

/v1/categories

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

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

  axios({
    method: 'GET',
    url: '/v1/categories',
    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": "categories",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"categories": [
		{
			"childCategories": [
				{
					"name": "String",
					"slug": "String",
					"isActive": true
				},
				{},
				{}
			],
			"activeChildCount": [
				null,
				null,
				null
			],
			"isActive": true
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

List Locations API

List all locations (optionally filter by country/city/district). Used for populating selectors and browsing. Public. No pagination (few thousand max).

API Frontend Description By The Backend Architect

Request all locations or optionally filter by country/city/district for cascading selectors. Public use for forms, admin for management. If needed, can expand to support location grouping/child-count in future.

Rest Route

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

/v1/locations

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

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

  axios({
    method: 'GET',
    url: '/v1/locations',
    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": "locations",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"locations": [
		{
			"isActive": true
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Update Category API

Update an existing category. Only admin allowed. Slug uniqueness enforced.

API Frontend Description By The Backend Architect

Admins can update any field of a category including parent/child relationships. Changing parentCategoryId triggers structure update. Slug must remain unique.

Rest Route

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

/v1/categories/:categoryId

Rest Request Parameters

The updateCategory api has got 7 regular request parameters

Parameter Type Required Population
categoryId ID true request.params?.[“categoryId”]
description Text false request.body?.[“description”]
icon String false request.body?.[“icon”]
name String false request.body?.[“name”]
parentCategoryId ID false request.body?.[“parentCategoryId”]
slug String false request.body?.[“slug”]
sortOrder Integer false request.body?.[“sortOrder”]
categoryId : This id paremeter is used to select the required data object that will be updated
description : Optional extended description for category (for admin display or frontend info).
icon : Icon identifier (string or URL to a static asset) for this category.
name : Category name, e.g. ‘Automobiles’, ‘Electronics’.
parentCategoryId : References parent category for hierarchy. Top-level (root) categories have null.
slug : SEO-friendly unique slug for URL and search. Lowercase, hyphens only.
sortOrder : Order for listing within siblings. Unique per parent.

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

  axios({
    method: 'PATCH',
    url: `/v1/categories/${categoryId}`,
    data: {
            description:"Text",  
            icon:"String",  
            name:"String",  
            parentCategoryId:"ID",  
            slug:"String",  
            sortOrder:"Integer",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "category",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"category": {
		"id": "ID",
		"description": "Text",
		"icon": "String",
		"name": "String",
		"parentCategoryId": "ID",
		"slug": "String",
		"sortOrder": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Update Location API

Update existing location entry. Only admin allowed. Composite key must remain unique.

API Frontend Description By The Backend Architect

Admin-only. Location string fields (country, city, district) must not create a duplicate. Use for typo correction or boundary updates; minimal public usage.

Rest Route

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

/v1/locations/:locationId

Rest Request Parameters

The updateLocation api has got 7 regular request parameters

Parameter Type Required Population
locationId ID true request.params?.[“locationId”]
city String false request.body?.[“city”]
country String false request.body?.[“country”]
district String false request.body?.[“district”]
latitude Double false request.body?.[“latitude”]
longitude Double false request.body?.[“longitude”]
postalCode String false request.body?.[“postalCode”]
locationId : This id paremeter is used to select the required data object that will be updated
city : City name.
country : Country name (typically ‘Turkey’).
district : District name, for fine-grained search.
latitude : Latitude for map/search.
longitude : Longitude for map/search.
postalCode : Postal code for location.

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

  axios({
    method: 'PATCH',
    url: `/v1/locations/${locationId}`,
    data: {
            city:"String",  
            country:"String",  
            district:"String",  
            latitude:"Double",  
            longitude:"Double",  
            postalCode:"String",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "location",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"location": {
		"id": "ID",
		"city": "String",
		"country": "String",
		"district": "String",
		"latitude": "Double",
		"longitude": "Double",
		"postalCode": "String",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

_fetch Listcategory API

System API to fetch list of category records for frontend application. Auto-generated, not visible in design.

Rest Route

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

/v1/_fetchlistcategory

Rest Request Parameters

Filter Parameters

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

name (String): Category name, e.g. ‘Automobiles’, ‘Electronics’.

parentCategoryId (ID): References parent category for hierarchy. Top-level (root) categories have null.

slug (String): SEO-friendly unique slug for URL and search. Lowercase, hyphens only.

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

  axios({
    method: 'GET',
    url: '/v1/_fetchlistcategory',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section above)
        // name: '<value>' // Filter by name
        // parentCategoryId: '<value>' // Filter by parentCategoryId
        // slug: '<value>' // Filter by slug
            }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "categories",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"categories": [
		{
			"id": "ID",
			"description": "Text",
			"icon": "String",
			"name": "String",
			"parentCategoryId": "ID",
			"slug": "String",
			"sortOrder": "Integer",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID",
			"parent": [
				{
					"description": "Text",
					"icon": "String",
					"name": "String",
					"parentCategoryId": "ID",
					"slug": "String",
					"sortOrder": "Integer"
				},
				{},
				{}
			]
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

_fetch Listlocation API

System API to fetch list of location records for frontend application. Auto-generated, not visible in design.

Rest Route

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

/v1/_fetchlistlocation

Rest Request Parameters

Filter Parameters

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

city (String): City name.

country (String): Country name (typically ‘Turkey’).

district (String): District name, for fine-grained search.

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

  axios({
    method: 'GET',
    url: '/v1/_fetchlistlocation',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section above)
        // city: '<value>' // Filter by city
        // country: '<value>' // Filter by country
        // district: '<value>' // Filter by district
            }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "locations",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"locations": [
		{
			"id": "ID",
			"city": "String",
			"country": "String",
			"district": "String",
			"latitude": "Double",
			"longitude": "Double",
			"postalCode": "String",
			"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.


Conversation Service

CLONESAHIBINDEN

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

This document is a part of a REST API guide for the clonesahibinden 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 conversation

Service Access

Conversation service management is handled through service specific base urls.

Conversation 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 conversation service, the base URLs are:

Scope

Conversation Service Description

Manages user-to-user messaging threads tied to listings, with message storage, read/unread and moderation support.

Conversation service provides apis and business logic for following data objects in clonesahibinden 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.

conversationMessage Data Object: A single message sent between two users within a conversation about a listing. Tracks sender, receiver, timestamps and read status.

conversationThread Data Object: Private messaging thread between two users regarding a specific listing. Unique per (listing, user pair), order-invariant. Tracks last message time for inbox sorting.

Conversation Service Frontend Description By The Backend Architect

Conversation Microservice UX Guidance

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"
}

Bucket Management

(This information is also given in PART 1 prompt.)

This application has a bucket service used to store user files and other object-related files. The bucket service is login-agnostic, so for write operations or private reads, include a bucket token (provided by services) in the request’s Authorization header as a Bearer token.

Please note that all other business services require the access token in the Bearer header, while the bucket service expects a bucket token because it is login-agnostic. Ensure you manage the required token injection properly; any auth interceptor should not replace the bucket token with the access token.

User Bucket This bucket stores public user files for each user.

When a user logs in—or in the /currentuser response—there is a userBucketToken to use when sending user-related public files to the bucket service.

{
  //...
  "userBucketToken": "e56d...."
}

To upload a file

POST {baseUrl}/bucket/upload

The request body is form-data which includes the bucketId and the file binary in the files field.

{
    bucketId: "{userId}-public-user-bucket",
    files: {binary}
}

Response status is 200 on success, e.g., body:

{
    "success": true,
    "data": [
        {
            "fileId": "9da03f6d-0409-41ad-bb06-225a244ae408",
            "originalName": "test (10).png",
            "mimeType": "image/png",
            "size": 604063,
            "status": "uploaded",
            "bucketName": "f7103b85-fcda-4dec-92c6-c336f71fd3a2-public-user-bucket",
            "isPublic": true,
            "downloadUrl": "https://babilcom.mindbricks.co/bucket/download/9da03f6d-0409-41ad-bb06-225a244ae408"
        }
    ]
}

To download a file from the bucket, you need its fileId. If you upload an avatar or other asset, ensure the download URL or the fileId is stored in the backend.

Buckets are mostly used in object creations that require an additional file, such as a product image or user avatar. After uploading your image to the bucket, insert the returned download URL into the related property of the target object record.

Application Bucket

This Clonesahibinden application also includes a common public bucket that anyone can read, but only users with the superAdmin, admin, or saasAdmin roles can write (upload) to it.

When a user with one of these admin roles is logged in, the /login response or the /currentuser response also returns an applicationBucketToken field, which is used when uploading any file to the application bucket.

{
  //...
  "applicationBucketToken": "e23fd...."
}

The common public application bucket ID is

"clonesahibinden-public-common-bucket"

In certain admin areas—such as product management pages—since the user already has the application bucket token, they will be able to upload related object images.

Please configure your UI to upload files to the application bucket using this bucket token whenever needed.

Object Buckets Some objects may also return a bucket token for uploading or accessing files related to that object. For example, in a project management application, when you fetch a project’s data, a public or private bucket token may be provided to upload or download project-related files.

These buckets will be used as described in the relevant object definitions.

ConversationMessage Data Object

A single message sent between two users within a conversation about a listing. Tracks sender, receiver, timestamps and read status.

ConversationMessage Data Object Frontend Description By The Backend Architect

Represents individual messages inside a conversation. Sender and receiver must match the thread participants. Users only see their own conversations and messages. Moderators can view all.

ConversationMessage Data Object Properties

ConversationMessage 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
content Text false Yes No Message text body. Sanitized before saving.
conversationThreadId ID false Yes No Parent thread for this message.
isRead Boolean false Yes No True if the receiver has read this message.
readAt Date false No No Timestamp when the receiver read the message (null if unread).
receiverId ID false Yes No User receiving the message (must be the other participant of the thread).
senderId ID false Yes No User sending the message (must be a participant of the thread).
sentAt Date false Yes No Timestamp when message was sent.

Relation Properties

conversationThreadId receiverId senderId

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: Yes

ConversationThread Data Object

Private messaging thread between two users regarding a specific listing. Unique per (listing, user pair), order-invariant. Tracks last message time for inbox sorting.

ConversationThread Data Object Frontend Description By The Backend Architect

Each thread uniquely represents all messages between two users about one listing. Users see these in inbox; moderators can list/search all for review.

ConversationThread Data Object Properties

ConversationThread 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
lastMessageAt Date false Yes No Date/time of the latest message in the thread (for sorting inbox).
listingId ID false Yes No ID of the listing being discussed.
receiverId ID false Yes No User B in the conversation (order-invariant with senderId).
senderId ID false Yes No User A in the conversation (order-invariant with receiverId).

Relation Properties

listingId receiverId senderId

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: Yes

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.

ConversationMessage Default APIs

Operation API Name Route Explicitly Set
Create createConversationMessage /v1/conversationmessages Auto
Update markMessageAsRead /v1/markmessageasread/:conversationMessageId Auto
Delete deleteConversationMessage /v1/conversationmessages/:conversationMessageId Auto
Get getConversationMessage /v1/conversationmessages/:conversationMessageId Auto
List listConversationMessages /v1/listconversationmessages/:conversationThreadId System

ConversationThread Default APIs

Operation API Name Route Explicitly Set
Create createConversationThread /v1/conversationthreads Auto
Update none - Auto
Delete none - Auto
Get getConversationThread /v1/conversationthreads/:conversationThreadId Auto
List listConversationThreads /v1/conversationthreads System

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 Conversationmessage API

Send a new message in a conversation. Only thread participants can send; updates thread’s lastMessageAt.

API Frontend Description By The Backend Architect

Used when a user sends a message in a conversation (thread). On success, new message appears in thread; unread by receiver.

Rest Route

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

/v1/conversationmessages

Rest Request Parameters

The createConversationMessage api has got 7 regular request parameters

Parameter Type Required Population
content Text true request.body?.[“content”]
conversationThreadId ID true request.body?.[“conversationThreadId”]
isRead Boolean true request.body?.[“isRead”]
readAt Date false request.body?.[“readAt”]
receiverId ID true request.body?.[“receiverId”]
senderId ID true request.body?.[“senderId”]
sentAt Date true request.body?.[“sentAt”]
content : Message text body. Sanitized before saving.
conversationThreadId : Parent thread for this message.
isRead : True if the receiver has read this message.
readAt : Timestamp when the receiver read the message (null if unread).
receiverId : User receiving the message (must be the other participant of the thread).
senderId : User sending the message (must be a participant of the thread).
sentAt : Timestamp when message was sent.

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

  axios({
    method: 'POST',
    url: '/v1/conversationmessages',
    data: {
            content:"Text",  
            conversationThreadId:"ID",  
            isRead:"Boolean",  
            readAt:"Date",  
            receiverId:"ID",  
            senderId:"ID",  
            sentAt:"Date",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "conversationMessage",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"conversationMessage": {
		"id": "ID",
		"content": "Text",
		"conversationThreadId": "ID",
		"isRead": "Boolean",
		"readAt": "Date",
		"receiverId": "ID",
		"senderId": "ID",
		"sentAt": "Date",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Create Conversationthread API

Starts a new conversation thread between two users for a specific listing. Prevents duplicate threads for the same user pair/listing.

API Frontend Description By The Backend Architect

Invoked when user contacts seller about a listing. If an existing thread exists for this user pair/listing (any order), it is reused. Only listing owner or buyers can start a thread.

Rest Route

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

/v1/conversationthreads

Rest Request Parameters

The createConversationThread api has got 4 regular request parameters

Parameter Type Required Population
lastMessageAt Date true request.body?.[“lastMessageAt”]
listingId ID true request.body?.[“listingId”]
receiverId ID true request.body?.[“receiverId”]
senderId ID true request.body?.[“senderId”]
lastMessageAt : Date/time of the latest message in the thread (for sorting inbox).
listingId : ID of the listing being discussed.
receiverId : User B in the conversation (order-invariant with senderId).
senderId : User A in the conversation (order-invariant with receiverId).

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

  axios({
    method: 'POST',
    url: '/v1/conversationthreads',
    data: {
            lastMessageAt:"Date",  
            listingId:"ID",  
            receiverId:"ID",  
            senderId:"ID",  
    
    },
    params: {
    
        }
  });

REST Response

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

Delete Conversationmessage API

Soft-deletes a message. Only moderator/admins can fully delete; users may hide/delete for self (future phase).

API Frontend Description By The Backend Architect

Used for moderation; message remains for audit trail/history.

Rest Route

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

/v1/conversationmessages/:conversationMessageId

Rest Request Parameters

The deleteConversationMessage api has got 1 regular request parameter

Parameter Type Required Population
conversationMessageId ID true request.params?.[“conversationMessageId”]
conversationMessageId : 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/conversationmessages/:conversationMessageId

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

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "conversationMessage",
	"method": "DELETE",
	"action": "delete",
	"appVersion": "Version",
	"rowCount": 1,
	"conversationMessage": {
		"id": "ID",
		"content": "Text",
		"conversationThreadId": "ID",
		"isRead": "Boolean",
		"readAt": "Date",
		"receiverId": "ID",
		"senderId": "ID",
		"sentAt": "Date",
		"isActive": false,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Get Conversationmessage API

Fetch a single message by ID. Only accessible to participants or moderators/admins.

API Frontend Description By The Backend Architect

Loads a message for display in UI. Fails if not participant or staff.

Rest Route

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

/v1/conversationmessages/:conversationMessageId

Rest Request Parameters

The getConversationMessage api has got 1 regular request parameter

Parameter Type Required Population
conversationMessageId ID true request.params?.[“conversationMessageId”]
conversationMessageId : 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/conversationmessages/:conversationMessageId

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

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "conversationMessage",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"conversationMessage": {
		"id": "ID",
		"content": "Text",
		"conversationThreadId": "ID",
		"isRead": "Boolean",
		"readAt": "Date",
		"receiverId": "ID",
		"senderId": "ID",
		"sentAt": "Date",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Get Conversationthread API

Get a conversation thread by ID. Only visible to participants or staff.

API Frontend Description By The Backend Architect

Shows full thread info for inbox/detail view. Fails if user does not participate or is not moderator/admin.

Rest Route

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

/v1/conversationthreads/:conversationThreadId

Rest Request Parameters

The getConversationThread api has got 1 regular request parameter

Parameter Type Required Population
conversationThreadId ID true request.params?.[“conversationThreadId”]
conversationThreadId : 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/conversationthreads/:conversationThreadId

  axios({
    method: 'GET',
    url: `/v1/conversationthreads/${conversationThreadId}`,
    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": "conversationThread",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"conversationThread": {
		"listing": {
			"status": "Enum",
			"status_idx": "Integer",
			"title": "String",
			"userId": "ID"
		},
		"isActive": true
	}
}

List Conversationmessages API

List all messages in a thread, sorted oldest to newest. Only accessible to thread participants or staff.

API Frontend Description By The Backend Architect

Loads the chat history in UI for reading; includes isRead, sender info, etc. Used for conversation detail view.

Rest Route

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

/v1/listconversationmessages/:conversationThreadId

Rest Request Parameters

The listConversationMessages api has got 1 regular request parameter

Parameter Type Required Population
conversationThreadId ID true request.query?.[“conversationThreadId”]
conversationThreadId : Thread to load messages from.

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

  axios({
    method: 'GET',
    url: `/v1/listconversationmessages/${conversationThreadId}`,
    data: {
    
    },
    params: {
             conversationThreadId:'"ID"',  
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "conversationMessages",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"conversationMessages": [
		{
			"id": "ID",
			"content": "Text",
			"conversationThreadId": "ID",
			"isRead": "Boolean",
			"readAt": "Date",
			"receiverId": "ID",
			"senderId": "ID",
			"sentAt": "Date",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID"
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

List Conversationthreads API

List all threads a user participates in, most recent first. Also used for moderator search/all-list.

API Frontend Description By The Backend Architect

Shows all user’s conversation threads in inbox. Moderators can search all.

Rest Route

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

/v1/conversationthreads

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

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

  axios({
    method: 'GET',
    url: '/v1/conversationthreads',
    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": "conversationThreads",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"conversationThreads": [
		{
			"listing": [
				{
					"status": "Enum",
					"status_idx": "Integer",
					"title": "String",
					"userId": "ID"
				},
				{},
				{}
			],
			"isActive": true
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Mark Messageasread API

Marks a message as read (isRead=true, readAt=now); only allowed for receiver.

API Frontend Description By The Backend Architect

When viewing messages, receiver marks message as read – triggers unread count decrement in UI, updates message status.

Rest Route

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

/v1/markmessageasread/:conversationMessageId

Rest Request Parameters

The markMessageAsRead api has got 3 regular request parameters

Parameter Type Required Population
conversationMessageId ID true request.params?.[“conversationMessageId”]
isRead Boolean false request.body?.[“isRead”]
readAt Date false request.body?.[“readAt”]
conversationMessageId : This id paremeter is used to select the required data object that will be updated
isRead : True if the receiver has read this message.
readAt : Timestamp when the receiver read the message (null if unread).

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

  axios({
    method: 'PATCH',
    url: `/v1/markmessageasread/${conversationMessageId}`,
    data: {
            isRead:"Boolean",  
            readAt:"Date",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "conversationMessage",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"conversationMessage": {
		"id": "ID",
		"content": "Text",
		"conversationThreadId": "ID",
		"isRead": "Boolean",
		"readAt": "Date",
		"receiverId": "ID",
		"senderId": "ID",
		"sentAt": "Date",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

_fetch Listconversationmessage API

System API to fetch list of conversationMessage records for frontend application. Auto-generated, not visible in design.

Rest Route

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

/v1/_fetchlistconversationmessage

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

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

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

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "conversationMessages",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"conversationMessages": [
		{
			"id": "ID",
			"content": "Text",
			"conversationThreadId": "ID",
			"isRead": "Boolean",
			"readAt": "Date",
			"receiverId": "ID",
			"senderId": "ID",
			"sentAt": "Date",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID",
			"thread": [
				{
					"lastMessageAt": "Date",
					"listingId": "ID",
					"receiverId": "ID",
					"senderId": "ID"
				},
				{},
				{}
			],
			"receiverUser": [
				{
					"fullname": "String"
				},
				{},
				{}
			],
			"senderUser": [
				{
					"fullname": "String"
				},
				{},
				{}
			]
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

_fetch Listconversationthread API

System API to fetch list of conversationThread records for frontend application. Auto-generated, not visible in design.

Rest Route

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

/v1/_fetchlistconversationthread

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

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

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

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "conversationThreads",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"conversationThreads": [
		{
			"id": "ID",
			"lastMessageAt": "Date",
			"listingId": "ID",
			"receiverId": "ID",
			"senderId": "ID",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID",
			"listing": [
				{
					"attributes": "Object",
					"categoryId": "ID",
					"condition": "Enum",
					"condition_idx": "Integer",
					"contactEmail": "String",
					"contactPhone": "String",
					"currency": "String",
					"description": "Text",
					"expiresAt": "Date",
					"favoriteCount": "Integer",
					"isPremium": "Boolean",
					"listingType": "Enum",
					"listingType_idx": "Integer",
					"locationId": "ID",
					"_paymentConfirmation": "String",
					"premiumExpiry": "Date",
					"premiumType": "Enum",
					"premiumType_idx": "Integer",
					"price": "Double",
					"status": "Enum",
					"status_idx": "Integer",
					"subcategoryId": "ID",
					"title": "String",
					"userId": "ID",
					"viewsCount": "Integer"
				},
				{},
				{}
			],
			"receiverUser": [
				{
					"fullname": "String"
				},
				{},
				{}
			],
			"senderUser": [
				{
					"fullname": "String"
				},
				{},
				{}
			]
		},
		{},
		{}
	],
	"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.


Favorite Service

CLONESAHIBINDEN

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

This document is a part of a REST API guide for the clonesahibinden 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 favorite

Service Access

Favorite service management is handled through service specific base urls.

Favorite 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 favorite service, the base URLs are:

Scope

Favorite Service Description

Handles all user favorites for classified listings, including add/remove, listing user-specific collections, and providing favorited status for listings. Prevents duplicate favorites and maintains favorite counts on listings for optimal UX. Cascade-cleans favorites if user or listing is deleted.

Favorite service provides apis and business logic for following data objects in clonesahibinden 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.

favorite Data Object: Stores which user favorited which listing, with timestamp. Enforces unique favorites per (user,listing) pair, and cascades on user/listing deletion.

Favorite Service Frontend Description By The Backend Architect

AI Dev: All favoriting actions require login. The UX must make favoriting/unfavoriting instant, providing clear feedback (heart icon animation, etc). The ‘Favorites’ page should show listing summary (titles and cover image at minimum). Show an “Already favorited” state in listing cards and details for each listing display. Any removal/addition must be reflected immediately in all screens due to eventual consistency (favoriteCount). For each listing in feeds or details, display if favorited by current user by pulling the user’s favorites or calling getFavorite for relevant pair. Listing favorite count must update optimistically on the UI after favorite/unfavorite. Do not allow favoriting own listings (enforced by backend API as well).

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"
}

Bucket Management

(This information is also given in PART 1 prompt.)

This application has a bucket service used to store user files and other object-related files. The bucket service is login-agnostic, so for write operations or private reads, include a bucket token (provided by services) in the request’s Authorization header as a Bearer token.

Please note that all other business services require the access token in the Bearer header, while the bucket service expects a bucket token because it is login-agnostic. Ensure you manage the required token injection properly; any auth interceptor should not replace the bucket token with the access token.

User Bucket This bucket stores public user files for each user.

When a user logs in—or in the /currentuser response—there is a userBucketToken to use when sending user-related public files to the bucket service.

{
  //...
  "userBucketToken": "e56d...."
}

To upload a file

POST {baseUrl}/bucket/upload

The request body is form-data which includes the bucketId and the file binary in the files field.

{
    bucketId: "{userId}-public-user-bucket",
    files: {binary}
}

Response status is 200 on success, e.g., body:

{
    "success": true,
    "data": [
        {
            "fileId": "9da03f6d-0409-41ad-bb06-225a244ae408",
            "originalName": "test (10).png",
            "mimeType": "image/png",
            "size": 604063,
            "status": "uploaded",
            "bucketName": "f7103b85-fcda-4dec-92c6-c336f71fd3a2-public-user-bucket",
            "isPublic": true,
            "downloadUrl": "https://babilcom.mindbricks.co/bucket/download/9da03f6d-0409-41ad-bb06-225a244ae408"
        }
    ]
}

To download a file from the bucket, you need its fileId. If you upload an avatar or other asset, ensure the download URL or the fileId is stored in the backend.

Buckets are mostly used in object creations that require an additional file, such as a product image or user avatar. After uploading your image to the bucket, insert the returned download URL into the related property of the target object record.

Application Bucket

This Clonesahibinden application also includes a common public bucket that anyone can read, but only users with the superAdmin, admin, or saasAdmin roles can write (upload) to it.

When a user with one of these admin roles is logged in, the /login response or the /currentuser response also returns an applicationBucketToken field, which is used when uploading any file to the application bucket.

{
  //...
  "applicationBucketToken": "e23fd...."
}

The common public application bucket ID is

"clonesahibinden-public-common-bucket"

In certain admin areas—such as product management pages—since the user already has the application bucket token, they will be able to upload related object images.

Please configure your UI to upload files to the application bucket using this bucket token whenever needed.

Object Buckets Some objects may also return a bucket token for uploading or accessing files related to that object. For example, in a project management application, when you fetch a project’s data, a public or private bucket token may be provided to upload or download project-related files.

These buckets will be used as described in the relevant object definitions.

Favorite Data Object

Stores which user favorited which listing, with timestamp. Enforces unique favorites per (user,listing) pair, and cascades on user/listing deletion.

Favorite Data Object Frontend Description By The Backend Architect

AI Dev: Each favorite represents a single (user,listing) pair—no duplicate favorites allowed. Used for rendering heart/check in listing cards and assembling user’s favorites page. Listing preview must be fetched alongside favorite info.

Favorite Data Object Properties

Favorite 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
favoritedAt Date false Yes No Date and time when the favorite was added.
listingId ID false Yes No Target listing being favorited.
userId ID false Yes No User who favorited the listing.

Relation Properties

listingId 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

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.

Favorite Default APIs

Operation API Name Route Explicitly Set
Create createFavorite /v1/favorites Auto
Update none - Auto
Delete deleteFavorite /v1/favorites/:favoriteId Auto
Get getFavorite /v1/favorites/:favoriteId Auto
List listFavorites /v1/favorites System

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 Favorite API

Add a favorite for a listing for the current user. Prevents duplicate (user,listing) pairs, and can’t favorite own listing.

API Frontend Description By The Backend Architect

AI Dev: Call this API to favorite a listing; on success, update UI state and increment count. If already favorited, show appropriate feedback. Cannot favorite own listings. No double favoriting allowed.

Rest Route

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

/v1/favorites

Rest Request Parameters

The createFavorite api has got 1 regular request parameter

Parameter Type Required Population
listingId ID true request.body?.[“listingId”]
listingId : Target listing being favorited.

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

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

REST Response

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

Delete Favorite API

Unfavorite (remove favorite) the given listing for current user. Decrements favoriteCount on related listing when possible.

API Frontend Description By The Backend Architect

AI Dev: Use this API to unfavorite a listing. On success, update UI (remove highlight) and decrement displayed favorite count. If not found, treat as idempotent success for best UX.

Rest Route

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

/v1/favorites/:favoriteId

Rest Request Parameters

The deleteFavorite api has got 2 regular request parameters

Parameter Type Required Population
favoriteId ID true request.params?.[“favoriteId”]
listingId ID true request.query?.[“listingId”]
favoriteId : This id paremeter is used to select the required data object that will be deleted
listingId : Target listing being favorited… The parameter is used to query data.

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

  axios({
    method: 'DELETE',
    url: `/v1/favorites/${favoriteId}`,
    data: {
    
    },
    params: {
             listingId:'"ID"',  
    
        }
  });

REST Response

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

Get Favorite API

Get a specific favorite by id or by userId+listingId, mainly used to check if a listing is favorited by user (for heart/check display in feeds/details). Only accessible by owner or admin.

API Frontend Description By The Backend Architect

AI Dev: Use to check if a given listing is in the user’s favorites; supports single-record fetch via id or userId+listingId composite. If no record, treat as not favorited in UI.

Rest Route

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

/v1/favorites/:favoriteId

Rest Request Parameters

The getFavorite api has got 1 regular request parameter

Parameter Type Required Population
favoriteId ID true request.params?.[“favoriteId”]
favoriteId : 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/favorites/:favoriteId

  axios({
    method: 'GET',
    url: `/v1/favorites/${favoriteId}`,
    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": "favorite",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"favorite": {
		"listing": {
			"isPremium": "Boolean",
			"premiumType": "Enum",
			"premiumType_idx": "Integer",
			"price": "Double",
			"status": "Enum",
			"status_idx": "Integer",
			"title": "String"
		},
		"isActive": true
	}
}

List Favorites API

List all listings favorited by the current user, joined with listing summary and preview (title, price, cover image, etc). Private; only owner or admin can access.

API Frontend Description By The Backend Architect

AI Dev: Use this to render the user’s entire favorites collection for the profile page. Each item must provide at least listing id, title, price, and main image for visual feed. Paginate and sort newest first by favoritedAt.

Rest Route

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

/v1/favorites

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

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

  axios({
    method: 'GET',
    url: '/v1/favorites',
    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": "favorites",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"favorites": [
		{
			"listing": [
				{
					"currency": "String",
					"isPremium": "Boolean",
					"premiumType": "Enum",
					"premiumType_idx": "Integer",
					"price": "Double",
					"status": "Enum",
					"status_idx": "Integer",
					"title": "String"
				},
				{},
				{}
			],
			"mainImage": {
				"sortOrder": "Integer",
				"thumbnailUrl": "String",
				"url": "String"
			},
			"isActive": true
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

_fetch Listfavorite API

System API to fetch list of favorite records for frontend application. Auto-generated, not visible in design.

Rest Route

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

/v1/_fetchlistfavorite

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

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

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

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "favorites",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"favorites": [
		{
			"id": "ID",
			"favoritedAt": "Date",
			"listingId": "ID",
			"userId": "ID",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID",
			"listing": [
				{
					"attributes": "Object",
					"categoryId": "ID",
					"condition": "Enum",
					"condition_idx": "Integer",
					"contactEmail": "String",
					"contactPhone": "String",
					"currency": "String",
					"description": "Text",
					"expiresAt": "Date",
					"favoriteCount": "Integer",
					"isPremium": "Boolean",
					"listingType": "Enum",
					"listingType_idx": "Integer",
					"locationId": "ID",
					"_paymentConfirmation": "String",
					"premiumExpiry": "Date",
					"premiumType": "Enum",
					"premiumType_idx": "Integer",
					"price": "Double",
					"status": "Enum",
					"status_idx": "Integer",
					"subcategoryId": "ID",
					"title": "String",
					"userId": "ID",
					"viewsCount": "Integer"
				},
				{},
				{}
			],
			"user": [
				{
					"fullname": "String"
				},
				{},
				{}
			]
		},
		{},
		{}
	],
	"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.


Listing Service

CLONESAHIBINDEN

FRONTEND GUIDE FOR AI CODING AGENTS - PART 10 - Listing Service

This document is a part of a REST API guide for the clonesahibinden 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 listing

Service Access

Listing service management is handled through service specific base urls.

Listing 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 listing service, the base URLs are:

Scope

Listing Service Description

Manages classified listings, their lifecycle, premium features, status transitions, and provides filtering/search for marketplace ads. Integrates with users, categories, locations, and Stripe for premium ad upgrades. Enforces ad and user type business logic.

Listing service provides apis and business logic for following data objects in clonesahibinden 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.

listing Data Object: Core object for classified ads. Contains main listing information, relations, status, premium logic, price, attributes, contact info, and custom attributes. Supports premium upgrades via Stripe and lifecycle management.

sys_listingPayment Data Object: A payment storage object to store the payment life cyle of orders based on listing object. It is autocreated based on the source object's checkout config

sys_paymentCustomer Data Object: A payment storage object to store the customer values of the payment platform

sys_paymentMethod Data Object: A payment storage object to store the payment methods of the platform customers

Listing Service Frontend Description By The Backend Architect

Listing Service UX Hints

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"
}

Bucket Management

(This information is also given in PART 1 prompt.)

This application has a bucket service used to store user files and other object-related files. The bucket service is login-agnostic, so for write operations or private reads, include a bucket token (provided by services) in the request’s Authorization header as a Bearer token.

Please note that all other business services require the access token in the Bearer header, while the bucket service expects a bucket token because it is login-agnostic. Ensure you manage the required token injection properly; any auth interceptor should not replace the bucket token with the access token.

User Bucket This bucket stores public user files for each user.

When a user logs in—or in the /currentuser response—there is a userBucketToken to use when sending user-related public files to the bucket service.

{
  //...
  "userBucketToken": "e56d...."
}

To upload a file

POST {baseUrl}/bucket/upload

The request body is form-data which includes the bucketId and the file binary in the files field.

{
    bucketId: "{userId}-public-user-bucket",
    files: {binary}
}

Response status is 200 on success, e.g., body:

{
    "success": true,
    "data": [
        {
            "fileId": "9da03f6d-0409-41ad-bb06-225a244ae408",
            "originalName": "test (10).png",
            "mimeType": "image/png",
            "size": 604063,
            "status": "uploaded",
            "bucketName": "f7103b85-fcda-4dec-92c6-c336f71fd3a2-public-user-bucket",
            "isPublic": true,
            "downloadUrl": "https://babilcom.mindbricks.co/bucket/download/9da03f6d-0409-41ad-bb06-225a244ae408"
        }
    ]
}

To download a file from the bucket, you need its fileId. If you upload an avatar or other asset, ensure the download URL or the fileId is stored in the backend.

Buckets are mostly used in object creations that require an additional file, such as a product image or user avatar. After uploading your image to the bucket, insert the returned download URL into the related property of the target object record.

Application Bucket

This Clonesahibinden application also includes a common public bucket that anyone can read, but only users with the superAdmin, admin, or saasAdmin roles can write (upload) to it.

When a user with one of these admin roles is logged in, the /login response or the /currentuser response also returns an applicationBucketToken field, which is used when uploading any file to the application bucket.

{
  //...
  "applicationBucketToken": "e23fd...."
}

The common public application bucket ID is

"clonesahibinden-public-common-bucket"

In certain admin areas—such as product management pages—since the user already has the application bucket token, they will be able to upload related object images.

Please configure your UI to upload files to the application bucket using this bucket token whenever needed.

Object Buckets Some objects may also return a bucket token for uploading or accessing files related to that object. For example, in a project management application, when you fetch a project’s data, a public or private bucket token may be provided to upload or download project-related files.

These buckets will be used as described in the relevant object definitions.

Listing Data Object

Core object for classified ads. Contains main listing information, relations, status, premium logic, price, attributes, contact info, and custom attributes. Supports premium upgrades via Stripe and lifecycle management.

Listing Data Object Frontend Description By The Backend Architect

Data Object: listing

Listing Data Object Properties

Listing 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
attributes Object false No No JSON object for custom per-category attributes (structured as required by category schema).
categoryId ID false Yes No Main category for the listing (categoryLocation:category).
condition Enum false Yes No Item condition: new, used, other.
contactEmail String false No No Contact email (recommended to send via platform only).
contactPhone String false No No Display phone/contact for listing; may be masked by front end.
currency String false Yes No Currency (ISO-4217 code, e.g. ‘TRY’, ‘USD’).
description Text false Yes No Full description/body of listing.
expiresAt Date false No No UTC expiry for listing; after this, listing is automatically expired.
favoriteCount Integer false Yes No Favorite count (updated asynchronously by favorite service, not directly settable by user).
isPremium Boolean false Yes No If true, the listing is premium (highlighted/pinned, eligible for special placement).
listingType Enum false Yes No Type of listing (sale, rent, service, etc.).
locationId ID false Yes No Location (categoryLocation:location).
_paymentConfirmation String false No No Stripe payment result details (Stripe webhook metadata, internal use only).
premiumExpiry Date false No No UTC date when premium status expires. Null if not premium or not applicable.
premiumType Enum false No No Which premium package (gold, silver, none, etc.).
price Double false Yes No Listing price.
status Enum false Yes No Lifecycle status: pending_review, active, denied, sold, expired, deleted.
subcategoryId ID false No No Subcategory for the listing, can be null for top-level (categoryLocation:category).
title String false Yes No Listing title, short and clear.
userId ID false Yes No Owner (poster) of the listing (auth:user).
viewsCount Integer false Yes No View count (updated asynchronously; not directly settable by user).
paymentConfirmation Enum false Yes No An automatic property that is used to check the confirmed status of the payment set by webhooks.

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

categoryId locationId subcategoryId 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

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

categoryId condition expiresAt isPremium listingType locationId premiumExpiry premiumType price status subcategoryId title userId paymentConfirmation

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_listingPayment Data Object

A payment storage object to store the payment life cyle of orders based on listing object. It is autocreated based on the source object's checkout config

Sys_listingPayment Data Object Properties

Sys_listingPayment 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
ownerId ID false No No An ID value to represent owner user who created the order
orderId ID false Yes No an ID value to represent the orderId which is the ID parameter of the source listing object
paymentId String false Yes No A String value to represent the paymentId which is generated on the Stripe gateway. This id may represent different objects due to the payment gateway and the chosen flow type
paymentStatus String false Yes No A string value to represent the payment status which belongs to the lifecyle of a Stripe payment.
statusLiteral String false Yes No A string value to represent the logical payment status which belongs to the application lifecycle itself.
redirectUrl String false No No A string value to represent return page of the frontend to show the result of the payment, this is used when the callback is made to server not the client.

Filter Properties

ownerId orderId paymentId paymentStatus statusLiteral redirectUrl

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_paymentCustomer Data Object

A payment storage object to store the customer values of the payment platform

Sys_paymentCustomer Data Object Properties

Sys_paymentCustomer 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 No No An ID value to represent the user who is created as a stripe customer
customerId String false Yes No A string value to represent the customer id which is generated on the Stripe gateway. This id is used to represent the customer in the Stripe gateway
platform String false Yes No A String value to represent payment platform which is used to make the payment. It is stripe as default. It will be used to distinguesh the payment gateways in the future.

Filter Properties

userId customerId platform

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_paymentMethod Data Object

A payment storage object to store the payment methods of the platform customers

Sys_paymentMethod Data Object Properties

Sys_paymentMethod 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
paymentMethodId String false Yes No A string value to represent the id of the payment method on the payment platform.
userId ID false Yes No An ID value to represent the user who owns the payment method
customerId String false Yes No A string value to represent the customer id which is generated on the payment gateway.
cardHolderName String false No No A string value to represent the name of the card holder. It can be different than the registered customer.
cardHolderZip String false No No A string value to represent the zip code of the card holder. It is used for address verification in specific countries.
platform String false Yes No A String value to represent payment platform which teh paymentMethod belongs. It is stripe as default. It will be used to distinguesh the payment gateways in the future.
cardInfo Object false Yes No A Json value to store the card details of the payment method.

Filter Properties

paymentMethodId userId customerId cardHolderName cardHolderZip platform cardInfo

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.

Listing Default APIs

Operation API Name Route Explicitly Set
Create createListing /v1/listings Auto
Update updateListing /v1/listings/:listingId Auto
Delete deleteListing /v1/listings/:listingId Auto
Get getListing /v1/listings/:listingId Auto
List listListings /v1/listings System

Sys_listingPayment Default APIs

Operation API Name Route Explicitly Set
Create createListingPayment /v1/listingpayment Auto
Update updateListingPayment /v1/listingpayment/:sys_listingPaymentId Auto
Delete deleteListingPayment /v1/listingpayment/:sys_listingPaymentId Auto
Get getListingPayment /v1/listingpayment/:sys_listingPaymentId Auto
List listListingPayments /v1/listingpayments System

Sys_paymentCustomer Default APIs

Operation API Name Route Explicitly Set
Create none - Auto
Update none - Auto
Delete none - Auto
Get getPaymentCustomerByUserId /v1/paymentcustomers/:userId Auto
List listPaymentCustomers /v1/paymentcustomers System

Sys_paymentMethod Default APIs

Operation API Name Route Explicitly Set
Create none - Auto
Update none - Auto
Delete none - Auto
Get none - Auto
List listPaymentCustomerMethods /v1/paymentcustomermethods/:userId System

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 Listing API

Create a new classified listing. Sets status to ‘pending_review’ (may be updated by moderator process). Accepts all mandatory fields, accepts premiumType for premium upgrade.

API Frontend Description By The Backend Architect

Rest Route

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

/v1/listings

Rest Request Parameters

The createListing api has got 19 regular request parameters

Parameter Type Required Population
attributes Object false request.body?.[“attributes”]
categoryId ID true request.body?.[“categoryId”]
condition Enum true request.body?.[“condition”]
contactEmail String false request.body?.[“contactEmail”]
contactPhone String false request.body?.[“contactPhone”]
currency String true request.body?.[“currency”]
description Text true request.body?.[“description”]
expiresAt Date false request.body?.[“expiresAt”]
favoriteCount Integer true request.body?.[“favoriteCount”]
listingType Enum true request.body?.[“listingType”]
locationId ID true request.body?.[“locationId”]
_paymentConfirmation String false request.body?.[“_paymentConfirmation”]
premiumExpiry Date false request.body?.[“premiumExpiry”]
premiumType Enum false request.body?.[“premiumType”]
price Double true request.body?.[“price”]
status Enum true request.body?.[“status”]
subcategoryId ID false request.body?.[“subcategoryId”]
title String true request.body?.[“title”]
viewsCount Integer true request.body?.[“viewsCount”]
attributes : JSON object for custom per-category attributes (structured as required by category schema).
categoryId : Main category for the listing (categoryLocation:category).
condition : Item condition: new, used, other.
contactEmail : Contact email (recommended to send via platform only).
contactPhone : Display phone/contact for listing; may be masked by front end.
currency : Currency (ISO-4217 code, e.g. ‘TRY’, ‘USD’).
description : Full description/body of listing.
expiresAt : UTC expiry for listing; after this, listing is automatically expired.
favoriteCount : Favorite count (updated asynchronously by favorite service, not directly settable by user).
listingType : Type of listing (sale, rent, service, etc.).
locationId : Location (categoryLocation:location).
_paymentConfirmation : Stripe payment result details (Stripe webhook metadata, internal use only).
premiumExpiry : UTC date when premium status expires. Null if not premium or not applicable.
premiumType : Which premium package (gold, silver, none, etc.).
price : Listing price.
status : Lifecycle status: pending_review, active, denied, sold, expired, deleted.
subcategoryId : Subcategory for the listing, can be null for top-level (categoryLocation:category).
title : Listing title, short and clear.
viewsCount : View count (updated asynchronously; not directly settable by user).

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

  axios({
    method: 'POST',
    url: '/v1/listings',
    data: {
            attributes:"Object",  
            categoryId:"ID",  
            condition:"Enum",  
            contactEmail:"String",  
            contactPhone:"String",  
            currency:"String",  
            description:"Text",  
            expiresAt:"Date",  
            favoriteCount:"Integer",  
            listingType:"Enum",  
            locationId:"ID",  
            _paymentConfirmation:"String",  
            premiumExpiry:"Date",  
            premiumType:"Enum",  
            price:"Double",  
            status:"Enum",  
            subcategoryId:"ID",  
            title:"String",  
            viewsCount:"Integer",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "listing",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"listing": {
		"id": "ID",
		"attributes": "Object",
		"categoryId": "ID",
		"condition": "Enum",
		"condition_idx": "Integer",
		"contactEmail": "String",
		"contactPhone": "String",
		"currency": "String",
		"description": "Text",
		"expiresAt": "Date",
		"favoriteCount": "Integer",
		"isPremium": "Boolean",
		"listingType": "Enum",
		"listingType_idx": "Integer",
		"locationId": "ID",
		"_paymentConfirmation": "String",
		"premiumExpiry": "Date",
		"premiumType": "Enum",
		"premiumType_idx": "Integer",
		"price": "Double",
		"status": "Enum",
		"status_idx": "Integer",
		"subcategoryId": "ID",
		"title": "String",
		"userId": "ID",
		"viewsCount": "Integer",
		"paymentConfirmation": "Enum",
		"paymentConfirmation_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Delete Listing API

Delete a listing (soft delete, sets status to ‘deleted’). Only allowed by listing owner, admin, or moderator.

API Frontend Description By The Backend Architect

Rest Route

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

/v1/listings/:listingId

Rest Request Parameters

The deleteListing api has got 1 regular request parameter

Parameter Type Required Population
listingId ID true request.params?.[“listingId”]
listingId : 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/listings/:listingId

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

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "listing",
	"method": "DELETE",
	"action": "delete",
	"appVersion": "Version",
	"rowCount": 1,
	"listing": {
		"id": "ID",
		"attributes": "Object",
		"categoryId": "ID",
		"condition": "Enum",
		"condition_idx": "Integer",
		"contactEmail": "String",
		"contactPhone": "String",
		"currency": "String",
		"description": "Text",
		"expiresAt": "Date",
		"favoriteCount": "Integer",
		"isPremium": "Boolean",
		"listingType": "Enum",
		"listingType_idx": "Integer",
		"locationId": "ID",
		"_paymentConfirmation": "String",
		"premiumExpiry": "Date",
		"premiumType": "Enum",
		"premiumType_idx": "Integer",
		"price": "Double",
		"status": "Enum",
		"status_idx": "Integer",
		"subcategoryId": "ID",
		"title": "String",
		"userId": "ID",
		"viewsCount": "Integer",
		"paymentConfirmation": "Enum",
		"paymentConfirmation_idx": "Integer",
		"isActive": false,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Expire Premiumsandlistings API

Scheduled job to expire listings or premium status as needed (cron call, not user). Sets status to expired, or disables isPremium when premiumExpiry is in the past.

API Frontend Description By The Backend Architect

Rest Route

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

/v1/expirepremiumsandlistings/:listingId

Rest Request Parameters

The expirePremiumsAndListings api has got 1 regular request parameter

Parameter Type Required Population
listingId ID true request.params?.[“listingId”]
listingId : 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 ** /v1/expirepremiumsandlistings/:listingId**

  axios({
    method: '',
    url: `/v1/expirepremiumsandlistings/${listingId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "listing",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"listing": {
		"id": "ID",
		"attributes": "Object",
		"categoryId": "ID",
		"condition": "Enum",
		"condition_idx": "Integer",
		"contactEmail": "String",
		"contactPhone": "String",
		"currency": "String",
		"description": "Text",
		"expiresAt": "Date",
		"favoriteCount": "Integer",
		"isPremium": "Boolean",
		"listingType": "Enum",
		"listingType_idx": "Integer",
		"locationId": "ID",
		"_paymentConfirmation": "String",
		"premiumExpiry": "Date",
		"premiumType": "Enum",
		"premiumType_idx": "Integer",
		"price": "Double",
		"status": "Enum",
		"status_idx": "Integer",
		"subcategoryId": "ID",
		"title": "String",
		"userId": "ID",
		"viewsCount": "Integer",
		"paymentConfirmation": "Enum",
		"paymentConfirmation_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Get Listing API

Retrieve one listing with all primary fields, including category, subcategory, location, user info. Optionally, frontend can request joined images/favorites from other services.

API Frontend Description By The Backend Architect

Rest Route

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

/v1/listings/:listingId

Rest Request Parameters

The getListing api has got 1 regular request parameter

Parameter Type Required Population
listingId ID true request.params?.[“listingId”]
listingId : 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/listings/:listingId

  axios({
    method: 'GET',
    url: `/v1/listings/${listingId}`,
    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": "listing",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"listing": {
		"user": {
			"fullname": "String",
			"avatar": "String",
			"roleId": "String"
		},
		"category": {
			"name": "String",
			"parentCategoryId": "ID",
			"slug": "String"
		},
		"subcategory": {
			"name": "String",
			"parentCategoryId": "ID",
			"slug": "String"
		},
		"location": {
			"city": "String",
			"country": "String",
			"district": "String"
		},
		"isActive": true
	}
}

List Listings API

Search/browse listings with advanced filtering (category, location, keyword, price range, condition, type, premium, status, etc.) and sorting. Publicly accessible. Supports pagination and all major sort orders. Full-text search on title/description.

API Frontend Description By The Backend Architect

Rest Route

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

/v1/listings

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

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

  axios({
    method: 'GET',
    url: '/v1/listings',
    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": "listings",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"listings": [
		{
			"user": [
				{
					"fullname": "String",
					"avatar": "String"
				},
				{},
				{}
			],
			"category": [
				{
					"name": "String"
				},
				{},
				{}
			],
			"subcategory": [
				{
					"name": "String"
				},
				{},
				{}
			],
			"location": [
				{
					"city": "String",
					"district": "String"
				},
				{},
				{}
			],
			"isActive": true
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Update Listing API

Update any mutable field of a listing. Only allowed by owner, admin, or moderator. If significant fields change and listing is active, status may return to pending_review until approved.

API Frontend Description By The Backend Architect

Rest Route

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

/v1/listings/:listingId

Rest Request Parameters

The updateListing api has got 17 regular request parameters

Parameter Type Required Population
listingId ID true request.params?.[“listingId”]
attributes Object false request.body?.[“attributes”]
categoryId ID false request.body?.[“categoryId”]
condition Enum false request.body?.[“condition”]
contactEmail String false request.body?.[“contactEmail”]
contactPhone String false request.body?.[“contactPhone”]
currency String false request.body?.[“currency”]
description Text false request.body?.[“description”]
expiresAt Date false request.body?.[“expiresAt”]
listingType Enum false request.body?.[“listingType”]
locationId ID false request.body?.[“locationId”]
premiumExpiry Date false request.body?.[“premiumExpiry”]
premiumType Enum false request.body?.[“premiumType”]
price Double false request.body?.[“price”]
status Enum false request.body?.[“status”]
subcategoryId ID false request.body?.[“subcategoryId”]
title String false request.body?.[“title”]
listingId : This id paremeter is used to select the required data object that will be updated
attributes : JSON object for custom per-category attributes (structured as required by category schema).
categoryId : Main category for the listing (categoryLocation:category).
condition : Item condition: new, used, other.
contactEmail : Contact email (recommended to send via platform only).
contactPhone : Display phone/contact for listing; may be masked by front end.
currency : Currency (ISO-4217 code, e.g. ‘TRY’, ‘USD’).
description : Full description/body of listing.
expiresAt : UTC expiry for listing; after this, listing is automatically expired.
listingType : Type of listing (sale, rent, service, etc.).
locationId : Location (categoryLocation:location).
premiumExpiry : UTC date when premium status expires. Null if not premium or not applicable.
premiumType : Which premium package (gold, silver, none, etc.).
price : Listing price.
status : Lifecycle status: pending_review, active, denied, sold, expired, deleted.
subcategoryId : Subcategory for the listing, can be null for top-level (categoryLocation:category).
title : Listing title, short and clear.

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

  axios({
    method: 'PATCH',
    url: `/v1/listings/${listingId}`,
    data: {
            attributes:"Object",  
            categoryId:"ID",  
            condition:"Enum",  
            contactEmail:"String",  
            contactPhone:"String",  
            currency:"String",  
            description:"Text",  
            expiresAt:"Date",  
            listingType:"Enum",  
            locationId:"ID",  
            premiumExpiry:"Date",  
            premiumType:"Enum",  
            price:"Double",  
            status:"Enum",  
            subcategoryId:"ID",  
            title:"String",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "listing",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"listing": {
		"id": "ID",
		"attributes": "Object",
		"categoryId": "ID",
		"condition": "Enum",
		"condition_idx": "Integer",
		"contactEmail": "String",
		"contactPhone": "String",
		"currency": "String",
		"description": "Text",
		"expiresAt": "Date",
		"favoriteCount": "Integer",
		"isPremium": "Boolean",
		"listingType": "Enum",
		"listingType_idx": "Integer",
		"locationId": "ID",
		"_paymentConfirmation": "String",
		"premiumExpiry": "Date",
		"premiumType": "Enum",
		"premiumType_idx": "Integer",
		"price": "Double",
		"status": "Enum",
		"status_idx": "Integer",
		"subcategoryId": "ID",
		"title": "String",
		"userId": "ID",
		"viewsCount": "Integer",
		"paymentConfirmation": "Enum",
		"paymentConfirmation_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Upgrade Listingpremium API

Upgrades a listing to premium status after successful payment. Sets isPremium=true, premiumType, premiumExpiry based on duration, and records payment confirmation. Called internally by payment service via interservice call.

API Frontend Description By The Backend Architect

Rest Route

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

/v1/listings/upgrade-premium

Rest Request Parameters

The upgradeListingPremium api has got 4 regular request parameters

Parameter Type Required Population
listingId ID true request.body?.[“listingId”]
premiumType Enum true request.body?.[“premiumType”]
premiumDuration Integer true request.body?.[“premiumDuration”]
paymentTransactionId ID true request.body?.[“paymentTransactionId”]
listingId : ID of the listing to upgrade
premiumType : Premium package type (bronze, silver, gold)
premiumDuration : Duration of premium in days
paymentTransactionId : Payment transaction ID for confirmation record

REST Request To access the api you can use the REST controller with the path POST /v1/listings/upgrade-premium

  axios({
    method: 'POST',
    url: '/v1/listings/upgrade-premium',
    data: {
            listingId:"ID",  
            premiumType:"Enum",  
            premiumDuration:"Integer",  
            paymentTransactionId:"ID",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "listing",
	"method": "POST",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"listing": {
		"id": "ID",
		"attributes": "Object",
		"categoryId": "ID",
		"condition": "Enum",
		"condition_idx": "Integer",
		"contactEmail": "String",
		"contactPhone": "String",
		"currency": "String",
		"description": "Text",
		"expiresAt": "Date",
		"favoriteCount": "Integer",
		"isPremium": "Boolean",
		"listingType": "Enum",
		"listingType_idx": "Integer",
		"locationId": "ID",
		"_paymentConfirmation": "String",
		"premiumExpiry": "Date",
		"premiumType": "Enum",
		"premiumType_idx": "Integer",
		"price": "Double",
		"status": "Enum",
		"status_idx": "Integer",
		"subcategoryId": "ID",
		"title": "String",
		"userId": "ID",
		"viewsCount": "Integer",
		"paymentConfirmation": "Enum",
		"paymentConfirmation_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Get Listingpayment API

This route is used to get the payment information by ID.

Rest Route

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

/v1/listingpayment/:sys_listingPaymentId

Rest Request Parameters

The getListingPayment api has got 1 regular request parameter

Parameter Type Required Population
sys_listingPaymentId ID true request.params?.[“sys_listingPaymentId”]
sys_listingPaymentId : 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/listingpayment/:sys_listingPaymentId

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

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_listingPayment",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"sys_listingPayment": {
		"id": "ID",
		"ownerId": "ID",
		"orderId": "ID",
		"paymentId": "String",
		"paymentStatus": "String",
		"statusLiteral": "String",
		"redirectUrl": "String",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

List Listingpayments API

This route is used to list all payments.

Rest Route

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

/v1/listingpayments

Rest Request Parameters

Filter Parameters

The listListingPayments api supports 6 optional filter parameters for filtering list results:

ownerId (ID): An ID value to represent owner user who created the order

orderId (ID): an ID value to represent the orderId which is the ID parameter of the source listing object

paymentId (String): A String value to represent the paymentId which is generated on the Stripe gateway. This id may represent different objects due to the payment gateway and the chosen flow type

paymentStatus (String): A string value to represent the payment status which belongs to the lifecyle of a Stripe payment.

statusLiteral (String): A string value to represent the logical payment status which belongs to the application lifecycle itself.

redirectUrl (String): A string value to represent return page of the frontend to show the result of the payment, this is used when the callback is made to server not the client.

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

  axios({
    method: 'GET',
    url: '/v1/listingpayments',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section above)
        // ownerId: '<value>' // Filter by ownerId
        // orderId: '<value>' // Filter by orderId
        // paymentId: '<value>' // Filter by paymentId
        // paymentStatus: '<value>' // Filter by paymentStatus
        // statusLiteral: '<value>' // Filter by statusLiteral
        // redirectUrl: '<value>' // Filter by redirectUrl
            }
  });

REST Response

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

Create Listingpayment API

This route is used to create a new payment.

Rest Route

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

/v1/listingpayment

Rest Request Parameters

The createListingPayment api has got 5 regular request parameters

Parameter Type Required Population
orderId ID true request.body?.[“orderId”]
paymentId String true request.body?.[“paymentId”]
paymentStatus String true request.body?.[“paymentStatus”]
statusLiteral String true request.body?.[“statusLiteral”]
redirectUrl String false request.body?.[“redirectUrl”]
orderId : an ID value to represent the orderId which is the ID parameter of the source listing object
paymentId : A String value to represent the paymentId which is generated on the Stripe gateway. This id may represent different objects due to the payment gateway and the chosen flow type
paymentStatus : A string value to represent the payment status which belongs to the lifecyle of a Stripe payment.
statusLiteral : A string value to represent the logical payment status which belongs to the application lifecycle itself.
redirectUrl : A string value to represent return page of the frontend to show the result of the payment, this is used when the callback is made to server not the client.

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

  axios({
    method: 'POST',
    url: '/v1/listingpayment',
    data: {
            orderId:"ID",  
            paymentId:"String",  
            paymentStatus:"String",  
            statusLiteral:"String",  
            redirectUrl:"String",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_listingPayment",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"sys_listingPayment": {
		"id": "ID",
		"ownerId": "ID",
		"orderId": "ID",
		"paymentId": "String",
		"paymentStatus": "String",
		"statusLiteral": "String",
		"redirectUrl": "String",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Update Listingpayment API

This route is used to update an existing payment.

Rest Route

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

/v1/listingpayment/:sys_listingPaymentId

Rest Request Parameters

The updateListingPayment api has got 5 regular request parameters

Parameter Type Required Population
sys_listingPaymentId ID true request.params?.[“sys_listingPaymentId”]
paymentId String false request.body?.[“paymentId”]
paymentStatus String false request.body?.[“paymentStatus”]
statusLiteral String false request.body?.[“statusLiteral”]
redirectUrl String false request.body?.[“redirectUrl”]
sys_listingPaymentId : This id paremeter is used to select the required data object that will be updated
paymentId : A String value to represent the paymentId which is generated on the Stripe gateway. This id may represent different objects due to the payment gateway and the chosen flow type
paymentStatus : A string value to represent the payment status which belongs to the lifecyle of a Stripe payment.
statusLiteral : A string value to represent the logical payment status which belongs to the application lifecycle itself.
redirectUrl : A string value to represent return page of the frontend to show the result of the payment, this is used when the callback is made to server not the client.

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

  axios({
    method: 'PATCH',
    url: `/v1/listingpayment/${sys_listingPaymentId}`,
    data: {
            paymentId:"String",  
            paymentStatus:"String",  
            statusLiteral:"String",  
            redirectUrl:"String",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_listingPayment",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"sys_listingPayment": {
		"id": "ID",
		"ownerId": "ID",
		"orderId": "ID",
		"paymentId": "String",
		"paymentStatus": "String",
		"statusLiteral": "String",
		"redirectUrl": "String",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Delete Listingpayment API

This route is used to delete a payment.

Rest Route

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

/v1/listingpayment/:sys_listingPaymentId

Rest Request Parameters

The deleteListingPayment api has got 1 regular request parameter

Parameter Type Required Population
sys_listingPaymentId ID true request.params?.[“sys_listingPaymentId”]
sys_listingPaymentId : 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/listingpayment/:sys_listingPaymentId

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

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_listingPayment",
	"method": "DELETE",
	"action": "delete",
	"appVersion": "Version",
	"rowCount": 1,
	"sys_listingPayment": {
		"id": "ID",
		"ownerId": "ID",
		"orderId": "ID",
		"paymentId": "String",
		"paymentStatus": "String",
		"statusLiteral": "String",
		"redirectUrl": "String",
		"isActive": false,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Get Listingpaymentbyorderid API

This route is used to get the payment information by order id.

Rest Route

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

/v1/listingpaymentbyorderid/:orderId

Rest Request Parameters

The getListingPaymentByOrderId api has got 2 regular request parameters

Parameter Type Required Population
sys_listingPaymentId ID true request.params?.[“sys_listingPaymentId”]
orderId ID true request.params?.[“orderId”]
sys_listingPaymentId : This id paremeter is used to query the required data object.
orderId : an ID value to represent the orderId which is the ID parameter of the source listing object. The parameter is used to query data.

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

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

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_listingPayment",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"sys_listingPayment": {
		"id": "ID",
		"ownerId": "ID",
		"orderId": "ID",
		"paymentId": "String",
		"paymentStatus": "String",
		"statusLiteral": "String",
		"redirectUrl": "String",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Get Listingpaymentbypaymentid API

This route is used to get the payment information by payment id.

Rest Route

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

/v1/listingpaymentbypaymentid/:paymentId

Rest Request Parameters

The getListingPaymentByPaymentId api has got 2 regular request parameters

Parameter Type Required Population
sys_listingPaymentId ID true request.params?.[“sys_listingPaymentId”]
paymentId String true request.params?.[“paymentId”]
sys_listingPaymentId : This id paremeter is used to query the required data object.
paymentId : A String value to represent the paymentId which is generated on the Stripe gateway. This id may represent different objects due to the payment gateway and the chosen flow type. The parameter is used to query data.

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

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

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_listingPayment",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"sys_listingPayment": {
		"id": "ID",
		"ownerId": "ID",
		"orderId": "ID",
		"paymentId": "String",
		"paymentStatus": "String",
		"statusLiteral": "String",
		"redirectUrl": "String",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Start Listingpayment API

Start payment for listing

Rest Route

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

/v1/startlistingpayment/:listingId

Rest Request Parameters

The startListingPayment api has got 2 regular request parameters

Parameter Type Required Population
listingId ID true request.params?.[“listingId”]
paymentUserParams Object false request.body?.[“paymentUserParams”]
listingId : This id paremeter is used to select the required data object that will be updated
paymentUserParams : The user parameters that should be defined to start a stripe payment process

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

  axios({
    method: 'PATCH',
    url: `/v1/startlistingpayment/${listingId}`,
    data: {
            paymentUserParams:"Object",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "listing",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"listing": {
		"id": "ID",
		"attributes": "Object",
		"categoryId": "ID",
		"condition": "Enum",
		"condition_idx": "Integer",
		"contactEmail": "String",
		"contactPhone": "String",
		"currency": "String",
		"description": "Text",
		"expiresAt": "Date",
		"favoriteCount": "Integer",
		"isPremium": "Boolean",
		"listingType": "Enum",
		"listingType_idx": "Integer",
		"locationId": "ID",
		"_paymentConfirmation": "String",
		"premiumExpiry": "Date",
		"premiumType": "Enum",
		"premiumType_idx": "Integer",
		"price": "Double",
		"status": "Enum",
		"status_idx": "Integer",
		"subcategoryId": "ID",
		"title": "String",
		"userId": "ID",
		"viewsCount": "Integer",
		"paymentConfirmation": "Enum",
		"paymentConfirmation_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	},
	"paymentResult": {
		"paymentTicketId": "ID",
		"orderId": "ID",
		"paymentId": "String",
		"paymentStatus": "Enum",
		"paymentIntentInfo": "Object",
		"statusLiteral": "String",
		"amount": "Double",
		"currency": "String",
		"success": true,
		"description": "String",
		"metadata": "Object",
		"paymentUserParams": "Object"
	}
}

Refresh Listingpayment API

Refresh payment info for listing from Stripe

Rest Route

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

/v1/refreshlistingpayment/:listingId

Rest Request Parameters

The refreshListingPayment api has got 2 regular request parameters

Parameter Type Required Population
listingId ID true request.params?.[“listingId”]
paymentUserParams Object false request.body?.[“paymentUserParams”]
listingId : This id paremeter is used to select the required data object that will be updated
paymentUserParams : The user parameters that should be defined to refresh a stripe payment process

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

  axios({
    method: 'PATCH',
    url: `/v1/refreshlistingpayment/${listingId}`,
    data: {
            paymentUserParams:"Object",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "listing",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"listing": {
		"id": "ID",
		"attributes": "Object",
		"categoryId": "ID",
		"condition": "Enum",
		"condition_idx": "Integer",
		"contactEmail": "String",
		"contactPhone": "String",
		"currency": "String",
		"description": "Text",
		"expiresAt": "Date",
		"favoriteCount": "Integer",
		"isPremium": "Boolean",
		"listingType": "Enum",
		"listingType_idx": "Integer",
		"locationId": "ID",
		"_paymentConfirmation": "String",
		"premiumExpiry": "Date",
		"premiumType": "Enum",
		"premiumType_idx": "Integer",
		"price": "Double",
		"status": "Enum",
		"status_idx": "Integer",
		"subcategoryId": "ID",
		"title": "String",
		"userId": "ID",
		"viewsCount": "Integer",
		"paymentConfirmation": "Enum",
		"paymentConfirmation_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	},
	"paymentResult": {
		"paymentTicketId": "ID",
		"orderId": "ID",
		"paymentId": "String",
		"paymentStatus": "Enum",
		"paymentIntentInfo": "Object",
		"statusLiteral": "String",
		"amount": "Double",
		"currency": "String",
		"success": true,
		"description": "String",
		"metadata": "Object",
		"paymentUserParams": "Object"
	}
}

Callback Listingpayment API

Refresh payment values by gateway webhook call for listing

Rest Route

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

/v1/callbacklistingpayment

Rest Request Parameters

The callbackListingPayment api has got 1 regular request parameter

Parameter Type Required Population
listingId ID true request.body?.[“listingId”]
listingId : The order id parameter that will be read from webhook callback params

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

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

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "listing",
	"method": "POST",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"listing": {
		"id": "ID",
		"attributes": "Object",
		"categoryId": "ID",
		"condition": "Enum",
		"condition_idx": "Integer",
		"contactEmail": "String",
		"contactPhone": "String",
		"currency": "String",
		"description": "Text",
		"expiresAt": "Date",
		"favoriteCount": "Integer",
		"isPremium": "Boolean",
		"listingType": "Enum",
		"listingType_idx": "Integer",
		"locationId": "ID",
		"_paymentConfirmation": "String",
		"premiumExpiry": "Date",
		"premiumType": "Enum",
		"premiumType_idx": "Integer",
		"price": "Double",
		"status": "Enum",
		"status_idx": "Integer",
		"subcategoryId": "ID",
		"title": "String",
		"userId": "ID",
		"viewsCount": "Integer",
		"paymentConfirmation": "Enum",
		"paymentConfirmation_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	},
	"paymentResult": {
		"paymentTicketId": "ID",
		"orderId": "ID",
		"paymentId": "String",
		"paymentStatus": "Enum",
		"paymentIntentInfo": "Object",
		"statusLiteral": "String",
		"amount": "Double",
		"currency": "String",
		"success": true,
		"description": "String",
		"metadata": "Object",
		"paymentUserParams": "Object"
	}
}

Get Paymentcustomerbyuserid API

This route is used to get the payment customer information by user id.

Rest Route

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

/v1/paymentcustomers/:userId

Rest Request Parameters

The getPaymentCustomerByUserId api has got 2 regular request parameters

Parameter Type Required Population
sys_paymentCustomerId ID true request.params?.[“sys_paymentCustomerId”]
userId ID true request.params?.[“userId”]
sys_paymentCustomerId : This id paremeter is used to query the required data object.
userId : An ID value to represent the user who is created as a stripe customer. The parameter is used to query data.

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

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

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_paymentCustomer",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"sys_paymentCustomer": {
		"id": "ID",
		"userId": "ID",
		"customerId": "String",
		"platform": "String",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

List Paymentcustomers API

This route is used to list all payment customers.

Rest Route

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

/v1/paymentcustomers

Rest Request Parameters

Filter Parameters

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

userId (ID): An ID value to represent the user who is created as a stripe customer

customerId (String): A string value to represent the customer id which is generated on the Stripe gateway. This id is used to represent the customer in the Stripe gateway

platform (String): A String value to represent payment platform which is used to make the payment. It is stripe as default. It will be used to distinguesh the payment gateways in the future.

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

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

REST Response

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

List Paymentcustomermethods API

This route is used to list all payment customer methods.

Rest Route

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

/v1/paymentcustomermethods/:userId

Rest Request Parameters

Filter Parameters

The listPaymentCustomerMethods api supports 6 optional filter parameters for filtering list results:

paymentMethodId (String): A string value to represent the id of the payment method on the payment platform.

customerId (String): A string value to represent the customer id which is generated on the payment gateway.

cardHolderName (String): A string value to represent the name of the card holder. It can be different than the registered customer.

cardHolderZip (String): A string value to represent the zip code of the card holder. It is used for address verification in specific countries.

platform (String): A String value to represent payment platform which teh paymentMethod belongs. It is stripe as default. It will be used to distinguesh the payment gateways in the future.

cardInfo (Object): A Json value to store the card details of the payment method.

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

  axios({
    method: 'GET',
    url: `/v1/paymentcustomermethods/${userId}`,
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section above)
        // paymentMethodId: '<value>' // Filter by paymentMethodId
        // customerId: '<value>' // Filter by customerId
        // cardHolderName: '<value>' // Filter by cardHolderName
        // cardHolderZip: '<value>' // Filter by cardHolderZip
        // platform: '<value>' // Filter by platform
        // cardInfo: '<value>' // Filter by cardInfo
            }
  });

REST Response

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

_fetch Listlisting API

System API to fetch list of listing records for frontend application. Auto-generated, not visible in design.

Rest Route

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

/v1/_fetchlistlisting

Rest Request Parameters

Filter Parameters

The _fetchListListing api supports 14 optional filter parameters for filtering list results:

categoryId (ID): Main category for the listing (categoryLocation:category).

condition (Enum): Item condition: new, used, other.

expiresAt (Date): UTC expiry for listing; after this, listing is automatically expired.

isPremium (Boolean): If true, the listing is premium (highlighted/pinned, eligible for special placement).

listingType (Enum): Type of listing (sale, rent, service, etc.).

locationId (ID): Location (categoryLocation:location).

premiumExpiry (Date): UTC date when premium status expires. Null if not premium or not applicable.

premiumType (Enum): Which premium package (gold, silver, none, etc.).

price (Double): Listing price.

status (Enum): Lifecycle status: pending_review, active, denied, sold, expired, deleted.

subcategoryId (ID): Subcategory for the listing, can be null for top-level (categoryLocation:category).

title (String): Listing title, short and clear.

userId (ID): Owner (poster) of the listing (auth:user).

paymentConfirmation (Enum): An automatic property that is used to check the confirmed status of the payment set by webhooks.

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

  axios({
    method: 'GET',
    url: '/v1/_fetchlistlisting',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section above)
        // categoryId: '<value>' // Filter by categoryId
        // condition: '<value>' // Filter by condition
        // expiresAt: '<value>' // Filter by expiresAt
        // isPremium: '<value>' // Filter by isPremium
        // listingType: '<value>' // Filter by listingType
        // locationId: '<value>' // Filter by locationId
        // premiumExpiry: '<value>' // Filter by premiumExpiry
        // premiumType: '<value>' // Filter by premiumType
        // price: '<value>' // Filter by price
        // status: '<value>' // Filter by status
        // subcategoryId: '<value>' // Filter by subcategoryId
        // title: '<value>' // Filter by title
        // userId: '<value>' // Filter by userId
        // paymentConfirmation: '<value>' // Filter by paymentConfirmation
            }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "listings",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"listings": [
		{
			"id": "ID",
			"attributes": "Object",
			"categoryId": "ID",
			"condition": "Enum",
			"condition_idx": "Integer",
			"contactEmail": "String",
			"contactPhone": "String",
			"currency": "String",
			"description": "Text",
			"expiresAt": "Date",
			"favoriteCount": "Integer",
			"isPremium": "Boolean",
			"listingType": "Enum",
			"listingType_idx": "Integer",
			"locationId": "ID",
			"_paymentConfirmation": "String",
			"premiumExpiry": "Date",
			"premiumType": "Enum",
			"premiumType_idx": "Integer",
			"price": "Double",
			"status": "Enum",
			"status_idx": "Integer",
			"subcategoryId": "ID",
			"title": "String",
			"userId": "ID",
			"viewsCount": "Integer",
			"paymentConfirmation": "Enum",
			"paymentConfirmation_idx": "Integer",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID",
			"mainCategory": [
				{
					"description": "Text",
					"icon": "String",
					"name": "String",
					"parentCategoryId": "ID",
					"slug": "String",
					"sortOrder": "Integer"
				},
				{},
				{}
			],
			"location": [
				{
					"city": "String",
					"country": "String",
					"district": "String",
					"latitude": "Double",
					"longitude": "Double",
					"postalCode": "String"
				},
				{},
				{}
			],
			"subCategory": [
				{
					"description": "Text",
					"icon": "String",
					"name": "String",
					"parentCategoryId": "ID",
					"slug": "String",
					"sortOrder": "Integer"
				},
				{},
				{}
			],
			"user": [
				{
					"fullname": "String"
				},
				{},
				{}
			]
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

_fetch Listsys_listingpayment API

System API to fetch list of sys_listingPayment records for frontend application. Auto-generated, not visible in design.

Rest Route

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

/v1/_fetchlistsys_listingpayment

Rest Request Parameters

Filter Parameters

The _fetchListSys_listingPayment api supports 6 optional filter parameters for filtering list results:

ownerId (ID): An ID value to represent owner user who created the order

orderId (ID): an ID value to represent the orderId which is the ID parameter of the source listing object

paymentId (String): A String value to represent the paymentId which is generated on the Stripe gateway. This id may represent different objects due to the payment gateway and the chosen flow type

paymentStatus (String): A string value to represent the payment status which belongs to the lifecyle of a Stripe payment.

statusLiteral (String): A string value to represent the logical payment status which belongs to the application lifecycle itself.

redirectUrl (String): A string value to represent return page of the frontend to show the result of the payment, this is used when the callback is made to server not the client.

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

  axios({
    method: 'GET',
    url: '/v1/_fetchlistsys_listingpayment',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section above)
        // ownerId: '<value>' // Filter by ownerId
        // orderId: '<value>' // Filter by orderId
        // paymentId: '<value>' // Filter by paymentId
        // paymentStatus: '<value>' // Filter by paymentStatus
        // statusLiteral: '<value>' // Filter by statusLiteral
        // redirectUrl: '<value>' // Filter by redirectUrl
            }
  });

REST Response

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

_fetch Listsys_paymentcustomer API

System API to fetch list of sys_paymentCustomer records for frontend application. Auto-generated, not visible in design.

Rest Route

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

/v1/_fetchlistsys_paymentcustomer

Rest Request Parameters

Filter Parameters

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

userId (ID): An ID value to represent the user who is created as a stripe customer

customerId (String): A string value to represent the customer id which is generated on the Stripe gateway. This id is used to represent the customer in the Stripe gateway

platform (String): A String value to represent payment platform which is used to make the payment. It is stripe as default. It will be used to distinguesh the payment gateways in the future.

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

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

REST Response

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

_fetch Listsys_paymentmethod API

System API to fetch list of sys_paymentMethod records for frontend application. Auto-generated, not visible in design.

Rest Route

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

/v1/_fetchlistsys_paymentmethod

Rest Request Parameters

Filter Parameters

The _fetchListSys_paymentMethod api supports 7 optional filter parameters for filtering list results:

paymentMethodId (String): A string value to represent the id of the payment method on the payment platform.

userId (ID): An ID value to represent the user who owns the payment method

customerId (String): A string value to represent the customer id which is generated on the payment gateway.

cardHolderName (String): A string value to represent the name of the card holder. It can be different than the registered customer.

cardHolderZip (String): A string value to represent the zip code of the card holder. It is used for address verification in specific countries.

platform (String): A String value to represent payment platform which teh paymentMethod belongs. It is stripe as default. It will be used to distinguesh the payment gateways in the future.

cardInfo (Object): A Json value to store the card details of the payment method.

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

  axios({
    method: 'GET',
    url: '/v1/_fetchlistsys_paymentmethod',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section above)
        // paymentMethodId: '<value>' // Filter by paymentMethodId
        // userId: '<value>' // Filter by userId
        // customerId: '<value>' // Filter by customerId
        // cardHolderName: '<value>' // Filter by cardHolderName
        // cardHolderZip: '<value>' // Filter by cardHolderZip
        // platform: '<value>' // Filter by platform
        // cardInfo: '<value>' // Filter by cardInfo
            }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_paymentMethods",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"sys_paymentMethods": [
		{
			"id": "ID",
			"paymentMethodId": "String",
			"userId": "ID",
			"customerId": "String",
			"cardHolderName": "String",
			"cardHolderZip": "String",
			"platform": "String",
			"cardInfo": "Object",
			"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.


Listing Service Listing Payment Flow

CLONESAHIBINDEN

FRONTEND GUIDE FOR AI CODING AGENTS - PART 11 - Listing Service Listing Payment Flow

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

Stripe Payment Flow For Listing

Listing is a data object that stores order information used for Stripe payments. The payment flow can only start after an instance of this data object is created in the database.

The ID of this data object—referenced as listingId in the general business logic—will be used as the orderId in the payment flow.

Accessing the service API for the payment flow API

The Clonesahibinden application doesn’t have a separate payment service; the payment flow is handled within the same service that manages orders. To access the related APIs, use the base URL of the listing service. Note that the application may be deployed to Preview, Staging, or Production. As with all API access, you should call the API using the base URL for the selected deployment.

For the listing service, the base URLs are:

Creating the Listing

While creating the listing instance is part of the business logic and can be implemented according to your architecture, this instance acts as the central hub for the payment flow and its related data objects. The order object is typically created via its own API (see the Business API for the create route of listing). The payment flow begins after the object is created.

Because of the data object’s Stripe order settings, the payment flow is aware of the following fields, references, and their purposes:

Before Payment Flow Starts

It is assumed that the frontend provides a “Pay” or “Checkout” button that initiates the payment flow. The following steps occur after the user clicks this button.
Note that an listing instance must already exist to represent the order being paid, with its initial status set.

A Stripe payment flow can be implemented in several ways, but the best practice is to use a PaymentIntent and manage it jointly from the backend and frontend.
A PaymentIntent represents the intent to collect payment for a given order (or any payable entity).
In the Clonesahibinden application, the PaymentIntent is created in the backend, while the PaymentMethod (the user’s stored card information) is created in the frontend.
Only the PaymentMethod ID and minimal metadata are stored in the backend for later reference.

The frontend first requests the current user’s saved payment methods from the backend, displays them in a list, and provides UI options to add or remove payment methods.
The user must select a Payment Method before starting the payment flow.

Listing the Payment Methods for the User

To list the payment methods of the currently logged-in user, call the following system API (unversioned):

GET /payment-methods/list

This endpoint requires no parameters and returns an array of payment methods belonging to the user — without any envelope.

const response = await fetch("$serviceUrl/payment-methods/list", {
  method: "GET",
  headers: { "Content-Type": "application/json" },
});

Example response:

[
  {
    "id": "19a5fbfd-3c25-405b-a7f7-06f023f2ca01",
    "paymentMethodId": "pm_1SQv9CP5uUv56Cse5BQ3nGW8",
    "userId": "f7103b85-fcda-4dec-92c6-c336f71fd3a2",
    "customerId": "cus_TNgWUw5QkmUPLa",
    "cardHolderName": "John Doe",
    "cardHolderZip": "34662",
    "platform": "stripe",
    "cardInfo": {
      "brand": "visa",
      "last4": "4242",
      "checks": {
        "cvc_check": "pass",
        "address_postal_code_check": "pass"
      },
      "funding": "credit",
      "exp_month": 11,
      "exp_year": 2033
    },
    "isActive": true,
    "createdAt": "2025-11-07T19:16:38.469Z",
    "updatedAt": "2025-11-07T19:16:38.469Z",
    "_owner": "f7103b85-fcda-4dec-92c6-c336f71fd3a2"
  }
]

In each payment method object, the following fields are useful for displaying to the user:

for (const method of paymentMethods) {
  const brand = method.cardInfo.brand; // use brand for displaying VISA/MASTERCARD icons
  const paymentMethodId = method.paymentMethodId; // send this when initiating the payment flow
  const cardHolderName = method.cardHolderName; // show in list
  const number = `**** **** **** ${method.cardInfo.last4}`; // masked card number
  const expDate = `${method.cardInfo.exp_month}/${method.cardInfo.exp_year}`; // expiry date
  const id = method.id; // internal DB record ID, used for deletion
  const customerId = method.customerId; // Stripe customer reference
}

If the list is empty, prompt the user to add a new payment method.

Creating a Payment Method

The payment page (or user profile page) should allow users to add a new payment method (credit card). Creating a Payment Method is a secure operation handled entirely through Stripe.js on the frontend — the backend never handles sensitive card data. After a card is successfully created, the backend only stores its reference (PaymentMethod ID) for reuse.

Stripe provides multiple ways to collect card information, all through secure UI elements. Below is an example setup — refer to the latest Stripe documentation for alternative patterns.

To initialize Stripe on the frontend, include your public key:

<script src="https://js.stripe.com/v3/?advancedFraudSignals=false"></script>
const stripe = Stripe("pk_test_51POkqt4..................");
const elements = stripe.elements();

const cardNumberElement = elements.create("cardNumber", {
  style: { base: { color: "#545454", fontSize: "16px" } },
});
cardNumberElement.mount("#card-number-element");

const cardExpiryElement = elements.create("cardExpiry", {
  style: { base: { color: "#545454", fontSize: "16px" } },
});
cardExpiryElement.mount("#card-expiry-element");

const cardCvcElement = elements.create("cardCvc", {
  style: { base: { color: "#545454", fontSize: "16px" } },
});
cardCvcElement.mount("#card-cvc-element");

// Note: cardholder name and ZIP code are collected via non-Stripe inputs (not secure).

You can dynamically show the card brand while typing:

cardNumberElement.on("change", (event) => {
  const cardBrand = event.brand;
  const cardNumberDiv = document.getElementById("card-number-element");
  cardNumberDiv.style.backgroundImage = getBrandImageUrl(cardBrand);
});

Once the user completes the card form, create the Payment Method on Stripe. Note that the expiry and CVC fields are securely handled by Stripe.js and are never readable from your code.

const { paymentMethod, error } = await stripe.createPaymentMethod({
  type: "card",
  card: cardNumberElement,
  billing_details: {
    name: cardholderName.value,
    address: { postal_code: cardholderZip.value },
  },
});

When a paymentMethod is successfully created, send its ID to your backend to attach it to the logged-in user’s account.

Use the system API (unversioned):

POST /payment-methods/add

Example:

const response = await fetch("$serviceUrl/payment-methods/add", {
  method: "POST",
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({ paymentMethodId: paymentMethod.id }),
});

When addPaymentMethod is called, the backend retrieves or creates the user’s Stripe Customer ID, attaches the Payment Method to that customer, and stores the reference in the local database for future use.

Example response:

{
  "isActive": true,
  "cardHolderName": "John Doe",
  "userId": "f7103b85-fcda-4dec-92c6-c336f71fd3a2",
  "customerId": "cus_TNgWUw5QkmUPLa",
  "paymentMethodId": "pm_1SQw5aP5uUv56CseDGzT1dzP",
  "platform": "stripe",
  "cardHolderZip": "34662",
  "cardInfo": {
    "brand": "visa",
    "last4": "4242",
    "funding": "credit",
    "exp_month": 11,
    "exp_year": 2033
  },
  "id": "19a5ff70-4986-4760-8fc4-6b591bd6bbbf",
  "createdAt": "2025-11-07T20:16:55.451Z",
  "updatedAt": "2025-11-07T20:16:55.451Z"
}

You can append this new entry directly to the UI list or refresh the list using the listPaymentMethods API.

Deleting a Payment Method

To remove a saved payment method from the current user’s account, call the system API (unversioned):

DELETE /payment-methods/delete/:paymentMethodId

Example:

await fetch(
  `$serviceUrl/payment-methods/delete/${paymentMethodId}`,
  {
    method: "DELETE",
    headers: { "Content-Type": "application/json" },
  }
);

Starting the Payment Flow in Backend — Creation and Confirmation of the PaymentIntent Object

The payment flow is initiated in the backend through the startListingPayment API.
This API must be called with one of the user’s existing payment methods. Therefore, ensure that the frontend forces the user to select a payment method before initiating the payment.

The startListingPayment API is a versioned Business Logic API and follows the same structure as other business APIs.

In the Clonesahibinden application, the payment flow starts by creating a Stripe PaymentIntent and confirming it in a single step within the backend.
In a typical (“happy”) path, when the startListingPayment API is called, the response will include a successful or failed PaymentIntent result inside the paymentResult object, along with the listing object.

However, in certain edge cases—such as when 3D Secure (3DS) or other bank-level authentication is required—the confirmation step cannot complete immediately.
In such cases, control should return to a frontend page to allow the user to finish the process.
To enable this, a return_url must be provided during the PaymentIntent creation step.

Although technically optional, it is strongly recommended to include a return_url.
This ensures that the frontend payment result page can display both successful and failed payments and complete flows that require user interaction.
The return_url must be a frontend URL.

The paymentUserParams parameter of the startListingPayment API contains the data necessary to create the Stripe PaymentIntent.

Call the API as follows:

const response = await fetch(
  `$serviceUrl/v1/startlistingpayment/${orderId}`,
  {
    method: "PATCH",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      paymentUserParams: {
        paymentMethodId,
        return_url: `${yourFrontendReturnUrl}`,
      },
    }),
  }
);

The API response will contain a paymentResult object. If an error occurs, it will begin with { "result": "ERR" }. Otherwise, it will include the PaymentIntent information:

{
  "paymentResult": {
    "success": true,
    "paymentTicketId": "19a60f8f-eeff-43a2-9954-58b18839e1da",
    "orderId": "19a60f84-56ee-40c4-b9c1-392f83877838",
    "paymentId": "pi_3SR0UHP5uUv56Cse1kwQWCK8",
    "paymentStatus": "succeeded",
    "paymentIntentInfo": {
      "paymentIntentId": "pi_3SR0UHP5uUv56Cse1kwQWCK8",
      "clientSecret": "pi_3SR0UHP5uUv56Cse1kwQWCK8_secret_PTc3DriD0YU5Th4isBepvDWdg",
      "publicKey": "pk_test_51POkqWP5uU",
      "status": "succeeded"
    },
    "statusLiteral": "success",
    "amount": 10,
    "currency": "USD",
    "description": "Your credit card is charged for babilOrder for 10",
    "metadata": {
      "order": "Purchase-Purchase-order",
      "orderId": "19a60f84-56ee-40c4-b9c1-392f83877838",
      "checkoutName": "babilOrder"
    },
    "paymentUserParams": {
      "paymentMethodId": "pm_1SQw5aP5uUv56CseDGzT1dzP",
      "return_url": "${yourFrontendReturnUrl}"
    }
  }
}

Start Listingpayment API

Start payment for listing

Rest Route

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

/v1/startlistingpayment/:listingId

Rest Request Parameters

The startListingPayment api has got 2 regular request parameters

Parameter Type Required Population
listingId ID true request.params?.[“listingId”]
paymentUserParams Object false request.body?.[“paymentUserParams”]
listingId : This id paremeter is used to select the required data object that will be updated
paymentUserParams : The user parameters that should be defined to start a stripe payment process

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

  axios({
    method: 'PATCH',
    url: `/v1/startlistingpayment/${listingId}`,
    data: {
            paymentUserParams:"Object",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "listing",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"listing": {
		"id": "ID",
		"attributes": "Object",
		"categoryId": "ID",
		"condition": "Enum",
		"condition_idx": "Integer",
		"contactEmail": "String",
		"contactPhone": "String",
		"currency": "String",
		"description": "Text",
		"expiresAt": "Date",
		"favoriteCount": "Integer",
		"isPremium": "Boolean",
		"listingType": "Enum",
		"listingType_idx": "Integer",
		"locationId": "ID",
		"_paymentConfirmation": "String",
		"premiumExpiry": "Date",
		"premiumType": "Enum",
		"premiumType_idx": "Integer",
		"price": "Double",
		"status": "Enum",
		"status_idx": "Integer",
		"subcategoryId": "ID",
		"title": "String",
		"userId": "ID",
		"viewsCount": "Integer",
		"paymentConfirmation": "Enum",
		"paymentConfirmation_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	},
	"paymentResult": {
		"paymentTicketId": "ID",
		"orderId": "ID",
		"paymentId": "String",
		"paymentStatus": "Enum",
		"paymentIntentInfo": "Object",
		"statusLiteral": "String",
		"amount": "Double",
		"currency": "String",
		"success": true,
		"description": "String",
		"metadata": "Object",
		"paymentUserParams": "Object"
	}
}

Analyzing the API Response

After calling the startListingPayment API, the most common expected outcome is a confirmed and completed payment. However, several alternate cases should be handled on the frontend.

System Error Case

The API may return a classic service-level error (unrelated to payment). Check the HTTP status code of the response. It should be 200 or 201. Any 400, 401, 403, or 404 indicates a system error.

{
  "result": "ERR",
  "status": 404,
  "message": "Record not found",
  "date": "2025-11-08T00:57:54.820Z"
}

Handle system errors on the payment page (show a retry option). Do not navigate to the result page.

Payment Error Case

The API performs both database operations and the Stripe payment operation. If the payment fails but the service logic succeeds, the API may still return a 200 OK status, with the failure recorded in the paymentResult.

In this case, show an error message and allow the user to retry.

{
  "status": "OK",
  "statusCode": "200",
  "listing": {
    "id": "19a60f8f-eeff-43a2-9954-58b18839e1da",
    "status": "failed"
  },
  "paymentResult": {
    "result": "ERR",
    "status": 500,
    "message": "Stripe error message: Your card number is incorrect.",
    "errCode": "invalid_number",
    "date": "2025-11-08T00:57:54.820Z"
  }
}

Payment errors should be handled on the payment page (retry option). Do not go to the result page.


Happy Case

When both the service and payment result succeed, this is considered the happy path. In this case, use the listing and paymentResult objects in the response to display a success message to the user.

amount and description values are included to help you show payment details on the result page.

{
  "status": "OK",
  "statusCode": "200",
  "order": {
    "id": "19a60f8f-eeff-43a2-9954-58b18839e1da",
    "status": "paid"
  },
  "paymentResult": {
    "success": true,
    "paymentStatus": "succeeded",
    "paymentIntentInfo": {
      "status": "succeeded"
    },
    "amount": 10,
    "currency": "USD",
    "description": "Your credit card is charged for babilOrder for 10"
  }
}

To verify success:

if (paymentResult.paymentIntentInfo.status === "succeeded") {
  // Redirect to result page
}

Note: A successful result does not trigger fulfillment immediately. Fulfillment begins only after the Stripe webhook updates the database. It’s recommended to show a short “success” toast, wait a few milliseconds, and then navigate to the result page.

Handle the happy case in the result page by sending the listingId and the payment intent secret.

const orderId = new URLSearchParams(window.location.search).get("orderId");
const url = new URL(`$yourResultPageUrl`, location.origin);
url.searchParams.set("orderId", orderId);
url.searchParams.set("payment_intent_client_secret", currentPaymentIntent.clientSecret);
setTimeout(() => { window.location.href = url.toString(); }, 600);

Edge Cases

Although startListingPayment is designed to handle both creation and confirmation in one step, Stripe may return an incomplete result if third-party authentication or redirect steps are required.

You must handle these cases in both the payment page and the result page, because some next actions are available immediately, while others occur only after a redirect.

If the paymentIntentInfo.status equals "requires_action", handle it using Stripe.js as shown below:

if (paymentResult.paymentIntentInfo.status === "requires_action") {
  await runNextAction(
    paymentResult.paymentIntentInfo.clientSecret,
    paymentResult.paymentIntentInfo.publicKey
  );
}

Helper function:

async function runNextAction(clientSecret, publicKey) {
  const stripe = Stripe(publicKey);
  const { error } = await stripe.handleNextAction({ clientSecret });
  if (error) {
    console.log("next_action error:", error);
    showToast(error.code + ": " + error.message, "fa-circle-xmark text-red-500");
    throw new Error(error.message);
  }
}

After handling the next action, re-fetch the PaymentIntent from Stripe, evaluate its status, show appropriate feedback, and navigate to the result page.

const { paymentIntent } = await stripe.retrievePaymentIntent(clientSecret);

if (paymentIntent.status === "succeeded") {
  showToast("Payment successful!", "fa-circle-check text-green-500");
} else if (paymentIntent.status === "processing") {
  showToast("Payment is processing…", "fa-circle-info text-blue-500");
} else if (paymentIntent.status === "requires_payment_method") {
  showToast("Payment failed. Try another card.", "fa-circle-xmark text-red-500");
}

const orderId = new URLSearchParams(window.location.search).get("orderId");
const url = new URL(`$yourResultPageUrl`, location.origin);
url.searchParams.set("orderId", orderId);
url.searchParams.set("payment_intent_client_secret", currentPaymentIntent.clientSecret);
setTimeout(() => { window.location.href = url.toString(); }, 600);

The Result Page

The payment result page should handle the following steps:

  1. Read orderId and payment_intent_client_secret from the query parameters.
  2. Retrieve the PaymentIntent from Stripe and check its status.
  3. If required, handle any next_action and re-fetch the PaymentIntent.
  4. If the status is "succeeded", display a clear visual confirmation.
  5. Fetch the listing instance from the backend to display any additional order or fulfillment details.

Note that paymentIntent status only gives information about the Stripe side. The listing instance in the service should also ve updated to start the fulfillment. In most cases, the startlistingPayment api updates the status of the order using the response of the paymentIntent confirmation, but as stated above in some cases this update can be done only when the webhook executes. So in teh result page always get the final payment status in the `listing.

To ensure that service i To fetch the listing instance, you van use the related api which is given before, and to ensure that the service is updated with the latest status read the paymentConfirmation field of the listing instance.

if (listing.paymentConfirmation == "canceled") {
  // the payment is canceled, user can be informed that they should try again
} if (listing.paymentConfirmation == "paid") {
  // service knows that payment is done, user can be informed that fullfillment started
} else {
  // it may be pending, processing
  // Fetch the object again until a canceled or paid status
}

Payment Flow via MCP (AI Chat Integration)

The payment flow is also accessible through the MCP (Model Context Protocol) AI chat interface. The listing service exposes an initiatePayment MCP tool that the AI can call when the user wants to pay for an order.

How initiatePayment Works in MCP

  1. User asks to pay — e.g., “I want to pay for my order”
  2. AI calls initiatePayment MCP tool with orderId (and orderType if multiple order types exist)
  3. Tool validates the order exists, is payable, and the user is authorized
  4. Tool returns __frontendAction with type: "payment" — this is NOT a direct payment execution
  5. Frontend chat UI renders a PaymentActionCard with a “Pay Now” button
  6. User clicks “Pay Now” — the frontend opens a payment modal with CheckoutForm
  7. Standard Stripe flow proceeds (payment method selection, 3DS handling, etc.)

Frontend Action Response Format

The initiatePayment MCP tool returns:

{
  "__frontendAction": {
    "type": "payment",
    "orderId": "uuid",
    "orderType": "listing",
    "serviceName": "listing",
    "amount": 99.99,
    "currency": "USD",
    "description": "Order description"
  },
  "message": "Payment is ready. Click the button below to proceed."
}

MCP Client Architecture

The frontend communicates with MCP tools through the MCP BFF (Backend-for-Frontend) service. The MCP BFF aggregates tool calls across all backend services and provides:

The PaymentActionCard component handles the rest: fetching order details, rendering the payment UI, and completing the Stripe checkout flow — all within the chat interface.


ListingImage Service

CLONESAHIBINDEN

FRONTEND GUIDE FOR AI CODING AGENTS - PART 12 - ListingImage Service

This document is a part of a REST API guide for the clonesahibinden 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 listingImage

Service Access

ListingImage service management is handled through service specific base urls.

ListingImage 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 listingImage service, the base URLs are:

Scope

ListingImage Service Description

Manages uploading, linking, ordering, and storing all images attached to classified listings. Enforces image file format, size, count, and metadata standards; supports multi-resolution handling and per-listing image count limits.

ListingImage service provides apis and business logic for following data objects in clonesahibinden 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.

listingImage Data Object: Stores metadata about each image attached to a classified listing, with enforced image count, format, size, and dimension constraints. Four separate URL fields for different resolutions. Tied to listing; managed by listing owner/admin/mod.

ListingImage Service Frontend Description By The Backend Architect

Each image attached to a listing is tracked via this service. Display order/sort of images is controlled via the sortOrder field. No more than 10 images are allowed for any listing, and only supported formats/size are accepted. Read-only access is public, create/update/delete is restricted to listing owner/admin/moderator. Images display in ordered gallery, with optional main/cover selection based on sortOrder=1. On exceeding image count or constraint errors, display informative error. Deletion is soft for restoration until the listing is removed or archived.

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"
}

Bucket Management

(This information is also given in PART 1 prompt.)

This application has a bucket service used to store user files and other object-related files. The bucket service is login-agnostic, so for write operations or private reads, include a bucket token (provided by services) in the request’s Authorization header as a Bearer token.

Please note that all other business services require the access token in the Bearer header, while the bucket service expects a bucket token because it is login-agnostic. Ensure you manage the required token injection properly; any auth interceptor should not replace the bucket token with the access token.

User Bucket This bucket stores public user files for each user.

When a user logs in—or in the /currentuser response—there is a userBucketToken to use when sending user-related public files to the bucket service.

{
  //...
  "userBucketToken": "e56d...."
}

To upload a file

POST {baseUrl}/bucket/upload

The request body is form-data which includes the bucketId and the file binary in the files field.

{
    bucketId: "{userId}-public-user-bucket",
    files: {binary}
}

Response status is 200 on success, e.g., body:

{
    "success": true,
    "data": [
        {
            "fileId": "9da03f6d-0409-41ad-bb06-225a244ae408",
            "originalName": "test (10).png",
            "mimeType": "image/png",
            "size": 604063,
            "status": "uploaded",
            "bucketName": "f7103b85-fcda-4dec-92c6-c336f71fd3a2-public-user-bucket",
            "isPublic": true,
            "downloadUrl": "https://babilcom.mindbricks.co/bucket/download/9da03f6d-0409-41ad-bb06-225a244ae408"
        }
    ]
}

To download a file from the bucket, you need its fileId. If you upload an avatar or other asset, ensure the download URL or the fileId is stored in the backend.

Buckets are mostly used in object creations that require an additional file, such as a product image or user avatar. After uploading your image to the bucket, insert the returned download URL into the related property of the target object record.

Application Bucket

This Clonesahibinden application also includes a common public bucket that anyone can read, but only users with the superAdmin, admin, or saasAdmin roles can write (upload) to it.

When a user with one of these admin roles is logged in, the /login response or the /currentuser response also returns an applicationBucketToken field, which is used when uploading any file to the application bucket.

{
  //...
  "applicationBucketToken": "e23fd...."
}

The common public application bucket ID is

"clonesahibinden-public-common-bucket"

In certain admin areas—such as product management pages—since the user already has the application bucket token, they will be able to upload related object images.

Please configure your UI to upload files to the application bucket using this bucket token whenever needed.

Object Buckets Some objects may also return a bucket token for uploading or accessing files related to that object. For example, in a project management application, when you fetch a project’s data, a public or private bucket token may be provided to upload or download project-related files.

These buckets will be used as described in the relevant object definitions.

ListingImage Data Object

Stores metadata about each image attached to a classified listing, with enforced image count, format, size, and dimension constraints. Four separate URL fields for different resolutions. Tied to listing; managed by listing owner/admin/mod.

ListingImage Data Object Frontend Description By The Backend Architect

Displays individual image information related to a listing, including all available sizes and original asset. Used in the gallery/carousel of listing details. Allows reordering (via sortOrder), and restricts total images per listing to 10. All constraints (file type, minimum/maximum dimensions, and size) must be checked before saving. Image deletion disables but does not erase record until listing is deleted. Main image is the one with the lowest sortOrder value.

ListingImage Data Object Properties

ListingImage 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
fileSize Integer false Yes No Size of the image file in bytes.
fullUrl String false Yes No URL to a full-res processed but possibly optimized image (e.g. with max side 1600px, for gallery display).
height Float false Yes No Height of the original image, in pixels.
listingId ID false Yes No The related listing that this image belongs to.
mediumUrl String false Yes No URL to the medium-sized processed image version (e.g. 400x300px or similar).
mimeType String false Yes No MIME type of the image (e.g., image/jpeg, image/png, image/webp, image/gif).
sortOrder Integer false Yes No Order value for display in UI; the lowest value image is the cover/main image.
thumbnailUrl String false Yes No URL to the thumbnail image (small size, e.g. 120x90px).
uploadedAt Date false Yes No UTC timestamp when image was uploaded to platform.
url String false Yes No URL to the original uploaded image file (full resolution/original).
width Float false Yes No Width of the original image, in pixels.

Relation Properties

listingId

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

Filter Properties

listingId

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.

ListingImage Default APIs

Operation API Name Route Explicitly Set
Create createListingImage /v1/listingimages Auto
Update updateListingImage /v1/listingimages/:listingImageId Auto
Delete deleteListingImage /v1/listingimages/:listingImageId Auto
Get getListingImage /v1/listingimages/:listingImageId Auto
List listListingImages /v1/listlistingimages/:listingId System

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 Listingimage API

Create an image record attached to a listing. Enforces max 10 images per listing, allowed file types (image/jpeg, png, webp, gif), max file size (10MB), and minimum dimensions (400x300px). Only owner of related listing, admin, or moderator can add.

API Frontend Description By The Backend Architect

Show file/image upload UI, allow per-image progress and preview, error on more than 10 images, reject unsupported types/sizes/resolutions. On success, show image in gallery. Only listing owner/moderator/admin may add images.

Rest Route

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

/v1/listingimages

Rest Request Parameters

The createListingImage api has got 11 regular request parameters

Parameter Type Required Population
fileSize Integer true request.body?.[“fileSize”]
fullUrl String true request.body?.[“fullUrl”]
height Float true request.body?.[“height”]
listingId ID true request.body?.[“listingId”]
mediumUrl String true request.body?.[“mediumUrl”]
mimeType String true request.body?.[“mimeType”]
sortOrder Integer true request.body?.[“sortOrder”]
thumbnailUrl String true request.body?.[“thumbnailUrl”]
uploadedAt Date true request.body?.[“uploadedAt”]
url String true request.body?.[“url”]
width Float true request.body?.[“width”]
fileSize : Size of the image file in bytes.
fullUrl : URL to a full-res processed but possibly optimized image (e.g. with max side 1600px, for gallery display).
height : Height of the original image, in pixels.
listingId : The related listing that this image belongs to.
mediumUrl : URL to the medium-sized processed image version (e.g. 400x300px or similar).
mimeType : MIME type of the image (e.g., image/jpeg, image/png, image/webp, image/gif).
sortOrder : Order value for display in UI; the lowest value image is the cover/main image.
thumbnailUrl : URL to the thumbnail image (small size, e.g. 120x90px).
uploadedAt : UTC timestamp when image was uploaded to platform.
url : URL to the original uploaded image file (full resolution/original).
width : Width of the original image, in pixels.

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

  axios({
    method: 'POST',
    url: '/v1/listingimages',
    data: {
            fileSize:"Integer",  
            fullUrl:"String",  
            height:"Float",  
            listingId:"ID",  
            mediumUrl:"String",  
            mimeType:"String",  
            sortOrder:"Integer",  
            thumbnailUrl:"String",  
            uploadedAt:"Date",  
            url:"String",  
            width:"Float",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "listingImage",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"listingImage": {
		"id": "ID",
		"fileSize": "Integer",
		"fullUrl": "String",
		"height": "Float",
		"listingId": "ID",
		"mediumUrl": "String",
		"mimeType": "String",
		"sortOrder": "Integer",
		"thumbnailUrl": "String",
		"uploadedAt": "Date",
		"url": "String",
		"width": "Float",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Delete Listingimage API

Remove (soft delete) this image record. Only admin, moderator, or owner of related listing may take action. Image stays in database; actual asset removal is scheduled or handled in listing/bucket image service.

API Frontend Description By The Backend Architect

Provide a delete/trash icon per image. Show immediate feedback on delete (soft delete). Remove from gallery and reflow grid/order. Deletion disables but does not erase image from DB or storage bucket (handled asynchronously).

Rest Route

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

/v1/listingimages/:listingImageId

Rest Request Parameters

The deleteListingImage api has got 1 regular request parameter

Parameter Type Required Population
listingImageId ID true request.params?.[“listingImageId”]
listingImageId : 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/listingimages/:listingImageId

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

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "listingImage",
	"method": "DELETE",
	"action": "delete",
	"appVersion": "Version",
	"rowCount": 1,
	"listingImage": {
		"id": "ID",
		"fileSize": "Integer",
		"fullUrl": "String",
		"height": "Float",
		"listingId": "ID",
		"mediumUrl": "String",
		"mimeType": "String",
		"sortOrder": "Integer",
		"thumbnailUrl": "String",
		"uploadedAt": "Date",
		"url": "String",
		"width": "Float",
		"isActive": false,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Get Listingimage API

Retrieve details/metadata of one image for a listing. Publicly accessible for gallery/carousel; has no sensitive info.

API Frontend Description By The Backend Architect

Used to fetch image details (URLs for all resolutions and display order) for single-image views. All users can access listing image detail for active listings.

Rest Route

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

/v1/listingimages/:listingImageId

Rest Request Parameters

The getListingImage api has got 1 regular request parameter

Parameter Type Required Population
listingImageId ID true request.params?.[“listingImageId”]
listingImageId : 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/listingimages/:listingImageId

  axios({
    method: 'GET',
    url: `/v1/listingimages/${listingImageId}`,
    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": "listingImage",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"listingImage": {
		"isActive": true
	}
}

List Listingimages API

List all images belonging to a specific listing, sorted by sortOrder ascending. Returns up to 10 images per listing. Publicly accessible for populating image galleries.

API Frontend Description By The Backend Architect

Display all images in a listing as a gallery or carousel, sorted by sortOrder (lowest/1 is main image/cover). Maximum images per listing is 10. Used on public listing detail pages and for listing management.

Rest Route

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

/v1/listlistingimages/:listingId

Rest Request Parameters

The listListingImages api has got 1 regular request parameter

Parameter Type Required Population
listingId ID true request.query?.[“listingId”]
listingId : The related listing that this image belongs to… The parameter is used to query data.

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

  axios({
    method: 'GET',
    url: `/v1/listlistingimages/${listingId}`,
    data: {
    
    },
    params: {
             listingId:'"ID"',  
    
        }
  });

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": "listingImages",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"listingImages": [
		{
			"isActive": true
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Update Listingimage API

Update sort order or image metadata; user is limited to manipulating images of their own listings (or admins/mods). Cannot move image to another listing. Can revalidate constraints on request.

API Frontend Description By The Backend Architect

Allow user to reorder images of a listing (changing sortOrder), set another main image (sortOrder=1), or update image metadata. Show error if trying to move image between listings or violate constraints.

Rest Route

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

/v1/listingimages/:listingImageId

Rest Request Parameters

The updateListingImage api has got 2 regular request parameters

Parameter Type Required Population
listingImageId ID true request.params?.[“listingImageId”]
sortOrder Integer false request.body?.[“sortOrder”]
listingImageId : This id paremeter is used to select the required data object that will be updated
sortOrder : Order value for display in UI; the lowest value image is the cover/main image.

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

  axios({
    method: 'PATCH',
    url: `/v1/listingimages/${listingImageId}`,
    data: {
            sortOrder:"Integer",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "listingImage",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"listingImage": {
		"id": "ID",
		"fileSize": "Integer",
		"fullUrl": "String",
		"height": "Float",
		"listingId": "ID",
		"mediumUrl": "String",
		"mimeType": "String",
		"sortOrder": "Integer",
		"thumbnailUrl": "String",
		"uploadedAt": "Date",
		"url": "String",
		"width": "Float",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

_fetch Listlistingimage API

System API to fetch list of listingImage records for frontend application. Auto-generated, not visible in design.

Rest Route

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

/v1/_fetchlistlistingimage

Rest Request Parameters

Filter Parameters

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

listingId (ID): The related listing that this image belongs to.

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

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

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "listingImages",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"listingImages": [
		{
			"id": "ID",
			"fileSize": "Integer",
			"fullUrl": "String",
			"height": "Float",
			"listingId": "ID",
			"mediumUrl": "String",
			"mimeType": "String",
			"sortOrder": "Integer",
			"thumbnailUrl": "String",
			"uploadedAt": "Date",
			"url": "String",
			"width": "Float",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID",
			"listing": [
				{
					"attributes": "Object",
					"categoryId": "ID",
					"condition": "Enum",
					"condition_idx": "Integer",
					"contactEmail": "String",
					"contactPhone": "String",
					"currency": "String",
					"description": "Text",
					"expiresAt": "Date",
					"favoriteCount": "Integer",
					"isPremium": "Boolean",
					"listingType": "Enum",
					"listingType_idx": "Integer",
					"locationId": "ID",
					"_paymentConfirmation": "String",
					"premiumExpiry": "Date",
					"premiumType": "Enum",
					"premiumType_idx": "Integer",
					"price": "Double",
					"status": "Enum",
					"status_idx": "Integer",
					"subcategoryId": "ID",
					"title": "String",
					"userId": "ID",
					"viewsCount": "Integer",
					"paymentConfirmation": "Enum",
					"paymentConfirmation_idx": "Integer"
				},
				{},
				{}
			]
		},
		{},
		{}
	],
	"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.


Payment Service

CLONESAHIBINDEN

FRONTEND GUIDE FOR AI CODING AGENTS - PART 13 - Payment Service

This document is a part of a REST API guide for the clonesahibinden 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 payment

Service Access

Payment service management is handled through service specific base urls.

Payment 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 payment service, the base URLs are:

Scope

Payment Service Description

Handles Stripe payment flow for one-time premium upgrades on classified listings. Creates and tracks payment transactions, manages Stripe Checkout session and webhooks, and notifies the listing service to update premium status. Exposes payment history endpoints for users and reconciliation for admin.

Payment service provides apis and business logic for following data objects in clonesahibinden 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.

paymentTransaction Data Object: Represents a Stripe-based payment for a one-time premium listing upgrade. Linked to user and listing, with payment metadata, premium details, status, and Stripe reconciliation fields. Immutable except for webhook-driven status updates.

Payment Service Frontend Description By The Backend Architect

Payment Microservice – Frontend Integration Guidance

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"
}

Bucket Management

(This information is also given in PART 1 prompt.)

This application has a bucket service used to store user files and other object-related files. The bucket service is login-agnostic, so for write operations or private reads, include a bucket token (provided by services) in the request’s Authorization header as a Bearer token.

Please note that all other business services require the access token in the Bearer header, while the bucket service expects a bucket token because it is login-agnostic. Ensure you manage the required token injection properly; any auth interceptor should not replace the bucket token with the access token.

User Bucket This bucket stores public user files for each user.

When a user logs in—or in the /currentuser response—there is a userBucketToken to use when sending user-related public files to the bucket service.

{
  //...
  "userBucketToken": "e56d...."
}

To upload a file

POST {baseUrl}/bucket/upload

The request body is form-data which includes the bucketId and the file binary in the files field.

{
    bucketId: "{userId}-public-user-bucket",
    files: {binary}
}

Response status is 200 on success, e.g., body:

{
    "success": true,
    "data": [
        {
            "fileId": "9da03f6d-0409-41ad-bb06-225a244ae408",
            "originalName": "test (10).png",
            "mimeType": "image/png",
            "size": 604063,
            "status": "uploaded",
            "bucketName": "f7103b85-fcda-4dec-92c6-c336f71fd3a2-public-user-bucket",
            "isPublic": true,
            "downloadUrl": "https://babilcom.mindbricks.co/bucket/download/9da03f6d-0409-41ad-bb06-225a244ae408"
        }
    ]
}

To download a file from the bucket, you need its fileId. If you upload an avatar or other asset, ensure the download URL or the fileId is stored in the backend.

Buckets are mostly used in object creations that require an additional file, such as a product image or user avatar. After uploading your image to the bucket, insert the returned download URL into the related property of the target object record.

Application Bucket

This Clonesahibinden application also includes a common public bucket that anyone can read, but only users with the superAdmin, admin, or saasAdmin roles can write (upload) to it.

When a user with one of these admin roles is logged in, the /login response or the /currentuser response also returns an applicationBucketToken field, which is used when uploading any file to the application bucket.

{
  //...
  "applicationBucketToken": "e23fd...."
}

The common public application bucket ID is

"clonesahibinden-public-common-bucket"

In certain admin areas—such as product management pages—since the user already has the application bucket token, they will be able to upload related object images.

Please configure your UI to upload files to the application bucket using this bucket token whenever needed.

Object Buckets Some objects may also return a bucket token for uploading or accessing files related to that object. For example, in a project management application, when you fetch a project’s data, a public or private bucket token may be provided to upload or download project-related files.

These buckets will be used as described in the relevant object definitions.

PaymentTransaction Data Object

Represents a Stripe-based payment for a one-time premium listing upgrade. Linked to user and listing, with payment metadata, premium details, status, and Stripe reconciliation fields. Immutable except for webhook-driven status updates.

PaymentTransaction Data Object Frontend Description By The Backend Architect

paymentTransaction Usage Guidance

PaymentTransaction Data Object Properties

PaymentTransaction 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
amount Double false Yes No Payment amount for selected premiumType, in target currency.
currency String false Yes No Currency in ISO-4217 format (e.g., ‘TRY’,‘USD’) used for Stripe checkout.
listingId ID false Yes No Target classified listing being upgraded to premium.
paymentConfirmedAt Date false No No Date/time when payment was confirmed and premium was granted. Null if never successful/aborted.
premiumType Enum false Yes No Premium upgrade package: bronze, silver, gold (matches frontend/listing options).
status Enum false Yes No Status of payment: pending, awaiting_confirmation (stripe checkout created, awaiting webhook), success (confirmed), failed (declined or errored), canceled (user canceled).
stripeEventId String false No No Last Stripe event webhook ID processed for this payment (used for double-spend/deduplication of webhook).
stripeSessionId String false No No Stripe Checkout Session ID associated with this payment (used for reconciling gateway callbacks).
userId ID false Yes No User (buyer) who made the payment (auth:user)

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

listingId 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

listingId paymentConfirmedAt premiumType status 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.

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.

PaymentTransaction Default APIs

Operation API Name Route Explicitly Set
Create createPaymentTransaction /v1/payments/create Auto
Update stripeWebhookCallback /v1/payments/webhook Auto
Delete none - Auto
Get getPaymentTransaction /v1/payments/:id Auto
List listPaymentTransactions /v1/payments System

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 Paymenttransaction API

Create a paymentTransaction to initiate a Stripe Checkout for premium upgrade on a listing. Checks listing and user, prevents duplicate active payments, creates transaction with status=‘pending’, triggers Stripe checkout, and returns checkout session URL/info.

API Frontend Description By The Backend Architect

Initiate Premium Payment

Rest Route

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

/v1/payments/create

Rest Request Parameters

The createPaymentTransaction api has got 2 regular request parameters

Parameter Type Required Population
listingId ID true request.body?.[“listingId”]
premiumType String true request.body?.[“premiumType”]
listingId : ID of the listing to upgrade to premium
premiumType : PremiumType to purchase (‘bronze’, ‘silver’, ‘gold’)

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

  axios({
    method: 'POST',
    url: '/v1/payments/create',
    data: {
            listingId:"ID",  
            premiumType:"String",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "paymentTransaction",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"paymentTransaction": {
		"id": "ID",
		"amount": "Double",
		"currency": "String",
		"listingId": "ID",
		"paymentConfirmedAt": "Date",
		"premiumType": "Enum",
		"premiumType_idx": "Integer",
		"status": "Enum",
		"status_idx": "Integer",
		"stripeEventId": "String",
		"stripeSessionId": "String",
		"userId": "ID",
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"isActive": true
	},
	"paymentResult": {
		"paymentTicketId": "ID",
		"orderId": "ID",
		"paymentId": "String",
		"paymentStatus": "Enum",
		"paymentIntentInfo": "Object",
		"statusLiteral": "String",
		"amount": "Double",
		"currency": "String",
		"success": true,
		"description": "String",
		"metadata": "Object",
		"paymentUserParams": "Object"
	}
}

Get Paymenttransaction API

Retrieve a paymentTransaction by ID. Only owner or admin may access. Used for order confirmation display, receipt, etc.

API Frontend Description By The Backend Architect

Rest Route

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

/v1/payments/:id

Rest Request Parameters

The getPaymentTransaction api has got 2 regular request parameters

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

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

  axios({
    method: 'GET',
    url: `/v1/payments/${id}`,
    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": "paymentTransaction",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"paymentTransaction": {
		"listingInfo": {
			"categoryId": "ID",
			"isPremium": "Boolean",
			"premiumExpiry": "Date",
			"premiumType": "Enum",
			"premiumType_idx": "Integer",
			"subcategoryId": "ID",
			"title": "String"
		},
		"isActive": true
	}
}

List Paymenttransactions API

List all paymentTransactions for current user, paginated. Admin can query all users. Used for user payment history and admin reconciliation.

API Frontend Description By The Backend Architect

Rest Route

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

/v1/payments

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

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

  axios({
    method: 'GET',
    url: '/v1/payments',
    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": "paymentTransactions",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"paymentTransactions": [
		{
			"listingInfo": [
				{
					"categoryId": "ID",
					"isPremium": "Boolean",
					"premiumExpiry": "Date",
					"premiumType": "Enum",
					"premiumType_idx": "Integer",
					"subcategoryId": "ID",
					"title": "String"
				},
				{},
				{}
			],
			"isActive": true
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Stripe Webhookcallback API

Receives Stripe webhook events, updates corresponding paymentTransaction (status, confirmation), triggers listing premium upgrade via interservice call. Only accepts trusted Stripe event payloads. No login required.

API Frontend Description By The Backend Architect

Rest Route

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

/v1/payments/webhook

Rest Request Parameters

The stripeWebhookCallback api has got 1 regular request parameter

Parameter Type Required Population
paymentTransactionId ID true request.params?.[“paymentTransactionId”]
paymentTransactionId : 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 POST /v1/payments/webhook

  axios({
    method: 'POST',
    url: '/v1/payments/webhook',
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "paymentTransaction",
	"method": "POST",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"paymentTransaction": {
		"id": "ID",
		"amount": "Double",
		"currency": "String",
		"listingId": "ID",
		"paymentConfirmedAt": "Date",
		"premiumType": "Enum",
		"premiumType_idx": "Integer",
		"status": "Enum",
		"status_idx": "Integer",
		"stripeEventId": "String",
		"stripeSessionId": "String",
		"userId": "ID",
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"isActive": true
	}
}

_fetch Listpaymenttransaction API

System API to fetch list of paymentTransaction records for frontend application. Auto-generated, not visible in design.

Rest Route

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

/v1/_fetchlistpaymenttransaction

Rest Request Parameters

Filter Parameters

The _fetchListPaymentTransaction api supports 5 optional filter parameters for filtering list results:

listingId (ID): Target classified listing being upgraded to premium.

paymentConfirmedAt (Date): Date/time when payment was confirmed and premium was granted. Null if never successful/aborted.

premiumType (Enum): Premium upgrade package: bronze, silver, gold (matches frontend/listing options).

status (Enum): Status of payment: pending, awaiting_confirmation (stripe checkout created, awaiting webhook), success (confirmed), failed (declined or errored), canceled (user canceled).

userId (ID): User (buyer) who made the payment (auth:user)

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

  axios({
    method: 'GET',
    url: '/v1/_fetchlistpaymenttransaction',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section above)
        // listingId: '<value>' // Filter by listingId
        // paymentConfirmedAt: '<value>' // Filter by paymentConfirmedAt
        // premiumType: '<value>' // Filter by premiumType
        // status: '<value>' // Filter by status
        // 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": "paymentTransactions",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"paymentTransactions": [
		{
			"id": "ID",
			"amount": "Double",
			"currency": "String",
			"listingId": "ID",
			"paymentConfirmedAt": "Date",
			"premiumType": "Enum",
			"premiumType_idx": "Integer",
			"status": "Enum",
			"status_idx": "Integer",
			"stripeEventId": "String",
			"stripeSessionId": "String",
			"userId": "ID",
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID",
			"listing": [
				{
					"attributes": "Object",
					"categoryId": "ID",
					"condition": "Enum",
					"condition_idx": "Integer",
					"contactEmail": "String",
					"contactPhone": "String",
					"currency": "String",
					"description": "Text",
					"expiresAt": "Date",
					"favoriteCount": "Integer",
					"isPremium": "Boolean",
					"listingType": "Enum",
					"listingType_idx": "Integer",
					"locationId": "ID",
					"_paymentConfirmation": "String",
					"premiumExpiry": "Date",
					"premiumType": "Enum",
					"premiumType_idx": "Integer",
					"price": "Double",
					"status": "Enum",
					"status_idx": "Integer",
					"subcategoryId": "ID",
					"title": "String",
					"userId": "ID",
					"viewsCount": "Integer",
					"paymentConfirmation": "Enum",
					"paymentConfirmation_idx": "Integer"
				},
				{},
				{}
			],
			"buyer": [
				{
					"fullname": "String"
				},
				{},
				{}
			],
			"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.


AdminModeration Service

Service Design Specification

Service Design Specification

clonesahibinden-adminmoderation-service documentation Version: 1.0.1

Scope

This document provides a structured architectural overview of the adminModeration 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.

AdminModeration Service Settings

Admin and moderation service for logging, approval/denial, banning, role/config management, and audit actions. Orchestrates administrative and moderation business APIs, ensures every critical action is logged for traceability, and enables moderator/admin workflows.

Service Overview

This service is configured to listen for HTTP requests on port 3009, 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 clonesahibinden-adminmoderation-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 clonesahibinden-adminmoderation-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
adminActionLog Records every moderation/admin action: who, what, target, reason, metadata, and timestamp. Used for full audit compliance and enables appeals, overrides, and reporting. Immutable except for soft delete. accessProtected

adminActionLog Data Object

Object Overview

Description: Records every moderation/admin action: who, what, target, reason, metadata, and timestamp. Used for full audit compliance and enables appeals, overrides, and reporting. Immutable except for soft delete.

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.

{"action":{"$in":["approveListing","banUser","denyListing","deleteMessage","assignRole"]}}

This object is only cached if this criteria is met.

The criteria is only checked during create and update operations, not during read operations. So if you want the criteria to be checked during read operations because it has checks about reading time context, you should deactivate the checkCriteriaOnlyInCreateAndUpdates option.

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
action String Yes Action performed (e.g., approveListing, denyListing, banUser, assignRole, etc.)
actionAt Date Yes Date and time the action was performed, UTC.
adminUserId ID Yes User ID of admin/moderator who initiated the action (refers to auth:user).
metadata Object No Extended details/JSON object with details relevant to the action (previous/new values, related entities, etc.)
reason String No Reason for action (required on denial, ban; optional for others).
targetId ID Yes ID of the affected resource/entity (listing, user, message, etc.)
targetType String Yes Kind of entity affected by the action (e.g., listing, user, conversationMessage, roleAssignment, category, etc.)

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

action actionAt adminUserId metadata reason targetId targetType

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

action actionAt adminUserId metadata reason targetId targetType

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

action actionAt adminUserId targetId targetType

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

adminUserId

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

Session Data Properties

adminUserId

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.

Filter Properties

action actionAt adminUserId targetId targetType

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

adminModeration has got 4 Business APIs to manage its internal and crud logic. For the details of each business API refer to its chapter.

Edge Controllers

m2mCreateAdminActionLog

Configuration:

REST Settings:


m2mBulkCreateAdminActionLog

Configuration:

REST Settings:


m2mUpdateAdminActionLogById

Configuration:

REST Settings:


m2mDeleteAdminActionLogById

Configuration:

REST Settings:


m2mUpdateAdminActionLogByQuery

Configuration:

REST Settings:


m2mDeleteAdminActionLogByQuery

Configuration:

REST Settings:


m2mUpdateAdminActionLogByIdList

Configuration:

REST Settings:



Service Library

Functions

No general functions defined.

Hook Functions

No hook functions defined.

Edge Functions

m2mCreateAdminActionLog.js

module.exports = async (request) => {
        const { createAdminActionLog } = require("dbLayer");
        const context = { session: request.session, requestId: request.requestId };
        const data = request.body?.data || request.data || request;
        const result = await createAdminActionLog(data, context);
        return { status: 200, content: result };
      }

m2mBulkCreateAdminActionLog.js

module.exports = async (request) => {
        const { createBulkAdminActionLog } = require("dbLayer");
        const context = { session: request.session, requestId: request.requestId };
        const dataList = request.body?.dataList || request.dataList || (Array.isArray(request.body) ? request.body : [request.body]);
        if (!Array.isArray(dataList) || dataList.length === 0) {
          return { status: 400, message: "dataList must be a non-empty array" };
        }
        const result = await createBulkAdminActionLog(dataList, context);
        return { status: 200, content: result };
      }

m2mUpdateAdminActionLogById.js

module.exports = async (request) => {
        const { updateAdminActionLogById } = require("dbLayer");
        const context = { session: request.session, requestId: request.requestId };
        const id = request.body?.id || request.params?.id || request.id;
        const dataClause = request.body?.dataClause || request.dataClause || request.body;
        if (dataClause && dataClause.id) delete dataClause.id;
        if (!id) {
          return { status: 400, message: "ID is required" };
        }
        const result = await updateAdminActionLogById(id, dataClause, context);
        return { status: 200, content: result };
      }

m2mDeleteAdminActionLogById.js

module.exports = async (request) => {
        const { deleteAdminActionLogById } = require("dbLayer");
        const context = { session: request.session, requestId: request.requestId };
        const id = request.body?.id || request.params?.id || request.id;
        if (!id) {
          return { status: 400, message: "ID is required" };
        }
        const result = await deleteAdminActionLogById(id, context);
        return { status: 200, content: result };
      }

m2mUpdateAdminActionLogByQuery.js

module.exports = async (request) => {
        const { updateAdminActionLogByQuery } = require("dbLayer");
        const context = { session: request.session, requestId: request.requestId };
        const dataClause = request.body?.dataClause || request.dataClause || request.body;
        const query = request.body?.query || request.query || {};
        if (!query || typeof query !== "object" || Object.keys(query).length === 0) {
          return { status: 400, message: "Query is required and must be a non-empty object" };
        }
        const result = await updateAdminActionLogByQuery(dataClause, query, context);
        return { status: 200, content: result };
      }

m2mDeleteAdminActionLogByQuery.js

module.exports = async (request) => {
        const { deleteAdminActionLogByQuery } = require("dbLayer");
        const context = { session: request.session, requestId: request.requestId };
        const query = request.body?.query || request.query || {};
        if (!query || typeof query !== "object" || Object.keys(query).length === 0) {
          return { status: 400, message: "Query is required and must be a non-empty object" };
        }
        const result = await deleteAdminActionLogByQuery(query, context);
        return { status: 200, content: result };
      }

m2mUpdateAdminActionLogByIdList.js

module.exports = async (request) => {
        const { updateAdminActionLogByIdList } = require("dbLayer");
        const context = { session: request.session, requestId: request.requestId };
        const idList = request.body?.idList || request.idList || [];
        const dataClause = request.body?.dataClause || request.dataClause || request.body;
        if (dataClause && dataClause.idList) delete dataClause.idList;
        if (!Array.isArray(idList) || idList.length === 0) {
          return { status: 400, message: "idList must be a non-empty array" };
        }
        const result = await updateAdminActionLogByIdList(idList, dataClause, context);
        return { status: 200, content: result };
      }

Templates

No templates defined.

Assets

No assets defined.

Public Assets

No public assets defined.


Event Emission


Integration Patterns

Deployment Considerations

Environment Configuration

Implementation Guidelines

Development Workflow

  1. Data Model Implementation: Generate database schema from data object definitions
  2. CRUD Route Generation: Implement auto-generated routes with custom logic
  3. Custom Logic Integration: Implement hook functions and edge functions
  4. Authentication Integration: Configure with project-level authentication
  5. Testing: Unit and integration testing for all components

Code Generation Expectations

Custom Code Integration Points

Testing Strategy

Unit Testing

Integration Testing

Performance Testing


Appendices

Data Type Reference

Type Description Storage
ID Unique identifier UUID (SQL) / ObjectID (NoSQL)
String Short text (≤255 chars) VARCHAR
Text Long-form text TEXT
Integer 32-bit whole numbers INT
Boolean True/false values BOOLEAN
Double 64-bit floating point DOUBLE
Float 32-bit floating point FLOAT
Short 16-bit integers SMALLINT
Object JSON object JSONB (PostgreSQL) / Object (MongoDB)
Date ISO 8601 timestamp TIMESTAMP
Enum Fixed numeric values SMALLINT with lookup

Enum Value Mappings

Request Locations

HTTP Methods

Edge Function Signature

async function edgeFunction(request) {
  // Custom request processing
  // Return response object or throw error
  return {
    data: {},
    status: 200,
    message: "Success"
  };
}

This document was generated from the service architecture definition and should be kept in sync with implementation changes.


REST API GUIDE

REST API GUIDE

clonesahibinden-adminmoderation-service

Version: 1.0.1

Admin and moderation service for logging, approval/denial, banning, role/config management, and audit actions. Orchestrates administrative and moderation business APIs, ensures every critical action is logged for traceability, and enables moderator/admin workflows.

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 AdminModeration Service’s REST API. This document is designed to provide a comprehensive guide to interfacing with our AdminModeration Service exclusively through RESTful API endpoints.

Intended Audience

This documentation is intended for developers and integrators who are looking to interact with the AdminModeration Service via HTTP requests for purposes such as creating, updating, deleting and querying AdminModeration 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 AdminModeration 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 AdminModeration 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 clonesahibinden-access-token
Cookie clonesahibinden-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 AdminModeration 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 AdminModeration service.

This service is configured to listen for HTTP requests on port 3009, 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 AdminModeration 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 AdminModeration 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 AdminModeration 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 AdminModeration 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

AdminModeration 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.

AdminActionLog resource

Resource Definition : Records every moderation/admin action: who, what, target, reason, metadata, and timestamp. Used for full audit compliance and enables appeals, overrides, and reporting. Immutable except for soft delete. AdminActionLog Resource Properties

Name Type Required Default Definition
action String Action performed (e.g., approveListing, denyListing, banUser, assignRole, etc.)
actionAt Date Date and time the action was performed, UTC.
adminUserId ID User ID of admin/moderator who initiated the action (refers to auth:user).
metadata Object Extended details/JSON object with details relevant to the action (previous/new values, related entities, etc.)
reason String Reason for action (required on denial, ban; optional for others).
targetId ID ID of the affected resource/entity (listing, user, message, etc.)
targetType String Kind of entity affected by the action (e.g., listing, user, conversationMessage, roleAssignment, category, etc.)

Business Api

Create Adminactionlog API

Appends a new immutable moderation/admin audit log entry for every critical action (listing, user, message, role, etc). Used both by internal workflows and explicit admin APIs.

API Frontend Description By The Backend Architect

Frontends should not invoke directly; log entries are created automatically via moderation/admin actions (approve/deny/ban/etc). Accepts adminUserId (from session), action, targetType, targetId, reason (required on denial/ban), metadata (optional), actionAt (server time, auto).

Rest Route

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

/v1/adminactionlogs

Rest Request Parameters

The createAdminActionLog api has got 5 regular request parameters

Parameter Type Required Population
action String true request.body?.[“action”]
metadata Object false request.body?.[“metadata”]
reason String false request.body?.[“reason”]
targetId ID true request.body?.[“targetId”]
targetType String true request.body?.[“targetType”]
action : Action performed (e.g., approveListing, denyListing, banUser, assignRole, etc.)
metadata : Extended details/JSON object with details relevant to the action (previous/new values, related entities, etc.)
reason : Reason for action (required on denial, ban; optional for others).
targetId : ID of the affected resource/entity (listing, user, message, etc.)
targetType : Kind of entity affected by the action (e.g., listing, user, conversationMessage, roleAssignment, category, etc.)

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

  axios({
    method: 'POST',
    url: '/v1/adminactionlogs',
    data: {
            action:"String",  
            metadata:"Object",  
            reason:"String",  
            targetId:"ID",  
            targetType:"String",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "adminActionLog",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"adminActionLog": {
		"id": "ID",
		"action": "String",
		"actionAt": "Date",
		"adminUserId": "ID",
		"metadata": "Object",
		"reason": "String",
		"targetId": "ID",
		"targetType": "String",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Get Adminactionlog API

Retrieve a single moderation/admin action log entry by ID. Used for detailed audit review or appeals.

API Frontend Description By The Backend Architect

Admin/staff frontend can use to show full details of an individual moderation event for investigation, override, or dispute resolution. Only available to admin/moderator roles.

Rest Route

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

/v1/adminactionlogs/:adminActionLogId

Rest Request Parameters

The getAdminActionLog api has got 1 regular request parameter

Parameter Type Required Population
adminActionLogId ID true request.params?.[“adminActionLogId”]
adminActionLogId : 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/adminactionlogs/:adminActionLogId

  axios({
    method: 'GET',
    url: `/v1/adminactionlogs/${adminActionLogId}`,
    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": "adminActionLog",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"adminActionLog": {
		"adminUser": {
			"email": "String",
			"fullname": "String",
			"roleId": "String"
		},
		"isActive": true
	}
}

List Adminactionlogs API

List all moderation/admin action logs with full filter/sort for dashboard or traceability/audit needs. Supports filtering by action, targetType, targetId, adminUserId, actionAt.

API Frontend Description By The Backend Architect

Feeds moderation dashboard. Supports filtering/searching by action (approve, deny, ban, etc), affected entity, targetId, admin/mod, time range. Pagination enabled for large result sets. Intended for admin/mod use only.

Rest Route

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

/v1/adminactionlogs

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

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

  axios({
    method: 'GET',
    url: '/v1/adminactionlogs',
    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": "adminActionLogs",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"adminActionLogs": [
		{
			"adminUser": [
				{
					"email": "String",
					"fullname": "String",
					"roleId": "String"
				},
				{},
				{}
			],
			"isActive": true
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

_fetch Listadminactionlog API

System API to fetch list of adminActionLog records for frontend application. Auto-generated, not visible in design.

Rest Route

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

/v1/_fetchlistadminactionlog

Rest Request Parameters

Filter Parameters

The _fetchListAdminActionLog api supports 5 optional filter parameters for filtering list results:

action (String): Action performed (e.g., approveListing, denyListing, banUser, assignRole, etc.)

actionAt (Date): Date and time the action was performed, UTC.

adminUserId (ID): User ID of admin/moderator who initiated the action (refers to auth:user).

targetId (ID): ID of the affected resource/entity (listing, user, message, etc.)

targetType (String): Kind of entity affected by the action (e.g., listing, user, conversationMessage, roleAssignment, category, etc.)

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

  axios({
    method: 'GET',
    url: '/v1/_fetchlistadminactionlog',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section above)
        // action: '<value>' // Filter by action
        // actionAt: '<value>' // Filter by actionAt
        // adminUserId: '<value>' // Filter by adminUserId
        // targetId: '<value>' // Filter by targetId
        // targetType: '<value>' // Filter by targetType
            }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "adminActionLogs",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"adminActionLogs": [
		{
			"id": "ID",
			"action": "String",
			"actionAt": "Date",
			"adminUserId": "ID",
			"metadata": "Object",
			"reason": "String",
			"targetId": "ID",
			"targetType": "String",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID",
			"adminUser": [
				{
					"fullname": "String"
				},
				{},
				{}
			]
		},
		{},
		{}
	],
	"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

clonesahibinden-adminmoderation-service

Admin and moderation service for logging, approval/denial, banning, role/config management, and audit actions. Orchestrates administrative and moderation business APIs, ensures every critical action is logged for traceability, and enables moderator/admin workflows.

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 AdminModeration Service Event descriptions. This guide is dedicated to detailing how to subscribe to and listen for state changes within the AdminModeration Service, offering an exclusive focus on event subscription mechanisms.

Intended Audience

This documentation is aimed at developers and integrators looking to monitor AdminModeration Service state changes. It is especially relevant for those wishing to implement or enhance business logic based on interactions with AdminModeration 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 AdminModeration 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 adminActionLog-created

Event topic: clonesahibinden-adminmoderation-service-dbevent-adminactionlog-created

This event is triggered upon the creation of a adminActionLog data object in the database. The event payload encompasses the newly created data, encapsulated within the root of the paylod.

Event payload:

{"id":"ID","action":"String","actionAt":"Date","adminUserId":"ID","metadata":"Object","reason":"String","targetId":"ID","targetType":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

DbEvent adminActionLog-updated

Event topic: clonesahibinden-adminmoderation-service-dbevent-adminactionlog-updated

Activation of this event follows the update of a adminActionLog data object. The payload contains the updated information under the adminActionLog attribute, along with the original data prior to update, labeled as old_adminActionLog and also you can find the old and new versions of updated-only portion of the data…

Event payload:

{
old_adminActionLog:{"id":"ID","action":"String","actionAt":"Date","adminUserId":"ID","metadata":"Object","reason":"String","targetId":"ID","targetType":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},
adminActionLog:{"id":"ID","action":"String","actionAt":"Date","adminUserId":"ID","metadata":"Object","reason":"String","targetId":"ID","targetType":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},
oldDataValues,
newDataValues
}

DbEvent adminActionLog-deleted

Event topic: clonesahibinden-adminmoderation-service-dbevent-adminactionlog-deleted

This event announces the deletion of a adminActionLog 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","action":"String","actionAt":"Date","adminUserId":"ID","metadata":"Object","reason":"String","targetId":"ID","targetType":"String","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

ElasticSearch Index Events

Within the AdminModeration 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 adminactionlog-created

Event topic: elastic-index-clonesahibinden_adminactionlog-created

Event payload:

{"id":"ID","action":"String","actionAt":"Date","adminUserId":"ID","metadata":"Object","reason":"String","targetId":"ID","targetType":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event adminactionlog-updated

Event topic: elastic-index-clonesahibinden_adminactionlog-created

Event payload:

{"id":"ID","action":"String","actionAt":"Date","adminUserId":"ID","metadata":"Object","reason":"String","targetId":"ID","targetType":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event adminactionlog-deleted

Event topic: elastic-index-clonesahibinden_adminactionlog-deleted

Event payload:

{"id":"ID","action":"String","actionAt":"Date","adminUserId":"ID","metadata":"Object","reason":"String","targetId":"ID","targetType":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event adminactionlog-extended

Event topic: elastic-index-clonesahibinden_adminactionlog-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 adminactionlog-created

Event topic : clonesahibinden-adminmoderation-service-adminactionlog-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 adminActionLog data object itself.

The following JSON included in the payload illustrates the fullest representation of the adminActionLog 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":"adminActionLog","method":"POST","action":"create","appVersion":"Version","rowCount":1,"adminActionLog":{"id":"ID","action":"String","actionAt":"Date","adminUserId":"ID","metadata":"Object","reason":"String","targetId":"ID","targetType":"String","isActive":true,"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 adminActionLog

Service Design Specification - Object Design for adminActionLog

clonesahibinden-adminmoderation-service documentation

Document Overview

This document outlines the object design for the adminActionLog model in our application. It includes details about the model’s attributes, relationships, and any specific validation or business logic that applies.

adminActionLog Data Object

Object Overview

Description: Records every moderation/admin action: who, what, target, reason, metadata, and timestamp. Used for full audit compliance and enables appeals, overrides, and reporting. Immutable except for soft delete.

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.

{"action":{"$in":["approveListing","banUser","denyListing","deleteMessage","assignRole"]}}

This object is only cached if this criteria is met.

The criteria is only checked during create and update operations, not during read operations. So if you want the criteria to be checked during read operations because it has checks about reading time context, you should deactivate the checkCriteriaOnlyInCreateAndUpdates option.

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
action String Yes Action performed (e.g., approveListing, denyListing, banUser, assignRole, etc.)
actionAt Date Yes Date and time the action was performed, UTC.
adminUserId ID Yes User ID of admin/moderator who initiated the action (refers to auth:user).
metadata Object No Extended details/JSON object with details relevant to the action (previous/new values, related entities, etc.)
reason String No Reason for action (required on denial, ban; optional for others).
targetId ID Yes ID of the affected resource/entity (listing, user, message, etc.)
targetType String Yes Kind of entity affected by the action (e.g., listing, user, conversationMessage, roleAssignment, category, etc.)

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

action actionAt adminUserId metadata reason targetId targetType

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

action actionAt adminUserId metadata reason targetId targetType

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

action actionAt adminUserId targetId targetType

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

adminUserId

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

Session Data Properties

adminUserId

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.

Filter Properties

action actionAt adminUserId targetId targetType

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 Adminactionlog

Business API Design Specification - Create Adminactionlog

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 createAdminActionLog 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 createAdminActionLog Business API is designed to handle a create operation on the AdminActionLog data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

Appends a new immutable moderation/admin audit log entry for every critical action (listing, user, message, role, etc). Used both by internal workflows and explicit admin APIs.

API Frontend Description By The Backend Architect

Frontends should not invoke directly; log entries are created automatically via moderation/admin actions (approve/deny/ban/etc). Accepts adminUserId (from session), action, targetType, targetId, reason (required on denial/ban), metadata (optional), actionAt (server time, auto).

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 createAdminActionLog Business API includes a REST controller that can be triggered via the following route:

/v1/adminactionlogs

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 createAdminActionLog Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The createAdminActionLog 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
adminActionLogId ID No - body adminActionLogId
Description: This id paremeter is used to create the data object with a given specific id. Leave null for automatic id.
action String Yes - body action
Description: Action performed (e.g., approveListing, denyListing, banUser, assignRole, etc.)
adminUserId ID Yes - session userId
Description: User ID of admin/moderator who initiated the action (refers to auth:user).
metadata Object No - body metadata
Description: Extended details/JSON object with details relevant to the action (previous/new values, related entities, etc.)
reason String No - body reason
Description: Reason for action (required on denial, ban; optional for others).
targetId ID Yes - body targetId
Description: ID of the affected resource/entity (listing, user, message, etc.)
targetType String Yes - body targetType
Description: Kind of entity affected by the action (e.g., listing, user, conversationMessage, roleAssignment, category, etc.)

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 createAdminActionLog 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.adminActionLogId,
  action: this.action,
  adminUserId: this.adminUserId,
  metadata: this.metadata ? (typeof this.metadata == 'string' ? JSON.parse(this.metadata) : this.metadata) : null,
  reason: this.reason,
  targetId: this.targetId,
  targetType: this.targetType,
  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, socketSettings, 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 createAdminActionLog api has got 5 regular client parameters

Parameter Type Required Population
action String true request.body?.[“action”]
metadata Object false request.body?.[“metadata”]
reason String false request.body?.[“reason”]
targetId ID true request.body?.[“targetId”]
targetType String true request.body?.[“targetType”]

REST Request

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

  axios({
    method: 'POST',
    url: '/v1/adminactionlogs',
    data: {
            action:"String",  
            metadata:"Object",  
            reason:"String",  
            targetId:"ID",  
            targetType:"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 adminActionLog 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": "adminActionLog",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"adminActionLog": {
		"id": "ID",
		"action": "String",
		"actionAt": "Date",
		"adminUserId": "ID",
		"metadata": "Object",
		"reason": "String",
		"targetId": "ID",
		"targetType": "String",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Business API Design Specification - Get Adminactionlog

Business API Design Specification - Get Adminactionlog

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 getAdminActionLog 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 getAdminActionLog Business API is designed to handle a get operation on the AdminActionLog data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

Retrieve a single moderation/admin action log entry by ID. Used for detailed audit review or appeals.

API Frontend Description By The Backend Architect

Admin/staff frontend can use to show full details of an individual moderation event for investigation, override, or dispute resolution. Only available to admin/moderator roles.

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 getAdminActionLog Business API includes a REST controller that can be triggered via the following route:

/v1/adminactionlogs/:adminActionLogId

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 getAdminActionLog Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The getAdminActionLog 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
adminActionLogId ID Yes - urlpath adminActionLogId
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 getAdminActionLog 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.",

adminUserId,action,targetType,targetId,reason,metadata,actionAt

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.

{$and:[{id:this.adminActionLogId},{isActive:true}]}

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, socketSettings, 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 getAdminActionLog api has got 1 regular client parameter

Parameter Type Required Population
adminActionLogId ID true request.params?.[“adminActionLogId”]

REST Request

To access the api you can use the REST controller with the path GET /v1/adminactionlogs/:adminActionLogId

  axios({
    method: 'GET',
    url: `/v1/adminactionlogs/${adminActionLogId}`,
    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 adminActionLog 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": "adminActionLog",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"adminActionLog": {
		"adminUser": {
			"email": "String",
			"fullname": "String",
			"roleId": "String"
		},
		"isActive": true
	}
}

Business API Design Specification - List Adminactionlogs

Business API Design Specification - List Adminactionlogs

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 listAdminActionLogs 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 listAdminActionLogs Business API is designed to handle a list operation on the AdminActionLog 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 moderation/admin action logs with full filter/sort for dashboard or traceability/audit needs. Supports filtering by action, targetType, targetId, adminUserId, actionAt.

API Frontend Description By The Backend Architect

Feeds moderation dashboard. Supports filtering/searching by action (approve, deny, ban, etc), affected entity, targetId, admin/mod, time range. Pagination enabled for large result sets. Intended for admin/mod use only.

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 listAdminActionLogs Business API includes a REST controller that can be triggered via the following route:

/v1/adminactionlogs

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 listAdminActionLogs Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The listAdminActionLogs 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 listAdminActionLogs 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.",

adminUserId,action,targetType,targetId,reason,metadata,actionAt

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.

{isActive:true}

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).

[ actionAt 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, socketSettings, 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 listAdminActionLogs api has got no visible parameters.

REST Request

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

  axios({
    method: 'GET',
    url: '/v1/adminactionlogs',
    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 adminActionLogs 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": "adminActionLogs",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"adminActionLogs": [
		{
			"adminUser": [
				{
					"email": "String",
					"fullname": "String",
					"roleId": "String"
				},
				{},
				{}
			],
			"isActive": true
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Business API Design Specification - _fetch Listadminactionlog

Business API Design Specification - _fetch Listadminactionlog

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 _fetchListAdminActionLog 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 _fetchListAdminActionLog Business API is designed to handle a list operation on the AdminActionLog data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

System API to fetch list of adminActionLog records for frontend application. Auto-generated, not visible in design.

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 _fetchListAdminActionLog Business API includes a REST controller that can be triggered via the following route:

/v1/_fetchlistadminactionlog

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 _fetchListAdminActionLog Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The _fetchListAdminActionLog 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 _fetchListAdminActionLog api supports 5 optional filter parameters for filtering list results using URL query parameters. These parameters are only available for list type APIs.

action Filter

Type: String
Description: Action performed (e.g., approveListing, denyListing, banUser, assignRole, 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/_fetchlistadminactionlog?action=john
// Matches: "John", "Johnny", "johnson", "McJohn", etc.

// Find records with multiple values (use multiple parameters)
GET /v1/_fetchlistadminactionlog?action=laptop&action=phone&action=tablet
// Matches records containing "laptop", "phone", or "tablet" anywhere in the field

// Find records without this field
GET /v1/_fetchlistadminactionlog?action=null

actionAt Filter

Type: Date
Description: Date and time the action was performed, UTC.
Location: Query Parameter

Usage:

Non-Array Property (Date filtering matches records where the date falls within the specified day, ignoring time portion):

Special Date Operators:

Date Formats: Dates can be provided in ISO 8601 format (2024-01-15, 2024-01-15T10:30:00Z) or as timestamps (1705324800000).

Examples:

// Get records created on a specific date
GET /v1/_fetchlistadminactionlog?actionAt=2024-01-15

// Get records created on multiple dates (use multiple parameters)
GET /v1/_fetchlistadminactionlog?actionAt=2024-01-15&actionAt=2024-01-20

// Get records created today (server timezone)
GET /v1/_fetchlistadminactionlog?actionAt=$today

// Get records created today (user's local timezone)
GET /v1/_fetchlistadminactionlog?actionAt=$ltoday

// Get records created this week (server timezone)
GET /v1/_fetchlistadminactionlog?actionAt=$week

// Get records created this week (user's local timezone)
GET /v1/_fetchlistadminactionlog?actionAt=$lweek

// Get records created this month
GET /v1/_fetchlistadminactionlog?actionAt=$month

// Get records created on a specific date (user's local timezone)
GET /v1/_fetchlistadminactionlog?actionAt=$leq-2024-01-15

// Get records created on multiple dates (user's local timezone, use multiple parameters)
GET /v1/_fetchlistadminactionlog?actionAt=$lin-2024-01-15&actionAt=$lin-2024-01-20

// Get records without this field
GET /v1/_fetchlistadminactionlog?actionAt=null

adminUserId Filter

Type: ID
Description: User ID of admin/moderator who initiated the action (refers to auth:user).
Location: Query Parameter

Usage:

Non-Array Property:

Examples:

// Get records with a specific ID
GET /v1/_fetchlistadminactionlog?adminUserId=550e8400-e29b-41d4-a716-446655440000

// Get records with multiple IDs (use multiple parameters)
GET /v1/_fetchlistadminactionlog?adminUserId=550e8400-e29b-41d4-a716-446655440000&adminUserId=660e8400-e29b-41d4-a716-446655440001

// Get records without this field
GET /v1/_fetchlistadminactionlog?adminUserId=null

targetId Filter

Type: ID
Description: ID of the affected resource/entity (listing, user, message, etc.)
Location: Query Parameter

Usage:

Non-Array Property:

Examples:

// Get records with a specific ID
GET /v1/_fetchlistadminactionlog?targetId=550e8400-e29b-41d4-a716-446655440000

// Get records with multiple IDs (use multiple parameters)
GET /v1/_fetchlistadminactionlog?targetId=550e8400-e29b-41d4-a716-446655440000&targetId=660e8400-e29b-41d4-a716-446655440001

// Get records without this field
GET /v1/_fetchlistadminactionlog?targetId=null

targetType Filter

Type: String
Description: Kind of entity affected by the action (e.g., listing, user, conversationMessage, roleAssignment, category, 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/_fetchlistadminactionlog?targetType=john
// Matches: "John", "Johnny", "johnson", "McJohn", etc.

// Find records with multiple values (use multiple parameters)
GET /v1/_fetchlistadminactionlog?targetType=laptop&targetType=phone&targetType=tablet
// Matches records containing "laptop", "phone", or "tablet" anywhere in the field

// Find records without this field
GET /v1/_fetchlistadminactionlog?targetType=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 _fetchListAdminActionLog 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.

{isActive:true}

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).

[ createdAt 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, socketSettings, 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 _fetchListAdminActionLog 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
action String No Action performed (e.g., approveListing, denyListing, banUser, assignRole, etc.)
actionAt Date No Date and time the action was performed, UTC.
adminUserId ID No User ID of admin/moderator who initiated the action (refers to auth:user).
targetId ID No ID of the affected resource/entity (listing, user, message, etc.)
targetType String No Kind of entity affected by the action (e.g., listing, user, conversationMessage, roleAssignment, category, etc.)

REST Request

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

  axios({
    method: 'GET',
    url: '/v1/_fetchlistadminactionlog',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section for usage examples)
        // action: '<value>' // Filter by action
        // actionAt: '<value>' // Filter by actionAt
        // adminUserId: '<value>' // Filter by adminUserId
        // targetId: '<value>' // Filter by targetId
        // targetType: '<value>' // Filter by targetType
            }
  });

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 adminActionLogs 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": "adminActionLogs",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"adminActionLogs": [
		{
			"id": "ID",
			"action": "String",
			"actionAt": "Date",
			"adminUserId": "ID",
			"metadata": "Object",
			"reason": "String",
			"targetId": "ID",
			"targetType": "String",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID",
			"adminUser": [
				{
					"fullname": "String"
				},
				{},
				{}
			]
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

CategoryLocation Service

Service Design Specification

Service Design Specification

clonesahibinden-categorylocation-service documentation Version: 1.0.1

Scope

This document provides a structured architectural overview of the categoryLocation 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.

CategoryLocation Service Settings

Manages the category and location hierarchies for listings. Provides CRUD with uniqueness enforcement, navigation endpoints for category/location trees, and supports efficient public browsing with heavy read optimization.

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 clonesahibinden-categorylocation-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 clonesahibinden-categorylocation-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
category Represents a listing category; supports up to three levels of nesting for hierarchical browsing and filtering. Self-referencing parent-child relationship. Slug is unique for public URL routing. Sort order is unique within parent for ordered display. accessPublic
location Represents a hierarchical location of country/city/district for listings. Used for filtering/search/location field on all listings. accessPublic

category Data Object

Object Overview

Description: Represents a listing category; supports up to three levels of nesting for hierarchical browsing and filtering. Self-referencing parent-child relationship. Slug is unique for public URL routing. Sort order is unique within parent for ordered display.

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.

{isActive:true}

This object is only cached if this criteria is met.

The criteria is checked during all operations, including read operations. If your criteria is all about the data properties, you can use the checkCriteriaOnlyInCreateAndUpdates option to improve performance.

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.

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
description Text No Optional extended description for category (for admin display or frontend info).
icon String No Icon identifier (string or URL to a static asset) for this category.
name String Yes Category name, e.g. 'Automobiles', 'Electronics'.
parentCategoryId ID No References parent category for hierarchy. Top-level (root) categories have null.
slug String Yes SEO-friendly unique slug for URL and search. Lowercase, hyphens only.
sortOrder Integer Yes Order for listing within siblings. Unique per parent.

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

description icon name parentCategoryId slug sortOrder

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

description icon name parentCategoryId slug sortOrder

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

name parentCategoryId slug sortOrder

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

slug

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

parentCategoryId slug

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

slug

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

parentCategoryId

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: No

Filter Properties

name parentCategoryId slug

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.

location Data Object

Object Overview

Description: Represents a hierarchical location of country/city/district for listings. Used for filtering/search/location field on all listings.

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.

{isActive:true}

This object is only cached if this criteria is met.

The criteria is checked during all operations, including read operations. If your criteria is all about the data properties, you can use the checkCriteriaOnlyInCreateAndUpdates option to improve performance.

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
city String Yes City name.
country String Yes Country name (typically 'Turkey').
district String Yes District name, for fine-grained search.
latitude Double No Latitude for map/search.
longitude Double No Longitude for map/search.
postalCode String No Postal code for location.

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

city country district latitude longitude postalCode

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

city country district latitude longitude postalCode

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

city country district

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

city country district

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

categoryLocation has got 12 Business APIs to manage its internal and crud logic. For the details of each business API refer to its chapter.

Edge Controllers

m2mCreateCategory

Configuration:

REST Settings:


m2mBulkCreateCategory

Configuration:

REST Settings:


m2mUpdateCategoryById

Configuration:

REST Settings:


m2mDeleteCategoryById

Configuration:

REST Settings:


m2mUpdateCategoryByQuery

Configuration:

REST Settings:


m2mDeleteCategoryByQuery

Configuration:

REST Settings:


m2mUpdateCategoryByIdList

Configuration:

REST Settings:


m2mCreateLocation

Configuration:

REST Settings:


m2mBulkCreateLocation

Configuration:

REST Settings:


m2mUpdateLocationById

Configuration:

REST Settings:


m2mDeleteLocationById

Configuration:

REST Settings:


m2mUpdateLocationByQuery

Configuration:

REST Settings:


m2mDeleteLocationByQuery

Configuration:

REST Settings:


m2mUpdateLocationByIdList

Configuration:

REST Settings:



Service Library

Functions

No general functions defined.

Hook Functions

No hook functions defined.

Edge Functions

m2mCreateCategory.js

module.exports = async (request) => {
        const { createCategory } = require("dbLayer");
        const context = { session: request.session, requestId: request.requestId };
        const data = request.body?.data || request.data || request;
        const result = await createCategory(data, context);
        return { status: 200, content: result };
      }

m2mBulkCreateCategory.js

module.exports = async (request) => {
        const { createBulkCategory } = require("dbLayer");
        const context = { session: request.session, requestId: request.requestId };
        const dataList = request.body?.dataList || request.dataList || (Array.isArray(request.body) ? request.body : [request.body]);
        if (!Array.isArray(dataList) || dataList.length === 0) {
          return { status: 400, message: "dataList must be a non-empty array" };
        }
        const result = await createBulkCategory(dataList, context);
        return { status: 200, content: result };
      }

m2mUpdateCategoryById.js

module.exports = async (request) => {
        const { updateCategoryById } = require("dbLayer");
        const context = { session: request.session, requestId: request.requestId };
        const id = request.body?.id || request.params?.id || request.id;
        const dataClause = request.body?.dataClause || request.dataClause || request.body;
        if (dataClause && dataClause.id) delete dataClause.id;
        if (!id) {
          return { status: 400, message: "ID is required" };
        }
        const result = await updateCategoryById(id, dataClause, context);
        return { status: 200, content: result };
      }

m2mDeleteCategoryById.js

module.exports = async (request) => {
        const { deleteCategoryById } = require("dbLayer");
        const context = { session: request.session, requestId: request.requestId };
        const id = request.body?.id || request.params?.id || request.id;
        if (!id) {
          return { status: 400, message: "ID is required" };
        }
        const result = await deleteCategoryById(id, context);
        return { status: 200, content: result };
      }

m2mUpdateCategoryByQuery.js

module.exports = async (request) => {
        const { updateCategoryByQuery } = require("dbLayer");
        const context = { session: request.session, requestId: request.requestId };
        const dataClause = request.body?.dataClause || request.dataClause || request.body;
        const query = request.body?.query || request.query || {};
        if (!query || typeof query !== "object" || Object.keys(query).length === 0) {
          return { status: 400, message: "Query is required and must be a non-empty object" };
        }
        const result = await updateCategoryByQuery(dataClause, query, context);
        return { status: 200, content: result };
      }

m2mDeleteCategoryByQuery.js

module.exports = async (request) => {
        const { deleteCategoryByQuery } = require("dbLayer");
        const context = { session: request.session, requestId: request.requestId };
        const query = request.body?.query || request.query || {};
        if (!query || typeof query !== "object" || Object.keys(query).length === 0) {
          return { status: 400, message: "Query is required and must be a non-empty object" };
        }
        const result = await deleteCategoryByQuery(query, context);
        return { status: 200, content: result };
      }

m2mUpdateCategoryByIdList.js

module.exports = async (request) => {
        const { updateCategoryByIdList } = require("dbLayer");
        const context = { session: request.session, requestId: request.requestId };
        const idList = request.body?.idList || request.idList || [];
        const dataClause = request.body?.dataClause || request.dataClause || request.body;
        if (dataClause && dataClause.idList) delete dataClause.idList;
        if (!Array.isArray(idList) || idList.length === 0) {
          return { status: 400, message: "idList must be a non-empty array" };
        }
        const result = await updateCategoryByIdList(idList, dataClause, context);
        return { status: 200, content: result };
      }

m2mCreateLocation.js

module.exports = async (request) => {
        const { createLocation } = require("dbLayer");
        const context = { session: request.session, requestId: request.requestId };
        const data = request.body?.data || request.data || request;
        const result = await createLocation(data, context);
        return { status: 200, content: result };
      }

m2mBulkCreateLocation.js

module.exports = async (request) => {
        const { createBulkLocation } = require("dbLayer");
        const context = { session: request.session, requestId: request.requestId };
        const dataList = request.body?.dataList || request.dataList || (Array.isArray(request.body) ? request.body : [request.body]);
        if (!Array.isArray(dataList) || dataList.length === 0) {
          return { status: 400, message: "dataList must be a non-empty array" };
        }
        const result = await createBulkLocation(dataList, context);
        return { status: 200, content: result };
      }

m2mUpdateLocationById.js

module.exports = async (request) => {
        const { updateLocationById } = require("dbLayer");
        const context = { session: request.session, requestId: request.requestId };
        const id = request.body?.id || request.params?.id || request.id;
        const dataClause = request.body?.dataClause || request.dataClause || request.body;
        if (dataClause && dataClause.id) delete dataClause.id;
        if (!id) {
          return { status: 400, message: "ID is required" };
        }
        const result = await updateLocationById(id, dataClause, context);
        return { status: 200, content: result };
      }

m2mDeleteLocationById.js

module.exports = async (request) => {
        const { deleteLocationById } = require("dbLayer");
        const context = { session: request.session, requestId: request.requestId };
        const id = request.body?.id || request.params?.id || request.id;
        if (!id) {
          return { status: 400, message: "ID is required" };
        }
        const result = await deleteLocationById(id, context);
        return { status: 200, content: result };
      }

m2mUpdateLocationByQuery.js

module.exports = async (request) => {
        const { updateLocationByQuery } = require("dbLayer");
        const context = { session: request.session, requestId: request.requestId };
        const dataClause = request.body?.dataClause || request.dataClause || request.body;
        const query = request.body?.query || request.query || {};
        if (!query || typeof query !== "object" || Object.keys(query).length === 0) {
          return { status: 400, message: "Query is required and must be a non-empty object" };
        }
        const result = await updateLocationByQuery(dataClause, query, context);
        return { status: 200, content: result };
      }

m2mDeleteLocationByQuery.js

module.exports = async (request) => {
        const { deleteLocationByQuery } = require("dbLayer");
        const context = { session: request.session, requestId: request.requestId };
        const query = request.body?.query || request.query || {};
        if (!query || typeof query !== "object" || Object.keys(query).length === 0) {
          return { status: 400, message: "Query is required and must be a non-empty object" };
        }
        const result = await deleteLocationByQuery(query, context);
        return { status: 200, content: result };
      }

m2mUpdateLocationByIdList.js

module.exports = async (request) => {
        const { updateLocationByIdList } = require("dbLayer");
        const context = { session: request.session, requestId: request.requestId };
        const idList = request.body?.idList || request.idList || [];
        const dataClause = request.body?.dataClause || request.dataClause || request.body;
        if (dataClause && dataClause.idList) delete dataClause.idList;
        if (!Array.isArray(idList) || idList.length === 0) {
          return { status: 400, message: "idList must be a non-empty array" };
        }
        const result = await updateLocationByIdList(idList, dataClause, context);
        return { status: 200, content: result };
      }

Templates

No templates defined.

Assets

No assets defined.

Public Assets

No public assets defined.


Event Emission


Integration Patterns

Deployment Considerations

Environment Configuration

Implementation Guidelines

Development Workflow

  1. Data Model Implementation: Generate database schema from data object definitions
  2. CRUD Route Generation: Implement auto-generated routes with custom logic
  3. Custom Logic Integration: Implement hook functions and edge functions
  4. Authentication Integration: Configure with project-level authentication
  5. Testing: Unit and integration testing for all components

Code Generation Expectations

Custom Code Integration Points

Testing Strategy

Unit Testing

Integration Testing

Performance Testing


Appendices

Data Type Reference

Type Description Storage
ID Unique identifier UUID (SQL) / ObjectID (NoSQL)
String Short text (≤255 chars) VARCHAR
Text Long-form text TEXT
Integer 32-bit whole numbers INT
Boolean True/false values BOOLEAN
Double 64-bit floating point DOUBLE
Float 32-bit floating point FLOAT
Short 16-bit integers SMALLINT
Object JSON object JSONB (PostgreSQL) / Object (MongoDB)
Date ISO 8601 timestamp TIMESTAMP
Enum Fixed numeric values SMALLINT with lookup

Enum Value Mappings

Request Locations

HTTP Methods

Edge Function Signature

async function edgeFunction(request) {
  // Custom request processing
  // Return response object or throw error
  return {
    data: {},
    status: 200,
    message: "Success"
  };
}

This document was generated from the service architecture definition and should be kept in sync with implementation changes.


REST API GUIDE

REST API GUIDE

clonesahibinden-categorylocation-service

Version: 1.0.1

Manages the category and location hierarchies for listings. Provides CRUD with uniqueness enforcement, navigation endpoints for category/location trees, and supports efficient public browsing with heavy read optimization.

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 CategoryLocation Service’s REST API. This document is designed to provide a comprehensive guide to interfacing with our CategoryLocation Service exclusively through RESTful API endpoints.

Intended Audience

This documentation is intended for developers and integrators who are looking to interact with the CategoryLocation Service via HTTP requests for purposes such as creating, updating, deleting and querying CategoryLocation 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 CategoryLocation 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 CategoryLocation 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 clonesahibinden-access-token
Cookie clonesahibinden-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 CategoryLocation 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 CategoryLocation 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 CategoryLocation 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 CategoryLocation 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 CategoryLocation 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 CategoryLocation 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

CategoryLocation 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.

Category resource

Resource Definition : Represents a listing category; supports up to three levels of nesting for hierarchical browsing and filtering. Self-referencing parent-child relationship. Slug is unique for public URL routing. Sort order is unique within parent for ordered display. Category Resource Properties

Name Type Required Default Definition
description Text Optional extended description for category (for admin display or frontend info).
icon String Icon identifier (string or URL to a static asset) for this category.
name String Category name, e.g. 'Automobiles', 'Electronics'.
parentCategoryId ID References parent category for hierarchy. Top-level (root) categories have null.
slug String SEO-friendly unique slug for URL and search. Lowercase, hyphens only.
sortOrder Integer Order for listing within siblings. Unique per parent.

Location resource

Resource Definition : Represents a hierarchical location of country/city/district for listings. Used for filtering/search/location field on all listings. Location Resource Properties

Name Type Required Default Definition
city String City name.
country String Country name (typically 'Turkey').
district String District name, for fine-grained search.
latitude Double Latitude for map/search.
longitude Double Longitude for map/search.
postalCode String Postal code for location.

Business Api

Create Category API

Creates a new category. Slug must be globally unique. Only admin may create categories.

API Frontend Description By The Backend Architect

Only admins can create categories. The slug field must be unique and URL-friendly. Parent selection (for nesting) is validated. Use for admin consoles and bulk management.

Rest Route

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

/v1/categories

Rest Request Parameters

The createCategory api has got 6 regular request parameters

Parameter Type Required Population
description Text false request.body?.[“description”]
icon String false request.body?.[“icon”]
name String true request.body?.[“name”]
parentCategoryId ID false request.body?.[“parentCategoryId”]
slug String true request.body?.[“slug”]
sortOrder Integer true request.body?.[“sortOrder”]
description : Optional extended description for category (for admin display or frontend info).
icon : Icon identifier (string or URL to a static asset) for this category.
name : Category name, e.g. ‘Automobiles’, ‘Electronics’.
parentCategoryId : References parent category for hierarchy. Top-level (root) categories have null.
slug : SEO-friendly unique slug for URL and search. Lowercase, hyphens only.
sortOrder : Order for listing within siblings. Unique per parent.

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

  axios({
    method: 'POST',
    url: '/v1/categories',
    data: {
            description:"Text",  
            icon:"String",  
            name:"String",  
            parentCategoryId:"ID",  
            slug:"String",  
            sortOrder:"Integer",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "category",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"category": {
		"id": "ID",
		"description": "Text",
		"icon": "String",
		"name": "String",
		"parentCategoryId": "ID",
		"slug": "String",
		"sortOrder": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Create Location API

Create a new location entry (country, city, district). Only admin allowed. Composite uniqueness enforced.

API Frontend Description By The Backend Architect

For admin use only. Location uniqueness validated on (country, city, district). For multi-level selectors, call this repeatedly to populate country/city/district lists.

Rest Route

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

/v1/locations

Rest Request Parameters

The createLocation api has got 6 regular request parameters

Parameter Type Required Population
city String true request.body?.[“city”]
country String true request.body?.[“country”]
district String true request.body?.[“district”]
latitude Double false request.body?.[“latitude”]
longitude Double false request.body?.[“longitude”]
postalCode String false request.body?.[“postalCode”]
city : City name.
country : Country name (typically ‘Turkey’).
district : District name, for fine-grained search.
latitude : Latitude for map/search.
longitude : Longitude for map/search.
postalCode : Postal code for location.

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

  axios({
    method: 'POST',
    url: '/v1/locations',
    data: {
            city:"String",  
            country:"String",  
            district:"String",  
            latitude:"Double",  
            longitude:"Double",  
            postalCode:"String",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "location",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"location": {
		"id": "ID",
		"city": "String",
		"country": "String",
		"district": "String",
		"latitude": "Double",
		"longitude": "Double",
		"postalCode": "String",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Delete Category API

Deletes a category by id (soft delete). Only admin allowed.

API Frontend Description By The Backend Architect

Admin-only. Deleting a parent category sets parentCategoryId to null on children. Category is soft-deleted for restoration if needed.

Rest Route

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

/v1/categories/:categoryId

Rest Request Parameters

The deleteCategory api has got 1 regular request parameter

Parameter Type Required Population
categoryId ID true request.params?.[“categoryId”]
categoryId : 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/categories/:categoryId

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

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "category",
	"method": "DELETE",
	"action": "delete",
	"appVersion": "Version",
	"rowCount": 1,
	"category": {
		"id": "ID",
		"description": "Text",
		"icon": "String",
		"name": "String",
		"parentCategoryId": "ID",
		"slug": "String",
		"sortOrder": "Integer",
		"isActive": false,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Delete Location API

Soft-delete a location for admin-only. Used for removing obsolete/corrected locations.

API Frontend Description By The Backend Architect

Admin-only. Set isActive=false to remove location from public selectors. If referenced elsewhere, deletion may be blocked until listings/categories updated.

Rest Route

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

/v1/locations/:locationId

Rest Request Parameters

The deleteLocation api has got 1 regular request parameter

Parameter Type Required Population
locationId ID true request.params?.[“locationId”]
locationId : 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/locations/:locationId

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

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "location",
	"method": "DELETE",
	"action": "delete",
	"appVersion": "Version",
	"rowCount": 1,
	"location": {
		"id": "ID",
		"city": "String",
		"country": "String",
		"district": "String",
		"latitude": "Double",
		"longitude": "Double",
		"postalCode": "String",
		"isActive": false,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Get Category API

Fetch a single category by id. Publicly accessible.

API Frontend Description By The Backend Architect

Get category details for a given id. Enrich response with child category count and parent info for navigation trees. Used for editing/viewing category details.

Rest Route

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

/v1/categories/:categoryId

Rest Request Parameters

The getCategory api has got 1 regular request parameter

Parameter Type Required Population
categoryId ID true request.params?.[“categoryId”]
categoryId : 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/categories/:categoryId

  axios({
    method: 'GET',
    url: `/v1/categories/${categoryId}`,
    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": "category",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"category": {
		"parentCategory": {
			"name": "String",
			"slug": "String"
		},
		"childCategories": {
			"name": "String",
			"slug": "String",
			"isActive": true
		},
		"isActive": true
	}
}

Get Location API

Get details of a location by id. Publicly accessible for search/forms. Used by listing creation editors, etc.

API Frontend Description By The Backend Architect

Fetch all fields for display or editing/location picker. Admins use for management forms; public users for navigation/filter search.

Rest Route

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

/v1/locations/:locationId

Rest Request Parameters

The getLocation api has got 1 regular request parameter

Parameter Type Required Population
locationId ID true request.params?.[“locationId”]
locationId : 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/locations/:locationId

  axios({
    method: 'GET',
    url: `/v1/locations/${locationId}`,
    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": "location",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"location": {
		"isActive": true
	}
}

List Categories API

Returns all categories (optionally filtered by parentCategoryId or isActive). Used for category trees, navigation, and dropdowns. Public.

API Frontend Description By The Backend Architect

Use this endpoint for building category selection/search trees, sidebars, or dropdowns. Accepts parentCategoryId as a filter for fetching children. Returns all data for public display. Pagination not enabled (few hundred at most). Children included via join. Optionally returns count of active children for expandable UI.

Rest Route

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

/v1/categories

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

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

  axios({
    method: 'GET',
    url: '/v1/categories',
    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": "categories",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"categories": [
		{
			"childCategories": [
				{
					"name": "String",
					"slug": "String",
					"isActive": true
				},
				{},
				{}
			],
			"activeChildCount": [
				null,
				null,
				null
			],
			"isActive": true
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

List Locations API

List all locations (optionally filter by country/city/district). Used for populating selectors and browsing. Public. No pagination (few thousand max).

API Frontend Description By The Backend Architect

Request all locations or optionally filter by country/city/district for cascading selectors. Public use for forms, admin for management. If needed, can expand to support location grouping/child-count in future.

Rest Route

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

/v1/locations

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

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

  axios({
    method: 'GET',
    url: '/v1/locations',
    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": "locations",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"locations": [
		{
			"isActive": true
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Update Category API

Update an existing category. Only admin allowed. Slug uniqueness enforced.

API Frontend Description By The Backend Architect

Admins can update any field of a category including parent/child relationships. Changing parentCategoryId triggers structure update. Slug must remain unique.

Rest Route

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

/v1/categories/:categoryId

Rest Request Parameters

The updateCategory api has got 7 regular request parameters

Parameter Type Required Population
categoryId ID true request.params?.[“categoryId”]
description Text false request.body?.[“description”]
icon String false request.body?.[“icon”]
name String false request.body?.[“name”]
parentCategoryId ID false request.body?.[“parentCategoryId”]
slug String false request.body?.[“slug”]
sortOrder Integer false request.body?.[“sortOrder”]
categoryId : This id paremeter is used to select the required data object that will be updated
description : Optional extended description for category (for admin display or frontend info).
icon : Icon identifier (string or URL to a static asset) for this category.
name : Category name, e.g. ‘Automobiles’, ‘Electronics’.
parentCategoryId : References parent category for hierarchy. Top-level (root) categories have null.
slug : SEO-friendly unique slug for URL and search. Lowercase, hyphens only.
sortOrder : Order for listing within siblings. Unique per parent.

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

  axios({
    method: 'PATCH',
    url: `/v1/categories/${categoryId}`,
    data: {
            description:"Text",  
            icon:"String",  
            name:"String",  
            parentCategoryId:"ID",  
            slug:"String",  
            sortOrder:"Integer",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "category",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"category": {
		"id": "ID",
		"description": "Text",
		"icon": "String",
		"name": "String",
		"parentCategoryId": "ID",
		"slug": "String",
		"sortOrder": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Update Location API

Update existing location entry. Only admin allowed. Composite key must remain unique.

API Frontend Description By The Backend Architect

Admin-only. Location string fields (country, city, district) must not create a duplicate. Use for typo correction or boundary updates; minimal public usage.

Rest Route

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

/v1/locations/:locationId

Rest Request Parameters

The updateLocation api has got 7 regular request parameters

Parameter Type Required Population
locationId ID true request.params?.[“locationId”]
city String false request.body?.[“city”]
country String false request.body?.[“country”]
district String false request.body?.[“district”]
latitude Double false request.body?.[“latitude”]
longitude Double false request.body?.[“longitude”]
postalCode String false request.body?.[“postalCode”]
locationId : This id paremeter is used to select the required data object that will be updated
city : City name.
country : Country name (typically ‘Turkey’).
district : District name, for fine-grained search.
latitude : Latitude for map/search.
longitude : Longitude for map/search.
postalCode : Postal code for location.

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

  axios({
    method: 'PATCH',
    url: `/v1/locations/${locationId}`,
    data: {
            city:"String",  
            country:"String",  
            district:"String",  
            latitude:"Double",  
            longitude:"Double",  
            postalCode:"String",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "location",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"location": {
		"id": "ID",
		"city": "String",
		"country": "String",
		"district": "String",
		"latitude": "Double",
		"longitude": "Double",
		"postalCode": "String",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

_fetch Listcategory API

System API to fetch list of category records for frontend application. Auto-generated, not visible in design.

Rest Route

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

/v1/_fetchlistcategory

Rest Request Parameters

Filter Parameters

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

name (String): Category name, e.g. ‘Automobiles’, ‘Electronics’.

parentCategoryId (ID): References parent category for hierarchy. Top-level (root) categories have null.

slug (String): SEO-friendly unique slug for URL and search. Lowercase, hyphens only.

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

  axios({
    method: 'GET',
    url: '/v1/_fetchlistcategory',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section above)
        // name: '<value>' // Filter by name
        // parentCategoryId: '<value>' // Filter by parentCategoryId
        // slug: '<value>' // Filter by slug
            }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "categories",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"categories": [
		{
			"id": "ID",
			"description": "Text",
			"icon": "String",
			"name": "String",
			"parentCategoryId": "ID",
			"slug": "String",
			"sortOrder": "Integer",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID",
			"parent": [
				{
					"description": "Text",
					"icon": "String",
					"name": "String",
					"parentCategoryId": "ID",
					"slug": "String",
					"sortOrder": "Integer"
				},
				{},
				{}
			]
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

_fetch Listlocation API

System API to fetch list of location records for frontend application. Auto-generated, not visible in design.

Rest Route

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

/v1/_fetchlistlocation

Rest Request Parameters

Filter Parameters

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

city (String): City name.

country (String): Country name (typically ‘Turkey’).

district (String): District name, for fine-grained search.

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

  axios({
    method: 'GET',
    url: '/v1/_fetchlistlocation',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section above)
        // city: '<value>' // Filter by city
        // country: '<value>' // Filter by country
        // district: '<value>' // Filter by district
            }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "locations",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"locations": [
		{
			"id": "ID",
			"city": "String",
			"country": "String",
			"district": "String",
			"latitude": "Double",
			"longitude": "Double",
			"postalCode": "String",
			"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

clonesahibinden-categorylocation-service

Manages the category and location hierarchies for listings. Provides CRUD with uniqueness enforcement, navigation endpoints for category/location trees, and supports efficient public browsing with heavy read optimization.

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 CategoryLocation Service Event descriptions. This guide is dedicated to detailing how to subscribe to and listen for state changes within the CategoryLocation Service, offering an exclusive focus on event subscription mechanisms.

Intended Audience

This documentation is aimed at developers and integrators looking to monitor CategoryLocation Service state changes. It is especially relevant for those wishing to implement or enhance business logic based on interactions with CategoryLocation 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 CategoryLocation 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 category-created

Event topic: clonesahibinden-categorylocation-service-dbevent-category-created

This event is triggered upon the creation of a category data object in the database. The event payload encompasses the newly created data, encapsulated within the root of the paylod.

Event payload:

{"id":"ID","description":"Text","icon":"String","name":"String","parentCategoryId":"ID","slug":"String","sortOrder":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

DbEvent category-updated

Event topic: clonesahibinden-categorylocation-service-dbevent-category-updated

Activation of this event follows the update of a category data object. The payload contains the updated information under the category attribute, along with the original data prior to update, labeled as old_category and also you can find the old and new versions of updated-only portion of the data…

Event payload:

{
old_category:{"id":"ID","description":"Text","icon":"String","name":"String","parentCategoryId":"ID","slug":"String","sortOrder":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},
category:{"id":"ID","description":"Text","icon":"String","name":"String","parentCategoryId":"ID","slug":"String","sortOrder":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},
oldDataValues,
newDataValues
}

DbEvent category-deleted

Event topic: clonesahibinden-categorylocation-service-dbevent-category-deleted

This event announces the deletion of a category 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","description":"Text","icon":"String","name":"String","parentCategoryId":"ID","slug":"String","sortOrder":"Integer","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

DbEvent location-created

Event topic: clonesahibinden-categorylocation-service-dbevent-location-created

This event is triggered upon the creation of a location data object in the database. The event payload encompasses the newly created data, encapsulated within the root of the paylod.

Event payload:

{"id":"ID","city":"String","country":"String","district":"String","latitude":"Double","longitude":"Double","postalCode":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

DbEvent location-updated

Event topic: clonesahibinden-categorylocation-service-dbevent-location-updated

Activation of this event follows the update of a location data object. The payload contains the updated information under the location attribute, along with the original data prior to update, labeled as old_location and also you can find the old and new versions of updated-only portion of the data…

Event payload:

{
old_location:{"id":"ID","city":"String","country":"String","district":"String","latitude":"Double","longitude":"Double","postalCode":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},
location:{"id":"ID","city":"String","country":"String","district":"String","latitude":"Double","longitude":"Double","postalCode":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},
oldDataValues,
newDataValues
}

DbEvent location-deleted

Event topic: clonesahibinden-categorylocation-service-dbevent-location-deleted

This event announces the deletion of a location 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","city":"String","country":"String","district":"String","latitude":"Double","longitude":"Double","postalCode":"String","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

ElasticSearch Index Events

Within the CategoryLocation 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 category-created

Event topic: elastic-index-clonesahibinden_category-created

Event payload:

{"id":"ID","description":"Text","icon":"String","name":"String","parentCategoryId":"ID","slug":"String","sortOrder":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event category-updated

Event topic: elastic-index-clonesahibinden_category-created

Event payload:

{"id":"ID","description":"Text","icon":"String","name":"String","parentCategoryId":"ID","slug":"String","sortOrder":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event category-deleted

Event topic: elastic-index-clonesahibinden_category-deleted

Event payload:

{"id":"ID","description":"Text","icon":"String","name":"String","parentCategoryId":"ID","slug":"String","sortOrder":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event category-extended

Event topic: elastic-index-clonesahibinden_category-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 category-created

Event topic : clonesahibinden-categorylocation-service-category-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 category data object itself.

The following JSON included in the payload illustrates the fullest representation of the category 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":"category","method":"POST","action":"create","appVersion":"Version","rowCount":1,"category":{"id":"ID","description":"Text","icon":"String","name":"String","parentCategoryId":"ID","slug":"String","sortOrder":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event location-created

Event topic : clonesahibinden-categorylocation-service-location-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 location data object itself.

The following JSON included in the payload illustrates the fullest representation of the location 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":"location","method":"POST","action":"create","appVersion":"Version","rowCount":1,"location":{"id":"ID","city":"String","country":"String","district":"String","latitude":"Double","longitude":"Double","postalCode":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event category-deleted

Event topic : clonesahibinden-categorylocation-service-category-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 category data object itself.

The following JSON included in the payload illustrates the fullest representation of the category 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":"category","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"category":{"id":"ID","description":"Text","icon":"String","name":"String","parentCategoryId":"ID","slug":"String","sortOrder":"Integer","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event location-deleted

Event topic : clonesahibinden-categorylocation-service-location-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 location data object itself.

The following JSON included in the payload illustrates the fullest representation of the location 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":"location","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"location":{"id":"ID","city":"String","country":"String","district":"String","latitude":"Double","longitude":"Double","postalCode":"String","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event category-updated

Event topic : clonesahibinden-categorylocation-service-category-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 category data object itself.

The following JSON included in the payload illustrates the fullest representation of the category 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":"category","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"category":{"id":"ID","description":"Text","icon":"String","name":"String","parentCategoryId":"ID","slug":"String","sortOrder":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event location-updated

Event topic : clonesahibinden-categorylocation-service-location-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 location data object itself.

The following JSON included in the payload illustrates the fullest representation of the location 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":"location","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"location":{"id":"ID","city":"String","country":"String","district":"String","latitude":"Double","longitude":"Double","postalCode":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Index Event location-created

Event topic: elastic-index-clonesahibinden_location-created

Event payload:

{"id":"ID","city":"String","country":"String","district":"String","latitude":"Double","longitude":"Double","postalCode":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event location-updated

Event topic: elastic-index-clonesahibinden_location-created

Event payload:

{"id":"ID","city":"String","country":"String","district":"String","latitude":"Double","longitude":"Double","postalCode":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event location-deleted

Event topic: elastic-index-clonesahibinden_location-deleted

Event payload:

{"id":"ID","city":"String","country":"String","district":"String","latitude":"Double","longitude":"Double","postalCode":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event location-extended

Event topic: elastic-index-clonesahibinden_location-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 category-created

Event topic : clonesahibinden-categorylocation-service-category-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 category data object itself.

The following JSON included in the payload illustrates the fullest representation of the category 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":"category","method":"POST","action":"create","appVersion":"Version","rowCount":1,"category":{"id":"ID","description":"Text","icon":"String","name":"String","parentCategoryId":"ID","slug":"String","sortOrder":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event location-created

Event topic : clonesahibinden-categorylocation-service-location-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 location data object itself.

The following JSON included in the payload illustrates the fullest representation of the location 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":"location","method":"POST","action":"create","appVersion":"Version","rowCount":1,"location":{"id":"ID","city":"String","country":"String","district":"String","latitude":"Double","longitude":"Double","postalCode":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event category-deleted

Event topic : clonesahibinden-categorylocation-service-category-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 category data object itself.

The following JSON included in the payload illustrates the fullest representation of the category 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":"category","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"category":{"id":"ID","description":"Text","icon":"String","name":"String","parentCategoryId":"ID","slug":"String","sortOrder":"Integer","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event location-deleted

Event topic : clonesahibinden-categorylocation-service-location-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 location data object itself.

The following JSON included in the payload illustrates the fullest representation of the location 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":"location","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"location":{"id":"ID","city":"String","country":"String","district":"String","latitude":"Double","longitude":"Double","postalCode":"String","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event category-updated

Event topic : clonesahibinden-categorylocation-service-category-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 category data object itself.

The following JSON included in the payload illustrates the fullest representation of the category 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":"category","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"category":{"id":"ID","description":"Text","icon":"String","name":"String","parentCategoryId":"ID","slug":"String","sortOrder":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event location-updated

Event topic : clonesahibinden-categorylocation-service-location-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 location data object itself.

The following JSON included in the payload illustrates the fullest representation of the location 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":"location","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"location":{"id":"ID","city":"String","country":"String","district":"String","latitude":"Double","longitude":"Double","postalCode":"String","isActive":true,"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 category

Service Design Specification - Object Design for category

clonesahibinden-categorylocation-service documentation

Document Overview

This document outlines the object design for the category model in our application. It includes details about the model’s attributes, relationships, and any specific validation or business logic that applies.

category Data Object

Object Overview

Description: Represents a listing category; supports up to three levels of nesting for hierarchical browsing and filtering. Self-referencing parent-child relationship. Slug is unique for public URL routing. Sort order is unique within parent for ordered display.

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.

{isActive:true}

This object is only cached if this criteria is met.

The criteria is checked during all operations, including read operations. If your criteria is all about the data properties, you can use the checkCriteriaOnlyInCreateAndUpdates option to improve performance.

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.

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
description Text No Optional extended description for category (for admin display or frontend info).
icon String No Icon identifier (string or URL to a static asset) for this category.
name String Yes Category name, e.g. 'Automobiles', 'Electronics'.
parentCategoryId ID No References parent category for hierarchy. Top-level (root) categories have null.
slug String Yes SEO-friendly unique slug for URL and search. Lowercase, hyphens only.
sortOrder Integer Yes Order for listing within siblings. Unique per parent.

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

description icon name parentCategoryId slug sortOrder

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

description icon name parentCategoryId slug sortOrder

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

name parentCategoryId slug sortOrder

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

slug

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

parentCategoryId slug

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

slug

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

parentCategoryId

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: No

Filter Properties

name parentCategoryId slug

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 location

Service Design Specification - Object Design for location

clonesahibinden-categorylocation-service documentation

Document Overview

This document outlines the object design for the location model in our application. It includes details about the model’s attributes, relationships, and any specific validation or business logic that applies.

location Data Object

Object Overview

Description: Represents a hierarchical location of country/city/district for listings. Used for filtering/search/location field on all listings.

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.

{isActive:true}

This object is only cached if this criteria is met.

The criteria is checked during all operations, including read operations. If your criteria is all about the data properties, you can use the checkCriteriaOnlyInCreateAndUpdates option to improve performance.

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
city String Yes City name.
country String Yes Country name (typically 'Turkey').
district String Yes District name, for fine-grained search.
latitude Double No Latitude for map/search.
longitude Double No Longitude for map/search.
postalCode String No Postal code for location.

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

city country district latitude longitude postalCode

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

city country district latitude longitude postalCode

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

city country district

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

city country district

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 Category

Business API Design Specification - Create Category

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 createCategory 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 createCategory Business API is designed to handle a create operation on the Category data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

Creates a new category. Slug must be globally unique. Only admin may create categories.

API Frontend Description By The Backend Architect

Only admins can create categories. The slug field must be unique and URL-friendly. Parent selection (for nesting) is validated. Use for admin consoles and bulk management.

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 createCategory Business API includes a REST controller that can be triggered via the following route:

/v1/categories

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 createCategory Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The createCategory 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
categoryId ID No - body categoryId
Description: This id paremeter is used to create the data object with a given specific id. Leave null for automatic id.
description Text No - body description
Description: Optional extended description for category (for admin display or frontend info).
icon String No - body icon
Description: Icon identifier (string or URL to a static asset) for this category.
name String Yes - body name
Description: Category name, e.g. ‘Automobiles’, ‘Electronics’.
parentCategoryId ID No - body parentCategoryId
Description: References parent category for hierarchy. Top-level (root) categories have null.
slug String Yes - body slug
Description: SEO-friendly unique slug for URL and search. Lowercase, hyphens only.
sortOrder Integer Yes - body sortOrder
Description: Order for listing within siblings. Unique per parent.

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 createCategory 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.categoryId,
  description: this.description,
  icon: this.icon,
  name: this.name,
  parentCategoryId: this.parentCategoryId,
  slug: this.slug,
  sortOrder: this.sortOrder,
  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, socketSettings, 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 : validateCategorySlug

Action Type: ValidationAction

Ensures slug is unique and URL-valid. Throws error if not.

class Api {
  async validateCategorySlug() {
    const isValid = !this.slug || /^[a-z0-9-]+$/.test(this.slug);

    if (!isValid) {
      throw new BadRequestError(
        "Category slug must be lowercase, alphanumeric, hyphens only.",
      );
    }
    return isValid;
  }
}

[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] 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

[7] 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

[8] Step : mainCreateOperation

Manager executes the database insert operation, updates indexes/caches, and triggers internal post-processing like linked default records.


[9] Step : buildOutput

Manager shapes the response: masks sensitive fields, resolves linked references, and formats output according to API contract.


[10] Step : sendResponse

Manager sends the response to the client and finalizes internal tasks like flushing logs or updating session state.


[11] 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 createCategory api has got 6 regular client parameters

Parameter Type Required Population
description Text false request.body?.[“description”]
icon String false request.body?.[“icon”]
name String true request.body?.[“name”]
parentCategoryId ID false request.body?.[“parentCategoryId”]
slug String true request.body?.[“slug”]
sortOrder Integer true request.body?.[“sortOrder”]

REST Request

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

  axios({
    method: 'POST',
    url: '/v1/categories',
    data: {
            description:"Text",  
            icon:"String",  
            name:"String",  
            parentCategoryId:"ID",  
            slug:"String",  
            sortOrder:"Integer",  
    
    },
    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 category 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": "category",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"category": {
		"id": "ID",
		"description": "Text",
		"icon": "String",
		"name": "String",
		"parentCategoryId": "ID",
		"slug": "String",
		"sortOrder": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Business API Design Specification - Create Location

Business API Design Specification - Create Location

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 createLocation 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 createLocation Business API is designed to handle a create operation on the Location 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 location entry (country, city, district). Only admin allowed. Composite uniqueness enforced.

API Frontend Description By The Backend Architect

For admin use only. Location uniqueness validated on (country, city, district). For multi-level selectors, call this repeatedly to populate country/city/district lists.

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 createLocation Business API includes a REST controller that can be triggered via the following route:

/v1/locations

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 createLocation Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The createLocation 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
locationId ID No - body locationId
Description: This id paremeter is used to create the data object with a given specific id. Leave null for automatic id.
city String Yes - body city
Description: City name.
country String Yes - body country
Description: Country name (typically ‘Turkey’).
district String Yes - body district
Description: District name, for fine-grained search.
latitude Double No - body latitude
Description: Latitude for map/search.
longitude Double No - body longitude
Description: Longitude for map/search.
postalCode String No - body postalCode
Description: Postal code for location.

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 createLocation 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.locationId,
  city: this.city,
  country: this.country,
  district: this.district,
  latitude: this.latitude,
  longitude: this.longitude,
  postalCode: this.postalCode,
  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, socketSettings, 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 : validateLocationUnique

Action Type: ValidationAction

Ensure no duplicate location entry exists for country/city/district.

class Api {
  async validateLocationUnique() {
    const isValid = (async () => {
      const db = require("dbLayer");
      const result = await db.getLocationByQuery({
        country: this.country,
        city: this.city,
        district: this.district,
        isActive: true,
      });
      return !result;
    })();

    if (!isValid) {
      throw new BadRequestError(
        "Location with this combination already exists.",
      );
    }
    return isValid;
  }
}

[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] 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

[7] 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

[8] Step : mainCreateOperation

Manager executes the database insert operation, updates indexes/caches, and triggers internal post-processing like linked default records.


[9] Step : buildOutput

Manager shapes the response: masks sensitive fields, resolves linked references, and formats output according to API contract.


[10] Step : sendResponse

Manager sends the response to the client and finalizes internal tasks like flushing logs or updating session state.


[11] 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 createLocation api has got 6 regular client parameters

Parameter Type Required Population
city String true request.body?.[“city”]
country String true request.body?.[“country”]
district String true request.body?.[“district”]
latitude Double false request.body?.[“latitude”]
longitude Double false request.body?.[“longitude”]
postalCode String false request.body?.[“postalCode”]

REST Request

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

  axios({
    method: 'POST',
    url: '/v1/locations',
    data: {
            city:"String",  
            country:"String",  
            district:"String",  
            latitude:"Double",  
            longitude:"Double",  
            postalCode:"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 location 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": "location",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"location": {
		"id": "ID",
		"city": "String",
		"country": "String",
		"district": "String",
		"latitude": "Double",
		"longitude": "Double",
		"postalCode": "String",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Business API Design Specification - Delete Category

Business API Design Specification - Delete Category

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 deleteCategory 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 deleteCategory Business API is designed to handle a delete operation on the Category data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

Deletes a category by id (soft delete). Only admin allowed.

API Frontend Description By The Backend Architect

Admin-only. Deleting a parent category sets parentCategoryId to null on children. Category is soft-deleted for restoration if needed.

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 deleteCategory Business API includes a REST controller that can be triggered via the following route:

/v1/categories/:categoryId

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 deleteCategory Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The deleteCategory 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
categoryId ID Yes - urlpath categoryId
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 deleteCategory 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.

{$and:[{id:this.categoryId},{isActive:true}]}

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, socketSettings, 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 deleteCategory api has got 1 regular client parameter

Parameter Type Required Population
categoryId ID true request.params?.[“categoryId”]

REST Request

To access the api you can use the REST controller with the path DELETE /v1/categories/:categoryId

  axios({
    method: 'DELETE',
    url: `/v1/categories/${categoryId}`,
    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 category 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": "category",
	"method": "DELETE",
	"action": "delete",
	"appVersion": "Version",
	"rowCount": 1,
	"category": {
		"id": "ID",
		"description": "Text",
		"icon": "String",
		"name": "String",
		"parentCategoryId": "ID",
		"slug": "String",
		"sortOrder": "Integer",
		"isActive": false,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Business API Design Specification - Delete Location

Business API Design Specification - Delete Location

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 deleteLocation 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 deleteLocation Business API is designed to handle a delete operation on the Location data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

Soft-delete a location for admin-only. Used for removing obsolete/corrected locations.

API Frontend Description By The Backend Architect

Admin-only. Set isActive=false to remove location from public selectors. If referenced elsewhere, deletion may be blocked until listings/categories updated.

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 deleteLocation Business API includes a REST controller that can be triggered via the following route:

/v1/locations/:locationId

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 deleteLocation Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The deleteLocation 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
locationId ID Yes - urlpath locationId
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 deleteLocation 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.

{$and:[{id:this.locationId},{isActive:true}]}

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, socketSettings, 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 deleteLocation api has got 1 regular client parameter

Parameter Type Required Population
locationId ID true request.params?.[“locationId”]

REST Request

To access the api you can use the REST controller with the path DELETE /v1/locations/:locationId

  axios({
    method: 'DELETE',
    url: `/v1/locations/${locationId}`,
    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 location 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": "location",
	"method": "DELETE",
	"action": "delete",
	"appVersion": "Version",
	"rowCount": 1,
	"location": {
		"id": "ID",
		"city": "String",
		"country": "String",
		"district": "String",
		"latitude": "Double",
		"longitude": "Double",
		"postalCode": "String",
		"isActive": false,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Business API Design Specification - Get Category

Business API Design Specification - Get Category

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 getCategory 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 getCategory Business API is designed to handle a get operation on the Category 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 category by id. Publicly accessible.

API Frontend Description By The Backend Architect

Get category details for a given id. Enrich response with child category count and parent info for navigation trees. Used for editing/viewing category details.

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 getCategory Business API includes a REST controller that can be triggered via the following route:

/v1/categories/:categoryId

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 getCategory Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The getCategory 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
categoryId ID Yes - urlpath categoryId
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 getCategory 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,parentCategoryId,name,slug,icon,description,sortOrder,isActive

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.

{$and:[{id:this.categoryId},{isActive:true}]}

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, socketSettings, 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 getCategory api has got 1 regular client parameter

Parameter Type Required Population
categoryId ID true request.params?.[“categoryId”]

REST Request

To access the api you can use the REST controller with the path GET /v1/categories/:categoryId

  axios({
    method: 'GET',
    url: `/v1/categories/${categoryId}`,
    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 category 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": "category",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"category": {
		"parentCategory": {
			"name": "String",
			"slug": "String"
		},
		"childCategories": {
			"name": "String",
			"slug": "String",
			"isActive": true
		},
		"isActive": true
	}
}

Business API Design Specification - Get Location

Business API Design Specification - Get Location

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 getLocation 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 getLocation Business API is designed to handle a get operation on the Location data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

Get details of a location by id. Publicly accessible for search/forms. Used by listing creation editors, etc.

API Frontend Description By The Backend Architect

Fetch all fields for display or editing/location picker. Admins use for management forms; public users for navigation/filter search.

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 getLocation Business API includes a REST controller that can be triggered via the following route:

/v1/locations/:locationId

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 getLocation Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The getLocation 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
locationId ID Yes - urlpath locationId
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 getLocation 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,country,city,district,postalCode,latitude,longitude,isActive

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.

{$and:[{id:this.locationId},{isActive:true}]}

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, socketSettings, 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 getLocation api has got 1 regular client parameter

Parameter Type Required Population
locationId ID true request.params?.[“locationId”]

REST Request

To access the api you can use the REST controller with the path GET /v1/locations/:locationId

  axios({
    method: 'GET',
    url: `/v1/locations/${locationId}`,
    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 location 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": "location",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"location": {
		"isActive": true
	}
}

Business API Design Specification - List Categories

Business API Design Specification - List Categories

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 listCategories 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 listCategories Business API is designed to handle a list operation on the Category data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

Returns all categories (optionally filtered by parentCategoryId or isActive). Used for category trees, navigation, and dropdowns. Public.

API Frontend Description By The Backend Architect

Use this endpoint for building category selection/search trees, sidebars, or dropdowns. Accepts parentCategoryId as a filter for fetching children. Returns all data for public display. Pagination not enabled (few hundred at most). Children included via join. Optionally returns count of active children for expandable UI.

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 listCategories Business API includes a REST controller that can be triggered via the following route:

/v1/categories

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 listCategories Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The listCategories 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 listCategories 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,parentCategoryId,name,slug,icon,description,sortOrder,isActive

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.

{isActive:true}

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).

[ sortOrder 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, socketSettings, 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 listCategories api has got no visible parameters.

REST Request

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

  axios({
    method: 'GET',
    url: '/v1/categories',
    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 categories 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": "categories",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"categories": [
		{
			"childCategories": [
				{
					"name": "String",
					"slug": "String",
					"isActive": true
				},
				{},
				{}
			],
			"activeChildCount": [
				null,
				null,
				null
			],
			"isActive": true
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Business API Design Specification - List Locations

Business API Design Specification - List Locations

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 listLocations 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 listLocations Business API is designed to handle a list operation on the Location 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 locations (optionally filter by country/city/district). Used for populating selectors and browsing. Public. No pagination (few thousand max).

API Frontend Description By The Backend Architect

Request all locations or optionally filter by country/city/district for cascading selectors. Public use for forms, admin for management. If needed, can expand to support location grouping/child-count in future.

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 listLocations Business API includes a REST controller that can be triggered via the following route:

/v1/locations

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 listLocations Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The listLocations 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 listLocations 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,country,city,district,postalCode,latitude,longitude,isActive

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.

{isActive:true}

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).

[ country asc,city asc,district 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, socketSettings, 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 listLocations api has got no visible parameters.

REST Request

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

  axios({
    method: 'GET',
    url: '/v1/locations',
    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 locations 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": "locations",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"locations": [
		{
			"isActive": true
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Business API Design Specification - Update Category

Business API Design Specification - Update Category

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 updateCategory 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 updateCategory Business API is designed to handle a update operation on the Category data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

Update an existing category. Only admin allowed. Slug uniqueness enforced.

API Frontend Description By The Backend Architect

Admins can update any field of a category including parent/child relationships. Changing parentCategoryId triggers structure update. Slug must remain unique.

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 updateCategory Business API includes a REST controller that can be triggered via the following route:

/v1/categories/:categoryId

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 updateCategory Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The updateCategory 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
categoryId ID Yes - urlpath categoryId
Description: This id paremeter is used to select the required data object that will be updated
description Text No - body description
Description: Optional extended description for category (for admin display or frontend info).
icon String No - body icon
Description: Icon identifier (string or URL to a static asset) for this category.
name String No - body name
Description: Category name, e.g. ‘Automobiles’, ‘Electronics’.
parentCategoryId ID No - body parentCategoryId
Description: References parent category for hierarchy. Top-level (root) categories have null.
slug String No - body slug
Description: SEO-friendly unique slug for URL and search. Lowercase, hyphens only.
sortOrder Integer No - body sortOrder
Description: Order for listing within siblings. Unique per parent.

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 updateCategory 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.

{$and:[{id:this.categoryId},{isActive:true}]}

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.

{
  description: this.description,
  icon: this.icon,
  name: this.name,
  parentCategoryId: this.parentCategoryId,
  slug: this.slug,
  sortOrder: this.sortOrder,
}

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, socketSettings, 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] Action : validateCategorySlugOnUpdate

Action Type: ValidationAction

Slug must remain unique and URL-safe.

class Api {
  async validateCategorySlugOnUpdate() {
    const isValid = !this.slug || /^[a-z0-9-]+$/.test(this.slug);

    if (!isValid) {
      throw new BadRequestError(
        "Category slug must be lowercase, alphanumeric, hyphens only.",
      );
    }
    return isValid;
  }
}

[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] 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] 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 updateCategory api has got 7 regular client parameters

Parameter Type Required Population
categoryId ID true request.params?.[“categoryId”]
description Text false request.body?.[“description”]
icon String false request.body?.[“icon”]
name String false request.body?.[“name”]
parentCategoryId ID false request.body?.[“parentCategoryId”]
slug String false request.body?.[“slug”]
sortOrder Integer false request.body?.[“sortOrder”]

REST Request

To access the api you can use the REST controller with the path PATCH /v1/categories/:categoryId

  axios({
    method: 'PATCH',
    url: `/v1/categories/${categoryId}`,
    data: {
            description:"Text",  
            icon:"String",  
            name:"String",  
            parentCategoryId:"ID",  
            slug:"String",  
            sortOrder:"Integer",  
    
    },
    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 category 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": "category",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"category": {
		"id": "ID",
		"description": "Text",
		"icon": "String",
		"name": "String",
		"parentCategoryId": "ID",
		"slug": "String",
		"sortOrder": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Business API Design Specification - Update Location

Business API Design Specification - Update Location

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 updateLocation 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 updateLocation Business API is designed to handle a update operation on the Location data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

Update existing location entry. Only admin allowed. Composite key must remain unique.

API Frontend Description By The Backend Architect

Admin-only. Location string fields (country, city, district) must not create a duplicate. Use for typo correction or boundary updates; minimal public usage.

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 updateLocation Business API includes a REST controller that can be triggered via the following route:

/v1/locations/:locationId

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 updateLocation Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The updateLocation 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
locationId ID Yes - urlpath locationId
Description: This id paremeter is used to select the required data object that will be updated
city String No - body city
Description: City name.
country String No - body country
Description: Country name (typically ‘Turkey’).
district String No - body district
Description: District name, for fine-grained search.
latitude Double No - body latitude
Description: Latitude for map/search.
longitude Double No - body longitude
Description: Longitude for map/search.
postalCode String No - body postalCode
Description: Postal code for location.

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 updateLocation 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.

{$and:[{id:this.locationId},{isActive:true}]}

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.

{
  city: this.city,
  country: this.country,
  district: this.district,
  latitude: this.latitude,
  longitude: this.longitude,
  postalCode: this.postalCode,
}

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, socketSettings, 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] Action : validateLocationUniqueOnUpdate

Action Type: ValidationAction

Ensure updated location does not cause a duplicate.

class Api {
  async validateLocationUniqueOnUpdate() {
    const isValid = (async () => {
      const db = require("dbLayer");
      const result = await db.getLocationByQuery({
        country: this.country,
        city: this.city,
        district: this.district,
        isActive: true,
      });
      return !result || result.id === this.id;
    })();

    if (!isValid) {
      throw new BadRequestError(
        "Location with this combination already exists.",
      );
    }
    return isValid;
  }
}

[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] 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] 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 updateLocation api has got 7 regular client parameters

Parameter Type Required Population
locationId ID true request.params?.[“locationId”]
city String false request.body?.[“city”]
country String false request.body?.[“country”]
district String false request.body?.[“district”]
latitude Double false request.body?.[“latitude”]
longitude Double false request.body?.[“longitude”]
postalCode String false request.body?.[“postalCode”]

REST Request

To access the api you can use the REST controller with the path PATCH /v1/locations/:locationId

  axios({
    method: 'PATCH',
    url: `/v1/locations/${locationId}`,
    data: {
            city:"String",  
            country:"String",  
            district:"String",  
            latitude:"Double",  
            longitude:"Double",  
            postalCode:"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 location 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": "location",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"location": {
		"id": "ID",
		"city": "String",
		"country": "String",
		"district": "String",
		"latitude": "Double",
		"longitude": "Double",
		"postalCode": "String",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Business API Design Specification - _fetch Listcategory

Business API Design Specification - _fetch Listcategory

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 _fetchListCategory 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 _fetchListCategory Business API is designed to handle a list operation on the Category data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

System API to fetch list of category records for frontend application. Auto-generated, not visible in design.

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 _fetchListCategory Business API includes a REST controller that can be triggered via the following route:

/v1/_fetchlistcategory

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 _fetchListCategory Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The _fetchListCategory 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 _fetchListCategory api supports 3 optional filter parameters for filtering list results using URL query parameters. These parameters are only available for list type APIs.

name Filter

Type: String
Description: Category name, e.g. ‘Automobiles’, ‘Electronics’.
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/_fetchlistcategory?name=john
// Matches: "John", "Johnny", "johnson", "McJohn", etc.

// Find records with multiple values (use multiple parameters)
GET /v1/_fetchlistcategory?name=laptop&name=phone&name=tablet
// Matches records containing "laptop", "phone", or "tablet" anywhere in the field

// Find records without this field
GET /v1/_fetchlistcategory?name=null

parentCategoryId Filter

Type: ID
Description: References parent category for hierarchy. Top-level (root) categories have null.
Location: Query Parameter

Usage:

Non-Array Property:

Examples:

// Get records with a specific ID
GET /v1/_fetchlistcategory?parentCategoryId=550e8400-e29b-41d4-a716-446655440000

// Get records with multiple IDs (use multiple parameters)
GET /v1/_fetchlistcategory?parentCategoryId=550e8400-e29b-41d4-a716-446655440000&parentCategoryId=660e8400-e29b-41d4-a716-446655440001

// Get records without this field
GET /v1/_fetchlistcategory?parentCategoryId=null

slug Filter

Type: String
Description: SEO-friendly unique slug for URL and search. Lowercase, hyphens only.
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/_fetchlistcategory?slug=john
// Matches: "John", "Johnny", "johnson", "McJohn", etc.

// Find records with multiple values (use multiple parameters)
GET /v1/_fetchlistcategory?slug=laptop&slug=phone&slug=tablet
// Matches records containing "laptop", "phone", or "tablet" anywhere in the field

// Find records without this field
GET /v1/_fetchlistcategory?slug=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 _fetchListCategory 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.

{isActive:true}

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).

[ createdAt 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, socketSettings, 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 _fetchListCategory 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
name String No Category name, e.g. ‘Automobiles’, ‘Electronics’.
parentCategoryId ID No References parent category for hierarchy. Top-level (root) categories have null.
slug String No SEO-friendly unique slug for URL and search. Lowercase, hyphens only.

REST Request

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

  axios({
    method: 'GET',
    url: '/v1/_fetchlistcategory',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section for usage examples)
        // name: '<value>' // Filter by name
        // parentCategoryId: '<value>' // Filter by parentCategoryId
        // slug: '<value>' // Filter by slug
            }
  });

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 categories 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": "categories",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"categories": [
		{
			"id": "ID",
			"description": "Text",
			"icon": "String",
			"name": "String",
			"parentCategoryId": "ID",
			"slug": "String",
			"sortOrder": "Integer",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID",
			"parent": [
				{
					"description": "Text",
					"icon": "String",
					"name": "String",
					"parentCategoryId": "ID",
					"slug": "String",
					"sortOrder": "Integer"
				},
				{},
				{}
			]
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Business API Design Specification - _fetch Listlocation

Business API Design Specification - _fetch Listlocation

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 _fetchListLocation 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 _fetchListLocation Business API is designed to handle a list operation on the Location data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

System API to fetch list of location records for frontend application. Auto-generated, not visible in design.

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 _fetchListLocation Business API includes a REST controller that can be triggered via the following route:

/v1/_fetchlistlocation

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 _fetchListLocation Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The _fetchListLocation 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 _fetchListLocation api supports 3 optional filter parameters for filtering list results using URL query parameters. These parameters are only available for list type APIs.

city Filter

Type: String
Description: City 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/_fetchlistlocation?city=john
// Matches: "John", "Johnny", "johnson", "McJohn", etc.

// Find records with multiple values (use multiple parameters)
GET /v1/_fetchlistlocation?city=laptop&city=phone&city=tablet
// Matches records containing "laptop", "phone", or "tablet" anywhere in the field

// Find records without this field
GET /v1/_fetchlistlocation?city=null

country Filter

Type: String
Description: Country name (typically ‘Turkey’).
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/_fetchlistlocation?country=john
// Matches: "John", "Johnny", "johnson", "McJohn", etc.

// Find records with multiple values (use multiple parameters)
GET /v1/_fetchlistlocation?country=laptop&country=phone&country=tablet
// Matches records containing "laptop", "phone", or "tablet" anywhere in the field

// Find records without this field
GET /v1/_fetchlistlocation?country=null

district Filter

Type: String
Description: District name, for fine-grained search.
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/_fetchlistlocation?district=john
// Matches: "John", "Johnny", "johnson", "McJohn", etc.

// Find records with multiple values (use multiple parameters)
GET /v1/_fetchlistlocation?district=laptop&district=phone&district=tablet
// Matches records containing "laptop", "phone", or "tablet" anywhere in the field

// Find records without this field
GET /v1/_fetchlistlocation?district=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 _fetchListLocation 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.

{isActive:true}

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).

[ createdAt 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, socketSettings, 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 _fetchListLocation 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
city String No City name.
country String No Country name (typically ‘Turkey’).
district String No District name, for fine-grained search.

REST Request

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

  axios({
    method: 'GET',
    url: '/v1/_fetchlistlocation',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section for usage examples)
        // city: '<value>' // Filter by city
        // country: '<value>' // Filter by country
        // district: '<value>' // Filter by district
            }
  });

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 locations 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": "locations",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"locations": [
		{
			"id": "ID",
			"city": "String",
			"country": "String",
			"district": "String",
			"latitude": "Double",
			"longitude": "Double",
			"postalCode": "String",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID"
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Conversation Service

Service Design Specification

Service Design Specification

clonesahibinden-conversation-service documentation Version: 1.0.1

Scope

This document provides a structured architectural overview of the conversation 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.

Conversation Service Settings

Manages user-to-user messaging threads tied to listings, with message storage, read/unread and moderation support.

Service Overview

This service is configured to listen for HTTP requests on port 3005, 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 clonesahibinden-conversation-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 clonesahibinden-conversation-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
conversationMessage A single message sent between two users within a conversation about a listing. Tracks sender, receiver, timestamps and read status. accessPrivate
conversationThread Private messaging thread between two users regarding a specific listing. Unique per (listing, user pair), order-invariant. Tracks last message time for inbox sorting. accessPrivate

conversationMessage Data Object

Object Overview

Description: A single message sent between two users within a conversation about a listing. Tracks sender, receiver, timestamps and read 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

Properties Schema

Property Type Required Description
content Text Yes Message text body. Sanitized before saving.
conversationThreadId ID Yes Parent thread for this message.
isRead Boolean Yes True if the receiver has read this message.
readAt Date No Timestamp when the receiver read the message (null if unread).
receiverId ID Yes User receiving the message (must be the other participant of the thread).
senderId ID Yes User sending the message (must be a participant of the thread).
sentAt Date Yes Timestamp when message was sent.

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

content conversationThreadId receiverId 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

isRead readAt

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

content conversationThreadId isRead readAt receiverId senderId sentAt

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

conversationThreadId receiverId senderId

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.

Cache Select Properties

conversationThreadId receiverId senderId

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.

Relation Properties

conversationThreadId receiverId senderId

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: Yes

conversationThread Data Object

Object Overview

Description: Private messaging thread between two users regarding a specific listing. Unique per (listing, user pair), order-invariant. Tracks last message time for inbox sorting.

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
lastMessageAt Date Yes Date/time of the latest message in the thread (for sorting inbox).
listingId ID Yes ID of the listing being discussed.
receiverId ID Yes User B in the conversation (order-invariant with senderId).
senderId ID Yes User A in the conversation (order-invariant with receiverId).

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

listingId receiverId senderId

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

lastMessageAt

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

lastMessageAt listingId receiverId senderId

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

lastMessageAt listingId receiverId senderId

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.

Cache Select Properties

listingId receiverId senderId

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.

Relation Properties

listingId receiverId senderId

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: Yes

Business Logic

conversation has got 10 Business APIs to manage its internal and crud logic. For the details of each business API refer to its chapter.

Edge Controllers

m2mCreateConversationMessage

Configuration:

REST Settings:


m2mBulkCreateConversationMessage

Configuration:

REST Settings:


m2mUpdateConversationMessageById

Configuration:

REST Settings:


m2mDeleteConversationMessageById

Configuration:

REST Settings:


m2mUpdateConversationMessageByQuery

Configuration:

REST Settings:


m2mDeleteConversationMessageByQuery

Configuration:

REST Settings:


m2mUpdateConversationMessageByIdList

Configuration:

REST Settings:


m2mCreateConversationThread

Configuration:

REST Settings:


m2mBulkCreateConversationThread

Configuration:

REST Settings:


m2mUpdateConversationThreadById

Configuration:

REST Settings:


m2mDeleteConversationThreadById

Configuration:

REST Settings:


m2mUpdateConversationThreadByQuery

Configuration:

REST Settings:


m2mDeleteConversationThreadByQuery

Configuration:

REST Settings:


m2mUpdateConversationThreadByIdList

Configuration:

REST Settings:



Service Library

Functions

No general functions defined.

Hook Functions

No hook functions defined.

Edge Functions

m2mCreateConversationMessage.js

module.exports = async (request) => {
        const { createConversationMessage } = require("dbLayer");
        const context = { session: request.session, requestId: request.requestId };
        const data = request.body?.data || request.data || request;
        const result = await createConversationMessage(data, context);
        return { status: 200, content: result };
      }

m2mBulkCreateConversationMessage.js

module.exports = async (request) => {
        const { createBulkConversationMessage } = require("dbLayer");
        const context = { session: request.session, requestId: request.requestId };
        const dataList = request.body?.dataList || request.dataList || (Array.isArray(request.body) ? request.body : [request.body]);
        if (!Array.isArray(dataList) || dataList.length === 0) {
          return { status: 400, message: "dataList must be a non-empty array" };
        }
        const result = await createBulkConversationMessage(dataList, context);
        return { status: 200, content: result };
      }

m2mUpdateConversationMessageById.js

module.exports = async (request) => {
        const { updateConversationMessageById } = require("dbLayer");
        const context = { session: request.session, requestId: request.requestId };
        const id = request.body?.id || request.params?.id || request.id;
        const dataClause = request.body?.dataClause || request.dataClause || request.body;
        if (dataClause && dataClause.id) delete dataClause.id;
        if (!id) {
          return { status: 400, message: "ID is required" };
        }
        const result = await updateConversationMessageById(id, dataClause, context);
        return { status: 200, content: result };
      }

m2mDeleteConversationMessageById.js

module.exports = async (request) => {
        const { deleteConversationMessageById } = require("dbLayer");
        const context = { session: request.session, requestId: request.requestId };
        const id = request.body?.id || request.params?.id || request.id;
        if (!id) {
          return { status: 400, message: "ID is required" };
        }
        const result = await deleteConversationMessageById(id, context);
        return { status: 200, content: result };
      }

m2mUpdateConversationMessageByQuery.js

module.exports = async (request) => {
        const { updateConversationMessageByQuery } = require("dbLayer");
        const context = { session: request.session, requestId: request.requestId };
        const dataClause = request.body?.dataClause || request.dataClause || request.body;
        const query = request.body?.query || request.query || {};
        if (!query || typeof query !== "object" || Object.keys(query).length === 0) {
          return { status: 400, message: "Query is required and must be a non-empty object" };
        }
        const result = await updateConversationMessageByQuery(dataClause, query, context);
        return { status: 200, content: result };
      }

m2mDeleteConversationMessageByQuery.js

module.exports = async (request) => {
        const { deleteConversationMessageByQuery } = require("dbLayer");
        const context = { session: request.session, requestId: request.requestId };
        const query = request.body?.query || request.query || {};
        if (!query || typeof query !== "object" || Object.keys(query).length === 0) {
          return { status: 400, message: "Query is required and must be a non-empty object" };
        }
        const result = await deleteConversationMessageByQuery(query, context);
        return { status: 200, content: result };
      }

m2mUpdateConversationMessageByIdList.js

module.exports = async (request) => {
        const { updateConversationMessageByIdList } = require("dbLayer");
        const context = { session: request.session, requestId: request.requestId };
        const idList = request.body?.idList || request.idList || [];
        const dataClause = request.body?.dataClause || request.dataClause || request.body;
        if (dataClause && dataClause.idList) delete dataClause.idList;
        if (!Array.isArray(idList) || idList.length === 0) {
          return { status: 400, message: "idList must be a non-empty array" };
        }
        const result = await updateConversationMessageByIdList(idList, dataClause, context);
        return { status: 200, content: result };
      }

m2mCreateConversationThread.js

module.exports = async (request) => {
        const { createConversationThread } = require("dbLayer");
        const context = { session: request.session, requestId: request.requestId };
        const data = request.body?.data || request.data || request;
        const result = await createConversationThread(data, context);
        return { status: 200, content: result };
      }

m2mBulkCreateConversationThread.js

module.exports = async (request) => {
        const { createBulkConversationThread } = require("dbLayer");
        const context = { session: request.session, requestId: request.requestId };
        const dataList = request.body?.dataList || request.dataList || (Array.isArray(request.body) ? request.body : [request.body]);
        if (!Array.isArray(dataList) || dataList.length === 0) {
          return { status: 400, message: "dataList must be a non-empty array" };
        }
        const result = await createBulkConversationThread(dataList, context);
        return { status: 200, content: result };
      }

m2mUpdateConversationThreadById.js

module.exports = async (request) => {
        const { updateConversationThreadById } = require("dbLayer");
        const context = { session: request.session, requestId: request.requestId };
        const id = request.body?.id || request.params?.id || request.id;
        const dataClause = request.body?.dataClause || request.dataClause || request.body;
        if (dataClause && dataClause.id) delete dataClause.id;
        if (!id) {
          return { status: 400, message: "ID is required" };
        }
        const result = await updateConversationThreadById(id, dataClause, context);
        return { status: 200, content: result };
      }

m2mDeleteConversationThreadById.js

module.exports = async (request) => {
        const { deleteConversationThreadById } = require("dbLayer");
        const context = { session: request.session, requestId: request.requestId };
        const id = request.body?.id || request.params?.id || request.id;
        if (!id) {
          return { status: 400, message: "ID is required" };
        }
        const result = await deleteConversationThreadById(id, context);
        return { status: 200, content: result };
      }

m2mUpdateConversationThreadByQuery.js

module.exports = async (request) => {
        const { updateConversationThreadByQuery } = require("dbLayer");
        const context = { session: request.session, requestId: request.requestId };
        const dataClause = request.body?.dataClause || request.dataClause || request.body;
        const query = request.body?.query || request.query || {};
        if (!query || typeof query !== "object" || Object.keys(query).length === 0) {
          return { status: 400, message: "Query is required and must be a non-empty object" };
        }
        const result = await updateConversationThreadByQuery(dataClause, query, context);
        return { status: 200, content: result };
      }

m2mDeleteConversationThreadByQuery.js

module.exports = async (request) => {
        const { deleteConversationThreadByQuery } = require("dbLayer");
        const context = { session: request.session, requestId: request.requestId };
        const query = request.body?.query || request.query || {};
        if (!query || typeof query !== "object" || Object.keys(query).length === 0) {
          return { status: 400, message: "Query is required and must be a non-empty object" };
        }
        const result = await deleteConversationThreadByQuery(query, context);
        return { status: 200, content: result };
      }

m2mUpdateConversationThreadByIdList.js

module.exports = async (request) => {
        const { updateConversationThreadByIdList } = require("dbLayer");
        const context = { session: request.session, requestId: request.requestId };
        const idList = request.body?.idList || request.idList || [];
        const dataClause = request.body?.dataClause || request.dataClause || request.body;
        if (dataClause && dataClause.idList) delete dataClause.idList;
        if (!Array.isArray(idList) || idList.length === 0) {
          return { status: 400, message: "idList must be a non-empty array" };
        }
        const result = await updateConversationThreadByIdList(idList, dataClause, context);
        return { status: 200, content: result };
      }

Templates

No templates defined.

Assets

No assets defined.

Public Assets

No public assets defined.


Event Emission


Integration Patterns

Deployment Considerations

Environment Configuration

Implementation Guidelines

Development Workflow

  1. Data Model Implementation: Generate database schema from data object definitions
  2. CRUD Route Generation: Implement auto-generated routes with custom logic
  3. Custom Logic Integration: Implement hook functions and edge functions
  4. Authentication Integration: Configure with project-level authentication
  5. Testing: Unit and integration testing for all components

Code Generation Expectations

Custom Code Integration Points

Testing Strategy

Unit Testing

Integration Testing

Performance Testing


Appendices

Data Type Reference

Type Description Storage
ID Unique identifier UUID (SQL) / ObjectID (NoSQL)
String Short text (≤255 chars) VARCHAR
Text Long-form text TEXT
Integer 32-bit whole numbers INT
Boolean True/false values BOOLEAN
Double 64-bit floating point DOUBLE
Float 32-bit floating point FLOAT
Short 16-bit integers SMALLINT
Object JSON object JSONB (PostgreSQL) / Object (MongoDB)
Date ISO 8601 timestamp TIMESTAMP
Enum Fixed numeric values SMALLINT with lookup

Enum Value Mappings

Request Locations

HTTP Methods

Edge Function Signature

async function edgeFunction(request) {
  // Custom request processing
  // Return response object or throw error
  return {
    data: {},
    status: 200,
    message: "Success"
  };
}

This document was generated from the service architecture definition and should be kept in sync with implementation changes.


REST API GUIDE

REST API GUIDE

clonesahibinden-conversation-service

Version: 1.0.1

Manages user-to-user messaging threads tied to listings, with message storage, read/unread and moderation support.

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 Conversation Service’s REST API. This document is designed to provide a comprehensive guide to interfacing with our Conversation Service exclusively through RESTful API endpoints.

Intended Audience

This documentation is intended for developers and integrators who are looking to interact with the Conversation Service via HTTP requests for purposes such as creating, updating, deleting and querying Conversation 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 Conversation 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 Conversation 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 clonesahibinden-access-token
Cookie clonesahibinden-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 Conversation 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 Conversation service.

This service is configured to listen for HTTP requests on port 3005, 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 Conversation 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 Conversation 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 Conversation 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 Conversation 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

Conversation 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.

ConversationMessage resource

Resource Definition : A single message sent between two users within a conversation about a listing. Tracks sender, receiver, timestamps and read status. ConversationMessage Resource Properties

Name Type Required Default Definition
content Text Message text body. Sanitized before saving.
conversationThreadId ID Parent thread for this message.
isRead Boolean True if the receiver has read this message.
readAt Date Timestamp when the receiver read the message (null if unread).
receiverId ID User receiving the message (must be the other participant of the thread).
senderId ID User sending the message (must be a participant of the thread).
sentAt Date Timestamp when message was sent.

ConversationThread resource

Resource Definition : Private messaging thread between two users regarding a specific listing. Unique per (listing, user pair), order-invariant. Tracks last message time for inbox sorting. ConversationThread Resource Properties

Name Type Required Default Definition
lastMessageAt Date Date/time of the latest message in the thread (for sorting inbox).
listingId ID ID of the listing being discussed.
receiverId ID User B in the conversation (order-invariant with senderId).
senderId ID User A in the conversation (order-invariant with receiverId).

Business Api

Create Conversationmessage API

Send a new message in a conversation. Only thread participants can send; updates thread’s lastMessageAt.

API Frontend Description By The Backend Architect

Used when a user sends a message in a conversation (thread). On success, new message appears in thread; unread by receiver.

Rest Route

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

/v1/conversationmessages

Rest Request Parameters

The createConversationMessage api has got 7 regular request parameters

Parameter Type Required Population
content Text true request.body?.[“content”]
conversationThreadId ID true request.body?.[“conversationThreadId”]
isRead Boolean true request.body?.[“isRead”]
readAt Date false request.body?.[“readAt”]
receiverId ID true request.body?.[“receiverId”]
senderId ID true request.body?.[“senderId”]
sentAt Date true request.body?.[“sentAt”]
content : Message text body. Sanitized before saving.
conversationThreadId : Parent thread for this message.
isRead : True if the receiver has read this message.
readAt : Timestamp when the receiver read the message (null if unread).
receiverId : User receiving the message (must be the other participant of the thread).
senderId : User sending the message (must be a participant of the thread).
sentAt : Timestamp when message was sent.

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

  axios({
    method: 'POST',
    url: '/v1/conversationmessages',
    data: {
            content:"Text",  
            conversationThreadId:"ID",  
            isRead:"Boolean",  
            readAt:"Date",  
            receiverId:"ID",  
            senderId:"ID",  
            sentAt:"Date",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "conversationMessage",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"conversationMessage": {
		"id": "ID",
		"content": "Text",
		"conversationThreadId": "ID",
		"isRead": "Boolean",
		"readAt": "Date",
		"receiverId": "ID",
		"senderId": "ID",
		"sentAt": "Date",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Create Conversationthread API

Starts a new conversation thread between two users for a specific listing. Prevents duplicate threads for the same user pair/listing.

API Frontend Description By The Backend Architect

Invoked when user contacts seller about a listing. If an existing thread exists for this user pair/listing (any order), it is reused. Only listing owner or buyers can start a thread.

Rest Route

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

/v1/conversationthreads

Rest Request Parameters

The createConversationThread api has got 4 regular request parameters

Parameter Type Required Population
lastMessageAt Date true request.body?.[“lastMessageAt”]
listingId ID true request.body?.[“listingId”]
receiverId ID true request.body?.[“receiverId”]
senderId ID true request.body?.[“senderId”]
lastMessageAt : Date/time of the latest message in the thread (for sorting inbox).
listingId : ID of the listing being discussed.
receiverId : User B in the conversation (order-invariant with senderId).
senderId : User A in the conversation (order-invariant with receiverId).

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

  axios({
    method: 'POST',
    url: '/v1/conversationthreads',
    data: {
            lastMessageAt:"Date",  
            listingId:"ID",  
            receiverId:"ID",  
            senderId:"ID",  
    
    },
    params: {
    
        }
  });

REST Response

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

Delete Conversationmessage API

Soft-deletes a message. Only moderator/admins can fully delete; users may hide/delete for self (future phase).

API Frontend Description By The Backend Architect

Used for moderation; message remains for audit trail/history.

Rest Route

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

/v1/conversationmessages/:conversationMessageId

Rest Request Parameters

The deleteConversationMessage api has got 1 regular request parameter

Parameter Type Required Population
conversationMessageId ID true request.params?.[“conversationMessageId”]
conversationMessageId : 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/conversationmessages/:conversationMessageId

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

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "conversationMessage",
	"method": "DELETE",
	"action": "delete",
	"appVersion": "Version",
	"rowCount": 1,
	"conversationMessage": {
		"id": "ID",
		"content": "Text",
		"conversationThreadId": "ID",
		"isRead": "Boolean",
		"readAt": "Date",
		"receiverId": "ID",
		"senderId": "ID",
		"sentAt": "Date",
		"isActive": false,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Get Conversationmessage API

Fetch a single message by ID. Only accessible to participants or moderators/admins.

API Frontend Description By The Backend Architect

Loads a message for display in UI. Fails if not participant or staff.

Rest Route

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

/v1/conversationmessages/:conversationMessageId

Rest Request Parameters

The getConversationMessage api has got 1 regular request parameter

Parameter Type Required Population
conversationMessageId ID true request.params?.[“conversationMessageId”]
conversationMessageId : 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/conversationmessages/:conversationMessageId

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

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "conversationMessage",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"conversationMessage": {
		"id": "ID",
		"content": "Text",
		"conversationThreadId": "ID",
		"isRead": "Boolean",
		"readAt": "Date",
		"receiverId": "ID",
		"senderId": "ID",
		"sentAt": "Date",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Get Conversationthread API

Get a conversation thread by ID. Only visible to participants or staff.

API Frontend Description By The Backend Architect

Shows full thread info for inbox/detail view. Fails if user does not participate or is not moderator/admin.

Rest Route

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

/v1/conversationthreads/:conversationThreadId

Rest Request Parameters

The getConversationThread api has got 1 regular request parameter

Parameter Type Required Population
conversationThreadId ID true request.params?.[“conversationThreadId”]
conversationThreadId : 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/conversationthreads/:conversationThreadId

  axios({
    method: 'GET',
    url: `/v1/conversationthreads/${conversationThreadId}`,
    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": "conversationThread",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"conversationThread": {
		"listing": {
			"status": "Enum",
			"status_idx": "Integer",
			"title": "String",
			"userId": "ID"
		},
		"isActive": true
	}
}

List Conversationmessages API

List all messages in a thread, sorted oldest to newest. Only accessible to thread participants or staff.

API Frontend Description By The Backend Architect

Loads the chat history in UI for reading; includes isRead, sender info, etc. Used for conversation detail view.

Rest Route

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

/v1/listconversationmessages/:conversationThreadId

Rest Request Parameters

The listConversationMessages api has got 1 regular request parameter

Parameter Type Required Population
conversationThreadId ID true request.query?.[“conversationThreadId”]
conversationThreadId : Thread to load messages from.

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

  axios({
    method: 'GET',
    url: `/v1/listconversationmessages/${conversationThreadId}`,
    data: {
    
    },
    params: {
             conversationThreadId:'"ID"',  
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "conversationMessages",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"conversationMessages": [
		{
			"id": "ID",
			"content": "Text",
			"conversationThreadId": "ID",
			"isRead": "Boolean",
			"readAt": "Date",
			"receiverId": "ID",
			"senderId": "ID",
			"sentAt": "Date",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID"
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

List Conversationthreads API

List all threads a user participates in, most recent first. Also used for moderator search/all-list.

API Frontend Description By The Backend Architect

Shows all user’s conversation threads in inbox. Moderators can search all.

Rest Route

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

/v1/conversationthreads

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

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

  axios({
    method: 'GET',
    url: '/v1/conversationthreads',
    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": "conversationThreads",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"conversationThreads": [
		{
			"listing": [
				{
					"status": "Enum",
					"status_idx": "Integer",
					"title": "String",
					"userId": "ID"
				},
				{},
				{}
			],
			"isActive": true
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Mark Messageasread API

Marks a message as read (isRead=true, readAt=now); only allowed for receiver.

API Frontend Description By The Backend Architect

When viewing messages, receiver marks message as read – triggers unread count decrement in UI, updates message status.

Rest Route

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

/v1/markmessageasread/:conversationMessageId

Rest Request Parameters

The markMessageAsRead api has got 3 regular request parameters

Parameter Type Required Population
conversationMessageId ID true request.params?.[“conversationMessageId”]
isRead Boolean false request.body?.[“isRead”]
readAt Date false request.body?.[“readAt”]
conversationMessageId : This id paremeter is used to select the required data object that will be updated
isRead : True if the receiver has read this message.
readAt : Timestamp when the receiver read the message (null if unread).

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

  axios({
    method: 'PATCH',
    url: `/v1/markmessageasread/${conversationMessageId}`,
    data: {
            isRead:"Boolean",  
            readAt:"Date",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "conversationMessage",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"conversationMessage": {
		"id": "ID",
		"content": "Text",
		"conversationThreadId": "ID",
		"isRead": "Boolean",
		"readAt": "Date",
		"receiverId": "ID",
		"senderId": "ID",
		"sentAt": "Date",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

_fetch Listconversationmessage API

System API to fetch list of conversationMessage records for frontend application. Auto-generated, not visible in design.

Rest Route

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

/v1/_fetchlistconversationmessage

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

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

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

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "conversationMessages",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"conversationMessages": [
		{
			"id": "ID",
			"content": "Text",
			"conversationThreadId": "ID",
			"isRead": "Boolean",
			"readAt": "Date",
			"receiverId": "ID",
			"senderId": "ID",
			"sentAt": "Date",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID",
			"thread": [
				{
					"lastMessageAt": "Date",
					"listingId": "ID",
					"receiverId": "ID",
					"senderId": "ID"
				},
				{},
				{}
			],
			"receiverUser": [
				{
					"fullname": "String"
				},
				{},
				{}
			],
			"senderUser": [
				{
					"fullname": "String"
				},
				{},
				{}
			]
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

_fetch Listconversationthread API

System API to fetch list of conversationThread records for frontend application. Auto-generated, not visible in design.

Rest Route

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

/v1/_fetchlistconversationthread

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

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

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

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "conversationThreads",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"conversationThreads": [
		{
			"id": "ID",
			"lastMessageAt": "Date",
			"listingId": "ID",
			"receiverId": "ID",
			"senderId": "ID",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID",
			"listing": [
				{
					"attributes": "Object",
					"categoryId": "ID",
					"condition": "Enum",
					"condition_idx": "Integer",
					"contactEmail": "String",
					"contactPhone": "String",
					"currency": "String",
					"description": "Text",
					"expiresAt": "Date",
					"favoriteCount": "Integer",
					"isPremium": "Boolean",
					"listingType": "Enum",
					"listingType_idx": "Integer",
					"locationId": "ID",
					"_paymentConfirmation": "String",
					"premiumExpiry": "Date",
					"premiumType": "Enum",
					"premiumType_idx": "Integer",
					"price": "Double",
					"status": "Enum",
					"status_idx": "Integer",
					"subcategoryId": "ID",
					"title": "String",
					"userId": "ID",
					"viewsCount": "Integer"
				},
				{},
				{}
			],
			"receiverUser": [
				{
					"fullname": "String"
				},
				{},
				{}
			],
			"senderUser": [
				{
					"fullname": "String"
				},
				{},
				{}
			]
		},
		{},
		{}
	],
	"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

clonesahibinden-conversation-service

Manages user-to-user messaging threads tied to listings, with message storage, read/unread and moderation support.

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 Conversation Service Event descriptions. This guide is dedicated to detailing how to subscribe to and listen for state changes within the Conversation Service, offering an exclusive focus on event subscription mechanisms.

Intended Audience

This documentation is aimed at developers and integrators looking to monitor Conversation Service state changes. It is especially relevant for those wishing to implement or enhance business logic based on interactions with Conversation 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 Conversation 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 conversationMessage-created

Event topic: clonesahibinden-conversation-service-dbevent-conversationmessage-created

This event is triggered upon the creation of a conversationMessage data object in the database. The event payload encompasses the newly created data, encapsulated within the root of the paylod.

Event payload:

{"id":"ID","content":"Text","conversationThreadId":"ID","isRead":"Boolean","readAt":"Date","receiverId":"ID","senderId":"ID","sentAt":"Date","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

DbEvent conversationMessage-updated

Event topic: clonesahibinden-conversation-service-dbevent-conversationmessage-updated

Activation of this event follows the update of a conversationMessage data object. The payload contains the updated information under the conversationMessage attribute, along with the original data prior to update, labeled as old_conversationMessage and also you can find the old and new versions of updated-only portion of the data…

Event payload:

{
old_conversationMessage:{"id":"ID","content":"Text","conversationThreadId":"ID","isRead":"Boolean","readAt":"Date","receiverId":"ID","senderId":"ID","sentAt":"Date","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},
conversationMessage:{"id":"ID","content":"Text","conversationThreadId":"ID","isRead":"Boolean","readAt":"Date","receiverId":"ID","senderId":"ID","sentAt":"Date","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},
oldDataValues,
newDataValues
}

DbEvent conversationMessage-deleted

Event topic: clonesahibinden-conversation-service-dbevent-conversationmessage-deleted

This event announces the deletion of a conversationMessage 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","content":"Text","conversationThreadId":"ID","isRead":"Boolean","readAt":"Date","receiverId":"ID","senderId":"ID","sentAt":"Date","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

DbEvent conversationThread-created

Event topic: clonesahibinden-conversation-service-dbevent-conversationthread-created

This event is triggered upon the creation of a conversationThread data object in the database. The event payload encompasses the newly created data, encapsulated within the root of the paylod.

Event payload:

{"id":"ID","lastMessageAt":"Date","listingId":"ID","receiverId":"ID","senderId":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

DbEvent conversationThread-updated

Event topic: clonesahibinden-conversation-service-dbevent-conversationthread-updated

Activation of this event follows the update of a conversationThread data object. The payload contains the updated information under the conversationThread attribute, along with the original data prior to update, labeled as old_conversationThread and also you can find the old and new versions of updated-only portion of the data…

Event payload:

{
old_conversationThread:{"id":"ID","lastMessageAt":"Date","listingId":"ID","receiverId":"ID","senderId":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},
conversationThread:{"id":"ID","lastMessageAt":"Date","listingId":"ID","receiverId":"ID","senderId":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},
oldDataValues,
newDataValues
}

DbEvent conversationThread-deleted

Event topic: clonesahibinden-conversation-service-dbevent-conversationthread-deleted

This event announces the deletion of a conversationThread 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","lastMessageAt":"Date","listingId":"ID","receiverId":"ID","senderId":"ID","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

ElasticSearch Index Events

Within the Conversation 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 conversationmessage-created

Event topic: elastic-index-clonesahibinden_conversationmessage-created

Event payload:

{"id":"ID","content":"Text","conversationThreadId":"ID","isRead":"Boolean","readAt":"Date","receiverId":"ID","senderId":"ID","sentAt":"Date","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event conversationmessage-updated

Event topic: elastic-index-clonesahibinden_conversationmessage-created

Event payload:

{"id":"ID","content":"Text","conversationThreadId":"ID","isRead":"Boolean","readAt":"Date","receiverId":"ID","senderId":"ID","sentAt":"Date","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event conversationmessage-deleted

Event topic: elastic-index-clonesahibinden_conversationmessage-deleted

Event payload:

{"id":"ID","content":"Text","conversationThreadId":"ID","isRead":"Boolean","readAt":"Date","receiverId":"ID","senderId":"ID","sentAt":"Date","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event conversationmessage-extended

Event topic: elastic-index-clonesahibinden_conversationmessage-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 conversationmessage-created

Event topic : clonesahibinden-conversation-service-conversationmessage-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 conversationMessage data object itself.

The following JSON included in the payload illustrates the fullest representation of the conversationMessage 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":"conversationMessage","method":"POST","action":"create","appVersion":"Version","rowCount":1,"conversationMessage":{"id":"ID","content":"Text","conversationThreadId":"ID","isRead":"Boolean","readAt":"Date","receiverId":"ID","senderId":"ID","sentAt":"Date","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event conversationthread-created

Event topic : clonesahibinden-conversation-service-conversationthread-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 conversationThread data object itself.

The following JSON included in the payload illustrates the fullest representation of the conversationThread 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":"conversationThread","method":"POST","action":"create","appVersion":"Version","rowCount":1,"conversationThread":{"id":"ID","lastMessageAt":"Date","listingId":"ID","receiverId":"ID","senderId":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event conversationmessage-deleted

Event topic : clonesahibinden-conversation-service-conversationmessage-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 conversationMessage data object itself.

The following JSON included in the payload illustrates the fullest representation of the conversationMessage 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":"conversationMessage","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"conversationMessage":{"id":"ID","content":"Text","conversationThreadId":"ID","isRead":"Boolean","readAt":"Date","receiverId":"ID","senderId":"ID","sentAt":"Date","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event messageasread-marked

Event topic : clonesahibinden-conversation-service-messageasread-marked

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 conversationMessage data object itself.

The following JSON included in the payload illustrates the fullest representation of the conversationMessage 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":"conversationMessage","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"conversationMessage":{"id":"ID","content":"Text","conversationThreadId":"ID","isRead":"Boolean","readAt":"Date","receiverId":"ID","senderId":"ID","sentAt":"Date","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Index Event conversationthread-created

Event topic: elastic-index-clonesahibinden_conversationthread-created

Event payload:

{"id":"ID","lastMessageAt":"Date","listingId":"ID","receiverId":"ID","senderId":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event conversationthread-updated

Event topic: elastic-index-clonesahibinden_conversationthread-created

Event payload:

{"id":"ID","lastMessageAt":"Date","listingId":"ID","receiverId":"ID","senderId":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event conversationthread-deleted

Event topic: elastic-index-clonesahibinden_conversationthread-deleted

Event payload:

{"id":"ID","lastMessageAt":"Date","listingId":"ID","receiverId":"ID","senderId":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event conversationthread-extended

Event topic: elastic-index-clonesahibinden_conversationthread-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 conversationmessage-created

Event topic : clonesahibinden-conversation-service-conversationmessage-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 conversationMessage data object itself.

The following JSON included in the payload illustrates the fullest representation of the conversationMessage 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":"conversationMessage","method":"POST","action":"create","appVersion":"Version","rowCount":1,"conversationMessage":{"id":"ID","content":"Text","conversationThreadId":"ID","isRead":"Boolean","readAt":"Date","receiverId":"ID","senderId":"ID","sentAt":"Date","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event conversationthread-created

Event topic : clonesahibinden-conversation-service-conversationthread-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 conversationThread data object itself.

The following JSON included in the payload illustrates the fullest representation of the conversationThread 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":"conversationThread","method":"POST","action":"create","appVersion":"Version","rowCount":1,"conversationThread":{"id":"ID","lastMessageAt":"Date","listingId":"ID","receiverId":"ID","senderId":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event conversationmessage-deleted

Event topic : clonesahibinden-conversation-service-conversationmessage-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 conversationMessage data object itself.

The following JSON included in the payload illustrates the fullest representation of the conversationMessage 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":"conversationMessage","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"conversationMessage":{"id":"ID","content":"Text","conversationThreadId":"ID","isRead":"Boolean","readAt":"Date","receiverId":"ID","senderId":"ID","sentAt":"Date","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event messageasread-marked

Event topic : clonesahibinden-conversation-service-messageasread-marked

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 conversationMessage data object itself.

The following JSON included in the payload illustrates the fullest representation of the conversationMessage 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":"conversationMessage","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"conversationMessage":{"id":"ID","content":"Text","conversationThreadId":"ID","isRead":"Boolean","readAt":"Date","receiverId":"ID","senderId":"ID","sentAt":"Date","isActive":true,"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 conversationMessage

Service Design Specification - Object Design for conversationMessage

clonesahibinden-conversation-service documentation

Document Overview

This document outlines the object design for the conversationMessage model in our application. It includes details about the model’s attributes, relationships, and any specific validation or business logic that applies.

conversationMessage Data Object

Object Overview

Description: A single message sent between two users within a conversation about a listing. Tracks sender, receiver, timestamps and read 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

Properties Schema

Property Type Required Description
content Text Yes Message text body. Sanitized before saving.
conversationThreadId ID Yes Parent thread for this message.
isRead Boolean Yes True if the receiver has read this message.
readAt Date No Timestamp when the receiver read the message (null if unread).
receiverId ID Yes User receiving the message (must be the other participant of the thread).
senderId ID Yes User sending the message (must be a participant of the thread).
sentAt Date Yes Timestamp when message was sent.

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

content conversationThreadId receiverId 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

isRead readAt

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

content conversationThreadId isRead readAt receiverId senderId sentAt

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

conversationThreadId receiverId senderId

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.

Cache Select Properties

conversationThreadId receiverId senderId

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.

Relation Properties

conversationThreadId receiverId senderId

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: Yes


Service Design Specification - Object Design for conversationThread

Service Design Specification - Object Design for conversationThread

clonesahibinden-conversation-service documentation

Document Overview

This document outlines the object design for the conversationThread model in our application. It includes details about the model’s attributes, relationships, and any specific validation or business logic that applies.

conversationThread Data Object

Object Overview

Description: Private messaging thread between two users regarding a specific listing. Unique per (listing, user pair), order-invariant. Tracks last message time for inbox sorting.

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
lastMessageAt Date Yes Date/time of the latest message in the thread (for sorting inbox).
listingId ID Yes ID of the listing being discussed.
receiverId ID Yes User B in the conversation (order-invariant with senderId).
senderId ID Yes User A in the conversation (order-invariant with receiverId).

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

listingId receiverId senderId

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

lastMessageAt

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

lastMessageAt listingId receiverId senderId

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

lastMessageAt listingId receiverId senderId

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.

Cache Select Properties

listingId receiverId senderId

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.

Relation Properties

listingId receiverId senderId

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: Yes


Business APIs

Business API Design Specification - Create Conversationmessage

Business API Design Specification - Create Conversationmessage

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 createConversationMessage 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 createConversationMessage Business API is designed to handle a create operation on the ConversationMessage 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 new message in a conversation. Only thread participants can send; updates thread’s lastMessageAt.

API Frontend Description By The Backend Architect

Used when a user sends a message in a conversation (thread). On success, new message appears in thread; unread by receiver.

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 createConversationMessage Business API includes a REST controller that can be triggered via the following route:

/v1/conversationmessages

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 createConversationMessage Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The createConversationMessage 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
conversationMessageId ID No - body conversationMessageId
Description: This id paremeter is used to create the data object with a given specific id. Leave null for automatic id.
content Text Yes - body content
Description: Message text body. Sanitized before saving.
conversationThreadId ID Yes - body conversationThreadId
Description: Parent thread for this message.
isRead Boolean Yes - body isRead
Description: True if the receiver has read this message.
readAt Date No - body readAt
Description: Timestamp when the receiver read the message (null if unread).
receiverId ID Yes - body receiverId
Description: User receiving the message (must be the other participant of the thread).
senderId ID Yes - body senderId
Description: User sending the message (must be a participant of the thread).
sentAt Date Yes - body sentAt
Description: Timestamp when message was sent.

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 createConversationMessage 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.conversationMessageId,
  content: this.content,
  conversationThreadId: this.conversationThreadId,
  isRead: this.isRead,
  readAt: this.readAt,
  receiverId: this.receiverId,
  senderId: this.senderId,
  sentAt: this.sentAt,
  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, socketSettings, cronSettings

[2] Action : fetchThread

Action Type: FetchObjectAction

Fetch parent conversation thread.

class Api {
  async fetchThread() {
    // Fetch Object on childObject conversationThread

    const userQuery = {
      $and: [{ id: this.conversationThreadId }, { isActive: true }],
    };
    const { convertUserQueryToSequelizeQuery } = require("common");
    const scriptQuery = convertUserQueryToSequelizeQuery(userQuery);

    // get object from db
    const data = await getConversationThreadByQuery(scriptQuery);

    if (!data) {
      throw new NotFoundError(
        "errMsg_FethcedObjectNotFound:conversationThread",
      );
    }

    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] 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 : validateParticipants

Action Type: ValidationAction

Sender or receiver must match session; only allowed for participants.

class Api {
  async validateParticipants() {
    if (this.checkAbsolute()) return true;

    const isValid =
      this.session.userId === this.senderId ||
      this.session.userId === this.receiverId ||
      true;

    if (!isValid) {
      throw new ForbiddenError(
        "Only conversation participants may send message.",
      );
    }
    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] Step : mainCreateOperation

Manager executes the database insert operation, updates indexes/caches, and triggers internal post-processing like linked default records.


[10] Action : updateThreadLastMessageAt

Action Type: UpdateCrudAction

Update thread’s lastMessageAt to now after new message.

class Api {
  async updateThreadLastMessageAt() {
    // Aggregated Update Operation on childObject conversationThread

    const params = {
      lastMessageAt: new Date(),
    };
    const userQuery = { id: this.conversationThreadId };

    const { convertUserQueryToSequelizeQuery } = require("common");
    const query = convertUserQueryToSequelizeQuery(userQuery);

    const result = await updateConversationThreadByQuery(params, query, this);
    if (!result) return null;

    // if updated record is in main data update main data
    if (this.dbResult) {
      for (const item of result) {
        if (item.id == this.dbResult.id) {
          Object.assign(this.dbResult, item);
          this.conversationMessage = this.dbResult;
        }
      }
    }
    if (result.length == 0) return null;
    if (result.length == 1) return result[0];
    return result;
  }
}

[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 createConversationMessage api has got 7 regular client parameters

Parameter Type Required Population
content Text true request.body?.[“content”]
conversationThreadId ID true request.body?.[“conversationThreadId”]
isRead Boolean true request.body?.[“isRead”]
readAt Date false request.body?.[“readAt”]
receiverId ID true request.body?.[“receiverId”]
senderId ID true request.body?.[“senderId”]
sentAt Date true request.body?.[“sentAt”]

REST Request

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

  axios({
    method: 'POST',
    url: '/v1/conversationmessages',
    data: {
            content:"Text",  
            conversationThreadId:"ID",  
            isRead:"Boolean",  
            readAt:"Date",  
            receiverId:"ID",  
            senderId:"ID",  
            sentAt:"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 conversationMessage 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": "conversationMessage",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"conversationMessage": {
		"id": "ID",
		"content": "Text",
		"conversationThreadId": "ID",
		"isRead": "Boolean",
		"readAt": "Date",
		"receiverId": "ID",
		"senderId": "ID",
		"sentAt": "Date",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Business API Design Specification - Create Conversationthread

Business API Design Specification - Create Conversationthread

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 createConversationThread 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 createConversationThread Business API is designed to handle a create operation on the ConversationThread data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

Starts a new conversation thread between two users for a specific listing. Prevents duplicate threads for the same user pair/listing.

API Frontend Description By The Backend Architect

Invoked when user contacts seller about a listing. If an existing thread exists for this user pair/listing (any order), it is reused. Only listing owner or buyers can start a thread.

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 createConversationThread Business API includes a REST controller that can be triggered via the following route:

/v1/conversationthreads

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 createConversationThread Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The createConversationThread 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
conversationThreadId ID No - body conversationThreadId
Description: This id paremeter is used to create the data object with a given specific id. Leave null for automatic id.
lastMessageAt Date Yes - body lastMessageAt
Description: Date/time of the latest message in the thread (for sorting inbox).
listingId ID Yes - body listingId
Description: ID of the listing being discussed.
receiverId ID Yes - body receiverId
Description: User B in the conversation (order-invariant with senderId).
senderId ID Yes - body senderId
Description: User A in the conversation (order-invariant with receiverId).

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 createConversationThread 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.conversationThreadId,
  lastMessageAt: this.lastMessageAt,
  listingId: this.listingId,
  receiverId: this.receiverId,
  senderId: this.senderId,
  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, socketSettings, cronSettings

[2] Action : fetchListing

Action Type: FetchObjectAction

Fetch related listing.

class Api {
  async fetchListing() {
    // Fetch Object on childObject listing

    const userQuery = {
      $and: [{ id: this.listingId }, { isActive: true }],
    };
    const { convertUserQueryToElasticQuery } = require("common");
    const scriptQuery = convertUserQueryToElasticQuery(userQuery);

    const elasticIndex = new ElasticIndexer("listing");
    const data = await elasticIndex.getOne(scriptQuery);

    if (!data) {
      throw new NotFoundError("errMsg_FethcedObjectNotFound:listing");
    }

    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] 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 : validateParticipants

Action Type: ValidationAction

Validate that neither participant is trying to chat with self, both are not listing owner, and IDs are valid.

class Api {
  async validateParticipants() {
    const isValid =
      this.senderId !== this.receiverId &&
      (this.senderId === this.session.userId ||
        this.receiverId === this.session.userId) &&
      this.listing.userId !== this.session.userId
        ? true
        : true;

    if (!isValid) {
      throw new BadRequestError(
        "Sender and receiver must be distinct and participate, only listing owner or buyers can start thread.",
      );
    }
    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 : checkDuplicateThread

Action Type: SearchObjectAction

Check for existing thread for listing and user pair (order-independent).

class Api {
  // Code for Search Object Action
  async checkDuplicateThread() {
    // Search objects from conversationThread

    const scriptQuery = {
      multi_match: {
        query: null,
        fields: [],
        fuzziness: "AUTO",
      },
    };

    console.log("SearchObject Query", scriptQuery);

    const elasticIndex = new ElasticIndexer("conversationThread");

    const searchResult = await elasticIndex.getDataByPage(0, 500, scriptQuery);
    console.log("SearchObject Result", searchResult);
    if (!searchResult) return [];

    return searchResult.map((item) => item.id);
  }
}

[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 createConversationThread api has got 4 regular client parameters

Parameter Type Required Population
lastMessageAt Date true request.body?.[“lastMessageAt”]
listingId ID true request.body?.[“listingId”]
receiverId ID true request.body?.[“receiverId”]
senderId ID true request.body?.[“senderId”]

REST Request

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

  axios({
    method: 'POST',
    url: '/v1/conversationthreads',
    data: {
            lastMessageAt:"Date",  
            listingId:"ID",  
            receiverId:"ID",  
            senderId:"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 conversationThread 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": "conversationThread",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"conversationThread": {
		"id": "ID",
		"lastMessageAt": "Date",
		"listingId": "ID",
		"receiverId": "ID",
		"senderId": "ID",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Business API Design Specification - Delete Conversationmessage

Business API Design Specification - Delete Conversationmessage

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 deleteConversationMessage 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 deleteConversationMessage Business API is designed to handle a delete operation on the ConversationMessage data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

Soft-deletes a message. Only moderator/admins can fully delete; users may hide/delete for self (future phase).

API Frontend Description By The Backend Architect

Used for moderation; message remains for audit trail/history.

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 deleteConversationMessage Business API includes a REST controller that can be triggered via the following route:

/v1/conversationmessages/:conversationMessageId

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 deleteConversationMessage Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The deleteConversationMessage 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
conversationMessageId ID Yes - urlpath conversationMessageId
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 deleteConversationMessage 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 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 a 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.

{$and:[{id:this.conversationMessageId},{isActive:true}]}

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, socketSettings, 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 deleteConversationMessage api has got 1 regular client parameter

Parameter Type Required Population
conversationMessageId ID true request.params?.[“conversationMessageId”]

REST Request

To access the api you can use the REST controller with the path DELETE /v1/conversationmessages/:conversationMessageId

  axios({
    method: 'DELETE',
    url: `/v1/conversationmessages/${conversationMessageId}`,
    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 conversationMessage 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": "conversationMessage",
	"method": "DELETE",
	"action": "delete",
	"appVersion": "Version",
	"rowCount": 1,
	"conversationMessage": {
		"id": "ID",
		"content": "Text",
		"conversationThreadId": "ID",
		"isRead": "Boolean",
		"readAt": "Date",
		"receiverId": "ID",
		"senderId": "ID",
		"sentAt": "Date",
		"isActive": false,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Business API Design Specification - Get Conversationmessage

Business API Design Specification - Get Conversationmessage

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 getConversationMessage 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 getConversationMessage Business API is designed to handle a get operation on the ConversationMessage 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 by ID. Only accessible to participants or moderators/admins.

API Frontend Description By The Backend Architect

Loads a message for display in UI. Fails if not participant or staff.

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 getConversationMessage Business API includes a REST controller that can be triggered via the following route:

/v1/conversationmessages/:conversationMessageId

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 getConversationMessage Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The getConversationMessage 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
conversationMessageId ID Yes - urlpath conversationMessageId
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 getConversationMessage 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 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 a fullWhereClause setting :

{ $or: [ { senderId: this.session.userId }, { receiverId: 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.

{$and:[{ $or: [ { senderId: this.session.userId }, { receiverId: this.session.userId } ] },{isActive:true}]}

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, socketSettings, 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 getConversationMessage api has got 1 regular client parameter

Parameter Type Required Population
conversationMessageId ID true request.params?.[“conversationMessageId”]

REST Request

To access the api you can use the REST controller with the path GET /v1/conversationmessages/:conversationMessageId

  axios({
    method: 'GET',
    url: `/v1/conversationmessages/${conversationMessageId}`,
    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 conversationMessage 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": "conversationMessage",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"conversationMessage": {
		"id": "ID",
		"content": "Text",
		"conversationThreadId": "ID",
		"isRead": "Boolean",
		"readAt": "Date",
		"receiverId": "ID",
		"senderId": "ID",
		"sentAt": "Date",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Business API Design Specification - Get Conversationthread

Business API Design Specification - Get Conversationthread

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 getConversationThread 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 getConversationThread Business API is designed to handle a get operation on the ConversationThread 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 conversation thread by ID. Only visible to participants or staff.

API Frontend Description By The Backend Architect

Shows full thread info for inbox/detail view. Fails if user does not participate or is not moderator/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 getConversationThread Business API includes a REST controller that can be triggered via the following route:

/v1/conversationthreads/:conversationThreadId

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 getConversationThread Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The getConversationThread 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
conversationThreadId ID Yes - urlpath conversationThreadId
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 getConversationThread 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,listingId,senderId,receiverId,lastMessageAt

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 a fullWhereClause setting :

{ $or: [ { senderId: this.session.userId }, { receiverId: 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.

{$and:[{ $or: [ { senderId: this.session.userId }, { receiverId: this.session.userId } ] },{isActive:true}]}

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, socketSettings, 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 getConversationThread api has got 1 regular client parameter

Parameter Type Required Population
conversationThreadId ID true request.params?.[“conversationThreadId”]

REST Request

To access the api you can use the REST controller with the path GET /v1/conversationthreads/:conversationThreadId

  axios({
    method: 'GET',
    url: `/v1/conversationthreads/${conversationThreadId}`,
    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 conversationThread 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": "conversationThread",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"conversationThread": {
		"listing": {
			"status": "Enum",
			"status_idx": "Integer",
			"title": "String",
			"userId": "ID"
		},
		"isActive": true
	}
}

Business API Design Specification - List Conversationmessages

Business API Design Specification - List Conversationmessages

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 listConversationMessages 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 listConversationMessages Business API is designed to handle a list operation on the ConversationMessage 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 messages in a thread, sorted oldest to newest. Only accessible to thread participants or staff.

API Frontend Description By The Backend Architect

Loads the chat history in UI for reading; includes isRead, sender info, etc. Used for conversation detail 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 listConversationMessages Business API includes a REST controller that can be triggered via the following route:

/v1/listconversationmessages/:conversationThreadId

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 listConversationMessages Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The listConversationMessages 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
conversationThreadId ID Yes `` query conversationThreadId
Description: Thread to load messages from.

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 listConversationMessages 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 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 a fullWhereClause setting :

{ $or: [ { senderId: this.session.userId }, { receiverId: 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.

{$and:[{ $or: [ { senderId: this.session.userId }, { receiverId: this.session.userId } ] },{isActive:true}]}

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, socketSettings, 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 listConversationMessages api has got 1 regular client parameter

Parameter Type Required Population
conversationThreadId ID true request.query?.[“conversationThreadId”]

REST Request

To access the api you can use the REST controller with the path GET /v1/listconversationmessages/:conversationThreadId

  axios({
    method: 'GET',
    url: `/v1/listconversationmessages/${conversationThreadId}`,
    data: {
    
    },
    params: {
             conversationThreadId:'"ID"',  
    
        }
  });

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 conversationMessages 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": "conversationMessages",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"conversationMessages": [
		{
			"id": "ID",
			"content": "Text",
			"conversationThreadId": "ID",
			"isRead": "Boolean",
			"readAt": "Date",
			"receiverId": "ID",
			"senderId": "ID",
			"sentAt": "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 - List Conversationthreads

Business API Design Specification - List Conversationthreads

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 listConversationThreads 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 listConversationThreads Business API is designed to handle a list operation on the ConversationThread 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 threads a user participates in, most recent first. Also used for moderator search/all-list.

API Frontend Description By The Backend Architect

Shows all user’s conversation threads in inbox. Moderators can search 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 listConversationThreads Business API includes a REST controller that can be triggered via the following route:

/v1/conversationthreads

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 listConversationThreads Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The listConversationThreads 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 listConversationThreads 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,listingId,senderId,receiverId,lastMessageAt

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 :

{ $or: [ { senderId: this.session.userId }, { receiverId: 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.

{$and:[{ $or: [ { senderId: this.session.userId }, { receiverId: this.session.userId } ] },{isActive:true}]}

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, socketSettings, 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 listConversationThreads api has got no visible parameters.

REST Request

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

  axios({
    method: 'GET',
    url: '/v1/conversationthreads',
    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 conversationThreads 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": "conversationThreads",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"conversationThreads": [
		{
			"listing": [
				{
					"status": "Enum",
					"status_idx": "Integer",
					"title": "String",
					"userId": "ID"
				},
				{},
				{}
			],
			"isActive": true
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Business API Design Specification - Mark Messageasread

Business API Design Specification - Mark Messageasread

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 markMessageAsRead 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 markMessageAsRead Business API is designed to handle a update operation on the ConversationMessage data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

Marks a message as read (isRead=true, readAt=now); only allowed for receiver.

API Frontend Description By The Backend Architect

When viewing messages, receiver marks message as read – triggers unread count decrement in UI, updates message 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 markMessageAsRead Business API includes a REST controller that can be triggered via the following route:

/v1/markmessageasread/:conversationMessageId

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 markMessageAsRead Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The markMessageAsRead 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
conversationMessageId ID Yes - urlpath conversationMessageId
Description: This id paremeter is used to select the required data object that will be updated
isRead Boolean No - body isRead
Description: True if the receiver has read this message.
readAt Date No - body readAt
Description: Timestamp when the receiver read the message (null if unread).

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 markMessageAsRead 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 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 a fullWhereClause setting :

{ receiverId: 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.

{$and:[{ receiverId: this.session.userId },{isActive:true}]}

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

{
    isRead: true,
    readAt: new Date(),
   
}

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.

{
  isRead: true,
  readAt: new Date(),
}

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, socketSettings, 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 markMessageAsRead api has got 3 regular client parameters

Parameter Type Required Population
conversationMessageId ID true request.params?.[“conversationMessageId”]
isRead Boolean false request.body?.[“isRead”]
readAt Date false request.body?.[“readAt”]

REST Request

To access the api you can use the REST controller with the path PATCH /v1/markmessageasread/:conversationMessageId

  axios({
    method: 'PATCH',
    url: `/v1/markmessageasread/${conversationMessageId}`,
    data: {
            isRead:"Boolean",  
            readAt:"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 conversationMessage 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": "conversationMessage",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"conversationMessage": {
		"id": "ID",
		"content": "Text",
		"conversationThreadId": "ID",
		"isRead": "Boolean",
		"readAt": "Date",
		"receiverId": "ID",
		"senderId": "ID",
		"sentAt": "Date",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Business API Design Specification - _fetch Listconversationmessage

Business API Design Specification - _fetch Listconversationmessage

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 _fetchListConversationMessage 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 _fetchListConversationMessage Business API is designed to handle a list operation on the ConversationMessage data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

System API to fetch list of conversationMessage records for frontend application. Auto-generated, not visible in design.

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 _fetchListConversationMessage Business API includes a REST controller that can be triggered via the following route:

/v1/_fetchlistconversationmessage

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 _fetchListConversationMessage Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The _fetchListConversationMessage 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 _fetchListConversationMessage 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.

{isActive:true}

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).

[ createdAt 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, socketSettings, 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 _fetchListConversationMessage api has got no visible parameters.

REST Request

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

  axios({
    method: 'GET',
    url: '/v1/_fetchlistconversationmessage',
    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 conversationMessages 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": "conversationMessages",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"conversationMessages": [
		{
			"id": "ID",
			"content": "Text",
			"conversationThreadId": "ID",
			"isRead": "Boolean",
			"readAt": "Date",
			"receiverId": "ID",
			"senderId": "ID",
			"sentAt": "Date",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID",
			"thread": [
				{
					"lastMessageAt": "Date",
					"listingId": "ID",
					"receiverId": "ID",
					"senderId": "ID"
				},
				{},
				{}
			],
			"receiverUser": [
				{
					"fullname": "String"
				},
				{},
				{}
			],
			"senderUser": [
				{
					"fullname": "String"
				},
				{},
				{}
			]
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Business API Design Specification - _fetch Listconversationthread

Business API Design Specification - _fetch Listconversationthread

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 _fetchListConversationThread 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 _fetchListConversationThread Business API is designed to handle a list operation on the ConversationThread data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

System API to fetch list of conversationThread records for frontend application. Auto-generated, not visible in design.

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 _fetchListConversationThread Business API includes a REST controller that can be triggered via the following route:

/v1/_fetchlistconversationthread

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 _fetchListConversationThread Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The _fetchListConversationThread 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 _fetchListConversationThread 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.

{isActive:true}

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).

[ createdAt 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, socketSettings, 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 _fetchListConversationThread api has got no visible parameters.

REST Request

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

  axios({
    method: 'GET',
    url: '/v1/_fetchlistconversationthread',
    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 conversationThreads 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": "conversationThreads",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"conversationThreads": [
		{
			"id": "ID",
			"lastMessageAt": "Date",
			"listingId": "ID",
			"receiverId": "ID",
			"senderId": "ID",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID",
			"listing": [
				{
					"attributes": "Object",
					"categoryId": "ID",
					"condition": "Enum",
					"condition_idx": "Integer",
					"contactEmail": "String",
					"contactPhone": "String",
					"currency": "String",
					"description": "Text",
					"expiresAt": "Date",
					"favoriteCount": "Integer",
					"isPremium": "Boolean",
					"listingType": "Enum",
					"listingType_idx": "Integer",
					"locationId": "ID",
					"_paymentConfirmation": "String",
					"premiumExpiry": "Date",
					"premiumType": "Enum",
					"premiumType_idx": "Integer",
					"price": "Double",
					"status": "Enum",
					"status_idx": "Integer",
					"subcategoryId": "ID",
					"title": "String",
					"userId": "ID",
					"viewsCount": "Integer"
				},
				{},
				{}
			],
			"receiverUser": [
				{
					"fullname": "String"
				},
				{},
				{}
			],
			"senderUser": [
				{
					"fullname": "String"
				},
				{},
				{}
			]
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Favorite Service

Service Design Specification

Service Design Specification

clonesahibinden-favorite-service documentation Version: 1.0.3

Scope

This document provides a structured architectural overview of the favorite 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.

Favorite Service Settings

Handles all user favorites for classified listings, including add/remove, listing user-specific collections, and providing favorited status for listings. Prevents duplicate favorites and maintains favorite counts on listings for optimal UX. Cascade-cleans favorites if user or listing is deleted.

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 clonesahibinden-favorite-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 clonesahibinden-favorite-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
favorite Stores which user favorited which listing, with timestamp. Enforces unique favorites per (user,listing) pair, and cascades on user/listing deletion. accessPrivate

favorite Data Object

Object Overview

Description: Stores which user favorited which listing, with timestamp. Enforces unique favorites per (user,listing) pair, and cascades on user/listing deletion.

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
favoritedAt Date Yes Date and time when the favorite was added.
listingId ID Yes Target listing being favorited.
userId ID Yes User who favorited the listing.

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

favoritedAt listingId 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.

Elastic Search Indexing

favoritedAt listingId 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

listingId 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.

Relation Properties

listingId 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.

Business Logic

favorite has got 5 Business APIs to manage its internal and crud logic. For the details of each business API refer to its chapter.

Edge Controllers

m2mCreateFavorite

Configuration:

REST Settings:


m2mBulkCreateFavorite

Configuration:

REST Settings:


m2mUpdateFavoriteById

Configuration:

REST Settings:


m2mDeleteFavoriteById

Configuration:

REST Settings:


m2mUpdateFavoriteByQuery

Configuration:

REST Settings:


m2mDeleteFavoriteByQuery

Configuration:

REST Settings:


m2mUpdateFavoriteByIdList

Configuration:

REST Settings:



Service Library

Functions

No general functions defined.

Hook Functions

No hook functions defined.

Edge Functions

m2mCreateFavorite.js

module.exports = async (request) => {
        const { createFavorite } = require("dbLayer");
        const context = { session: request.session, requestId: request.requestId };
        const data = request.body?.data || request.data || request;
        const result = await createFavorite(data, context);
        return { status: 200, content: result };
      }

m2mBulkCreateFavorite.js

module.exports = async (request) => {
        const { createBulkFavorite } = require("dbLayer");
        const context = { session: request.session, requestId: request.requestId };
        const dataList = request.body?.dataList || request.dataList || (Array.isArray(request.body) ? request.body : [request.body]);
        if (!Array.isArray(dataList) || dataList.length === 0) {
          return { status: 400, message: "dataList must be a non-empty array" };
        }
        const result = await createBulkFavorite(dataList, context);
        return { status: 200, content: result };
      }

m2mUpdateFavoriteById.js

module.exports = async (request) => {
        const { updateFavoriteById } = require("dbLayer");
        const context = { session: request.session, requestId: request.requestId };
        const id = request.body?.id || request.params?.id || request.id;
        const dataClause = request.body?.dataClause || request.dataClause || request.body;
        if (dataClause && dataClause.id) delete dataClause.id;
        if (!id) {
          return { status: 400, message: "ID is required" };
        }
        const result = await updateFavoriteById(id, dataClause, context);
        return { status: 200, content: result };
      }

m2mDeleteFavoriteById.js

module.exports = async (request) => {
        const { deleteFavoriteById } = require("dbLayer");
        const context = { session: request.session, requestId: request.requestId };
        const id = request.body?.id || request.params?.id || request.id;
        if (!id) {
          return { status: 400, message: "ID is required" };
        }
        const result = await deleteFavoriteById(id, context);
        return { status: 200, content: result };
      }

m2mUpdateFavoriteByQuery.js

module.exports = async (request) => {
        const { updateFavoriteByQuery } = require("dbLayer");
        const context = { session: request.session, requestId: request.requestId };
        const dataClause = request.body?.dataClause || request.dataClause || request.body;
        const query = request.body?.query || request.query || {};
        if (!query || typeof query !== "object" || Object.keys(query).length === 0) {
          return { status: 400, message: "Query is required and must be a non-empty object" };
        }
        const result = await updateFavoriteByQuery(dataClause, query, context);
        return { status: 200, content: result };
      }

m2mDeleteFavoriteByQuery.js

module.exports = async (request) => {
        const { deleteFavoriteByQuery } = require("dbLayer");
        const context = { session: request.session, requestId: request.requestId };
        const query = request.body?.query || request.query || {};
        if (!query || typeof query !== "object" || Object.keys(query).length === 0) {
          return { status: 400, message: "Query is required and must be a non-empty object" };
        }
        const result = await deleteFavoriteByQuery(query, context);
        return { status: 200, content: result };
      }

m2mUpdateFavoriteByIdList.js

module.exports = async (request) => {
        const { updateFavoriteByIdList } = require("dbLayer");
        const context = { session: request.session, requestId: request.requestId };
        const idList = request.body?.idList || request.idList || [];
        const dataClause = request.body?.dataClause || request.dataClause || request.body;
        if (dataClause && dataClause.idList) delete dataClause.idList;
        if (!Array.isArray(idList) || idList.length === 0) {
          return { status: 400, message: "idList must be a non-empty array" };
        }
        const result = await updateFavoriteByIdList(idList, dataClause, context);
        return { status: 200, content: result };
      }

Templates

No templates defined.

Assets

No assets defined.

Public Assets

No public assets defined.


Event Emission


Integration Patterns

Deployment Considerations

Environment Configuration

Implementation Guidelines

Development Workflow

  1. Data Model Implementation: Generate database schema from data object definitions
  2. CRUD Route Generation: Implement auto-generated routes with custom logic
  3. Custom Logic Integration: Implement hook functions and edge functions
  4. Authentication Integration: Configure with project-level authentication
  5. Testing: Unit and integration testing for all components

Code Generation Expectations

Custom Code Integration Points

Testing Strategy

Unit Testing

Integration Testing

Performance Testing


Appendices

Data Type Reference

Type Description Storage
ID Unique identifier UUID (SQL) / ObjectID (NoSQL)
String Short text (≤255 chars) VARCHAR
Text Long-form text TEXT
Integer 32-bit whole numbers INT
Boolean True/false values BOOLEAN
Double 64-bit floating point DOUBLE
Float 32-bit floating point FLOAT
Short 16-bit integers SMALLINT
Object JSON object JSONB (PostgreSQL) / Object (MongoDB)
Date ISO 8601 timestamp TIMESTAMP
Enum Fixed numeric values SMALLINT with lookup

Enum Value Mappings

Request Locations

HTTP Methods

Edge Function Signature

async function edgeFunction(request) {
  // Custom request processing
  // Return response object or throw error
  return {
    data: {},
    status: 200,
    message: "Success"
  };
}

This document was generated from the service architecture definition and should be kept in sync with implementation changes.


REST API GUIDE

REST API GUIDE

clonesahibinden-favorite-service

Version: 1.0.3

Handles all user favorites for classified listings, including add/remove, listing user-specific collections, and providing favorited status for listings. Prevents duplicate favorites and maintains favorite counts on listings for optimal UX. Cascade-cleans favorites if user or listing is deleted.

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 Favorite Service’s REST API. This document is designed to provide a comprehensive guide to interfacing with our Favorite Service exclusively through RESTful API endpoints.

Intended Audience

This documentation is intended for developers and integrators who are looking to interact with the Favorite Service via HTTP requests for purposes such as creating, updating, deleting and querying Favorite 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 Favorite 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 Favorite 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 clonesahibinden-access-token
Cookie clonesahibinden-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 Favorite 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 Favorite 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 Favorite 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 Favorite 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 Favorite 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 Favorite 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

Favorite 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.

Favorite resource

Resource Definition : Stores which user favorited which listing, with timestamp. Enforces unique favorites per (user,listing) pair, and cascades on user/listing deletion. Favorite Resource Properties

Name Type Required Default Definition
favoritedAt Date Date and time when the favorite was added.
listingId ID Target listing being favorited.
userId ID User who favorited the listing.

Business Api

Create Favorite API

Add a favorite for a listing for the current user. Prevents duplicate (user,listing) pairs, and can’t favorite own listing.

API Frontend Description By The Backend Architect

AI Dev: Call this API to favorite a listing; on success, update UI state and increment count. If already favorited, show appropriate feedback. Cannot favorite own listings. No double favoriting allowed.

Rest Route

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

/v1/favorites

Rest Request Parameters

The createFavorite api has got 1 regular request parameter

Parameter Type Required Population
listingId ID true request.body?.[“listingId”]
listingId : Target listing being favorited.

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

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

REST Response

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

Delete Favorite API

Unfavorite (remove favorite) the given listing for current user. Decrements favoriteCount on related listing when possible.

API Frontend Description By The Backend Architect

AI Dev: Use this API to unfavorite a listing. On success, update UI (remove highlight) and decrement displayed favorite count. If not found, treat as idempotent success for best UX.

Rest Route

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

/v1/favorites/:favoriteId

Rest Request Parameters

The deleteFavorite api has got 2 regular request parameters

Parameter Type Required Population
favoriteId ID true request.params?.[“favoriteId”]
listingId ID true request.query?.[“listingId”]
favoriteId : This id paremeter is used to select the required data object that will be deleted
listingId : Target listing being favorited… The parameter is used to query data.

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

  axios({
    method: 'DELETE',
    url: `/v1/favorites/${favoriteId}`,
    data: {
    
    },
    params: {
             listingId:'"ID"',  
    
        }
  });

REST Response

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

Get Favorite API

Get a specific favorite by id or by userId+listingId, mainly used to check if a listing is favorited by user (for heart/check display in feeds/details). Only accessible by owner or admin.

API Frontend Description By The Backend Architect

AI Dev: Use to check if a given listing is in the user’s favorites; supports single-record fetch via id or userId+listingId composite. If no record, treat as not favorited in UI.

Rest Route

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

/v1/favorites/:favoriteId

Rest Request Parameters

The getFavorite api has got 1 regular request parameter

Parameter Type Required Population
favoriteId ID true request.params?.[“favoriteId”]
favoriteId : 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/favorites/:favoriteId

  axios({
    method: 'GET',
    url: `/v1/favorites/${favoriteId}`,
    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": "favorite",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"favorite": {
		"listing": {
			"isPremium": "Boolean",
			"premiumType": "Enum",
			"premiumType_idx": "Integer",
			"price": "Double",
			"status": "Enum",
			"status_idx": "Integer",
			"title": "String"
		},
		"isActive": true
	}
}

List Favorites API

List all listings favorited by the current user, joined with listing summary and preview (title, price, cover image, etc). Private; only owner or admin can access.

API Frontend Description By The Backend Architect

AI Dev: Use this to render the user’s entire favorites collection for the profile page. Each item must provide at least listing id, title, price, and main image for visual feed. Paginate and sort newest first by favoritedAt.

Rest Route

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

/v1/favorites

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

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

  axios({
    method: 'GET',
    url: '/v1/favorites',
    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": "favorites",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"favorites": [
		{
			"listing": [
				{
					"currency": "String",
					"isPremium": "Boolean",
					"premiumType": "Enum",
					"premiumType_idx": "Integer",
					"price": "Double",
					"status": "Enum",
					"status_idx": "Integer",
					"title": "String"
				},
				{},
				{}
			],
			"mainImage": {
				"sortOrder": "Integer",
				"thumbnailUrl": "String",
				"url": "String"
			},
			"isActive": true
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

_fetch Listfavorite API

System API to fetch list of favorite records for frontend application. Auto-generated, not visible in design.

Rest Route

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

/v1/_fetchlistfavorite

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

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

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

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "favorites",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"favorites": [
		{
			"id": "ID",
			"favoritedAt": "Date",
			"listingId": "ID",
			"userId": "ID",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID",
			"listing": [
				{
					"attributes": "Object",
					"categoryId": "ID",
					"condition": "Enum",
					"condition_idx": "Integer",
					"contactEmail": "String",
					"contactPhone": "String",
					"currency": "String",
					"description": "Text",
					"expiresAt": "Date",
					"favoriteCount": "Integer",
					"isPremium": "Boolean",
					"listingType": "Enum",
					"listingType_idx": "Integer",
					"locationId": "ID",
					"_paymentConfirmation": "String",
					"premiumExpiry": "Date",
					"premiumType": "Enum",
					"premiumType_idx": "Integer",
					"price": "Double",
					"status": "Enum",
					"status_idx": "Integer",
					"subcategoryId": "ID",
					"title": "String",
					"userId": "ID",
					"viewsCount": "Integer"
				},
				{},
				{}
			],
			"user": [
				{
					"fullname": "String"
				},
				{},
				{}
			]
		},
		{},
		{}
	],
	"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

clonesahibinden-favorite-service

Handles all user favorites for classified listings, including add/remove, listing user-specific collections, and providing favorited status for listings. Prevents duplicate favorites and maintains favorite counts on listings for optimal UX. Cascade-cleans favorites if user or listing is deleted.

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 Favorite Service Event descriptions. This guide is dedicated to detailing how to subscribe to and listen for state changes within the Favorite Service, offering an exclusive focus on event subscription mechanisms.

Intended Audience

This documentation is aimed at developers and integrators looking to monitor Favorite Service state changes. It is especially relevant for those wishing to implement or enhance business logic based on interactions with Favorite 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 Favorite 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 favorite-created

Event topic: clonesahibinden-favorite-service-dbevent-favorite-created

This event is triggered upon the creation of a favorite data object in the database. The event payload encompasses the newly created data, encapsulated within the root of the paylod.

Event payload:

{"id":"ID","favoritedAt":"Date","listingId":"ID","userId":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

DbEvent favorite-updated

Event topic: clonesahibinden-favorite-service-dbevent-favorite-updated

Activation of this event follows the update of a favorite data object. The payload contains the updated information under the favorite attribute, along with the original data prior to update, labeled as old_favorite and also you can find the old and new versions of updated-only portion of the data…

Event payload:

{
old_favorite:{"id":"ID","favoritedAt":"Date","listingId":"ID","userId":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},
favorite:{"id":"ID","favoritedAt":"Date","listingId":"ID","userId":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},
oldDataValues,
newDataValues
}

DbEvent favorite-deleted

Event topic: clonesahibinden-favorite-service-dbevent-favorite-deleted

This event announces the deletion of a favorite 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","favoritedAt":"Date","listingId":"ID","userId":"ID","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

ElasticSearch Index Events

Within the Favorite 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 favorite-created

Event topic: elastic-index-clonesahibinden_favorite-created

Event payload:

{"id":"ID","favoritedAt":"Date","listingId":"ID","userId":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event favorite-updated

Event topic: elastic-index-clonesahibinden_favorite-created

Event payload:

{"id":"ID","favoritedAt":"Date","listingId":"ID","userId":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event favorite-deleted

Event topic: elastic-index-clonesahibinden_favorite-deleted

Event payload:

{"id":"ID","favoritedAt":"Date","listingId":"ID","userId":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event favorite-extended

Event topic: elastic-index-clonesahibinden_favorite-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 favorite-created

Event topic : clonesahibinden-favorite-service-favorite-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 favorite data object itself.

The following JSON included in the payload illustrates the fullest representation of the favorite 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":"favorite","method":"POST","action":"create","appVersion":"Version","rowCount":1,"favorite":{"id":"ID","favoritedAt":"Date","listingId":"ID","userId":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event favorite-deleted

Event topic : clonesahibinden-favorite-service-favorite-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 favorite data object itself.

The following JSON included in the payload illustrates the fullest representation of the favorite 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":"favorite","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"favorite":{"id":"ID","favoritedAt":"Date","listingId":"ID","userId":"ID","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 favorite

Service Design Specification - Object Design for favorite

clonesahibinden-favorite-service documentation

Document Overview

This document outlines the object design for the favorite model in our application. It includes details about the model’s attributes, relationships, and any specific validation or business logic that applies.

favorite Data Object

Object Overview

Description: Stores which user favorited which listing, with timestamp. Enforces unique favorites per (user,listing) pair, and cascades on user/listing deletion.

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
favoritedAt Date Yes Date and time when the favorite was added.
listingId ID Yes Target listing being favorited.
userId ID Yes User who favorited the listing.

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

favoritedAt listingId 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.

Elastic Search Indexing

favoritedAt listingId 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

listingId 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.

Relation Properties

listingId 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.


Business APIs

Business API Design Specification - Create Favorite

Business API Design Specification - Create Favorite

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 createFavorite 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 createFavorite Business API is designed to handle a create operation on the Favorite 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 favorite for a listing for the current user. Prevents duplicate (user,listing) pairs, and can’t favorite own listing.

API Frontend Description By The Backend Architect

AI Dev: Call this API to favorite a listing; on success, update UI state and increment count. If already favorited, show appropriate feedback. Cannot favorite own listings. No double favoriting 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 createFavorite Business API includes a REST controller that can be triggered via the following route:

/v1/favorites

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 createFavorite Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The createFavorite 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
favoriteId ID No - body favoriteId
Description: This id paremeter is used to create the data object with a given specific id. Leave null for automatic id.
listingId ID Yes - body listingId
Description: Target listing being favorited.
userId ID Yes - session userId
Description: User who favorited the listing.

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 createFavorite 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.favoriteId,
  listingId: this.listingId,
  userId: this.userId,
  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, socketSettings, 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 : fetchListing

Action Type: FetchObjectAction

Fetch the related listing to check user can’t favorite own listing, and for count update.

class Api {
  async fetchListing() {
    // Fetch Object on childObject listing

    const userQuery = {
      $and: [{ id: this.listingId }, { isActive: true }],
    };
    const { convertUserQueryToElasticQuery } = require("common");
    const scriptQuery = convertUserQueryToElasticQuery(userQuery);

    const elasticIndex = new ElasticIndexer("listing");
    const data = await elasticIndex.getOne(scriptQuery);

    if (!data) {
      throw new NotFoundError("errMsg_FethcedObjectNotFound:listing");
    }

    return data
      ? {
          id: data["id"],
          userId: data["userId"],
        }
      : null;
  }
}

[4] Action : checkDuplicate

Action Type: FunctionCallAction

Check if this favorite already exists.

class Api {
  async checkDuplicate() {
    try {
      return await getFavoriteByQuery({
        userId: this.session.userId,
        listingId: this.listingId,
      });
    } catch (err) {
      console.error("Error in FunctionCallAction checkDuplicate:", err);
      throw err;
    }
  }
}

[5] Step : transposeParameters

Manager transforms parameters, computes derived values, flattens or remaps arrays/objects, and adjusts formats for downstream processing.


[6] Action : checkDuplicateValidation

Action Type: ValidationAction

Block duplicate favoriting.

class Api {
  async checkDuplicateValidation() {
    const isError = !!this.duplicateFavorite;

    if (isError) {
      throw new BadRequestError("You have already favorited this listing!");
    }
    return isError;
  }
}

[7] Action : selfFavoriteValidation

Action Type: ValidationAction

User cannot favorite own listing.

class Api {
  async selfFavoriteValidation() {
    const isError = this.session.userId == this.targetListing.userId;

    if (isError) {
      throw new BadRequestError("You cannot favorite your own listing!");
    }
    return isError;
  }
}

[8] Step : checkParameters

Manager executes built-in validations: required field checks, type enforcement, and basic business rules. Prevents operation if validation fails.


[9] 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

[10] 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

[11] Action : setFavoritedAt

Action Type: AddToContextAction

Ensure favoritedAt is set now.

class Api {
  async setFavoritedAt() {
    try {
      this["favoritedAt"] = new Date().toISOString();

      return true;
    } catch (error) {
      console.error("AddToContextAction error:", error);
      throw error;
    }
  }
}

[12] Step : mainCreateOperation

Manager executes the database insert operation, updates indexes/caches, and triggers internal post-processing like linked default records.


[13] Action : incFavoriteCount

Action Type: UpdateCrudAction

Increment favoriteCount on listing after favorite created.

class Api {
  async incFavoriteCount() {
    // Aggregated Update Operation on childObject listing

    const params = {
      favoriteCount: (this.targetListing.favoriteCount ?? 0) + 1,
    };
    const userQuery = { id: this.listingId };

    const { convertUserQueryToSequelizeQuery } = require("common");
    const query = convertUserQueryToSequelizeQuery(userQuery);

    // Remote object - call inter-service M2M edge function
    const { InterService } = require("common-service");
    const options = {};

    const result = await InterService.callListingm2mUpdateListingByQuery(
      {
        body: { dataClause: params, query: query },
      },
      options,
    );

    if (!result || result.status !== 200) {
      throw new HttpServerError(
        `Inter-service call failed: ${result?.message || "Unknown error"}`,
      );
    }

    const updatedResult = result.content;
    if (!updatedResult) return null;

    // if updated record is in main data update main data
    if (this.dbResult) {
      for (const item of updatedResult) {
        if (item.id == this.dbResult.id) {
          Object.assign(this.dbResult, item);
          this.favorite = this.dbResult;
        }
      }
    }
    if (updatedResult.length == 0) return null;
    if (updatedResult.length == 1) return updatedResult[0];
    return updatedResult;
  }
}

[14] Step : buildOutput

Manager shapes the response: masks sensitive fields, resolves linked references, and formats output according to API contract.


[15] Step : sendResponse

Manager sends the response to the client and finalizes internal tasks like flushing logs or updating session state.


[16] 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 createFavorite api has got 1 regular client parameter

Parameter Type Required Population
listingId ID true request.body?.[“listingId”]

REST Request

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

  axios({
    method: 'POST',
    url: '/v1/favorites',
    data: {
            listingId:"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 favorite 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": "favorite",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"favorite": {
		"id": "ID",
		"favoritedAt": "Date",
		"listingId": "ID",
		"userId": "ID",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Business API Design Specification - Delete Favorite

Business API Design Specification - Delete Favorite

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 deleteFavorite 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 deleteFavorite Business API is designed to handle a delete operation on the Favorite data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

Unfavorite (remove favorite) the given listing for current user. Decrements favoriteCount on related listing when possible.

API Frontend Description By The Backend Architect

AI Dev: Use this API to unfavorite a listing. On success, update UI (remove highlight) and decrement displayed favorite count. If not found, treat as idempotent success for best UX.

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 deleteFavorite Business API includes a REST controller that can be triggered via the following route:

/v1/favorites/:favoriteId

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 deleteFavorite Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The deleteFavorite 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
favoriteId ID Yes - urlpath favoriteId
Description: This id paremeter is used to select the required data object that will be deleted
listingId ID Yes - query listingId
Description: Target listing being favorited… The parameter is used to query data.
userId ID Yes - session userId
Description: User who favorited the listing… The parameter is used to query data.

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 deleteFavorite 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 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.

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.

{$and:[{id:this.favoriteId},{isActive:true}]}

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, socketSettings, 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] Action : fetchTargetListingOnDelete

Action Type: FetchObjectAction

Fetch the related listing for count decrement.

class Api {
  async fetchTargetListingOnDelete() {
    // Fetch Object on childObject listing

    const userQuery = {
      $and: [{ id: this.listingId }, { isActive: true }],
    };
    const { convertUserQueryToElasticQuery } = require("common");
    const scriptQuery = convertUserQueryToElasticQuery(userQuery);

    const elasticIndex = new ElasticIndexer("listing");
    const data = await elasticIndex.getOne(scriptQuery);

    return data
      ? {
          id: data["id"],
          favoriteCount: data["favoriteCount"],
        }
      : null;
  }
}

[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 : decFavoriteCount

Action Type: UpdateCrudAction

Decrement favoriteCount on related listing if found.

class Api {
  async decFavoriteCount() {
    // Aggregated Update Operation on childObject listing

    const params = {
      favoriteCount: Math.max(0, (this.targetListing.favoriteCount ?? 1) - 1),
    };
    const userQuery = { id: this.listingId };

    const { convertUserQueryToSequelizeQuery } = require("common");
    const query = convertUserQueryToSequelizeQuery(userQuery);

    // Remote object - call inter-service M2M edge function
    const { InterService } = require("common-service");
    const options = {};

    const result = await InterService.callListingm2mUpdateListingByQuery(
      {
        body: { dataClause: params, query: query },
      },
      options,
    );

    if (!result || result.status !== 200) {
      throw new HttpServerError(
        `Inter-service call failed: ${result?.message || "Unknown error"}`,
      );
    }

    const updatedResult = result.content;
    if (!updatedResult) return null;

    // if updated record is in main data update main data
    if (this.dbResult) {
      for (const item of updatedResult) {
        if (item.id == this.dbResult.id) {
          Object.assign(this.dbResult, item);
          this.favorite = this.dbResult;
        }
      }
    }
    if (updatedResult.length == 0) return null;
    if (updatedResult.length == 1) return updatedResult[0];
    return updatedResult;
  }
}

[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 deleteFavorite api has got 2 regular client parameters

Parameter Type Required Population
favoriteId ID true request.params?.[“favoriteId”]
listingId ID true request.query?.[“listingId”]

REST Request

To access the api you can use the REST controller with the path DELETE /v1/favorites/:favoriteId

  axios({
    method: 'DELETE',
    url: `/v1/favorites/${favoriteId}`,
    data: {
    
    },
    params: {
             listingId:'"ID"',  
    
        }
  });

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 favorite 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": "favorite",
	"method": "DELETE",
	"action": "delete",
	"appVersion": "Version",
	"rowCount": 1,
	"favorite": {
		"id": "ID",
		"favoritedAt": "Date",
		"listingId": "ID",
		"userId": "ID",
		"isActive": false,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Business API Design Specification - Get Favorite

Business API Design Specification - Get Favorite

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 getFavorite 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 getFavorite Business API is designed to handle a get operation on the Favorite 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 specific favorite by id or by userId+listingId, mainly used to check if a listing is favorited by user (for heart/check display in feeds/details). Only accessible by owner or admin.

API Frontend Description By The Backend Architect

AI Dev: Use to check if a given listing is in the user’s favorites; supports single-record fetch via id or userId+listingId composite. If no record, treat as not favorited in UI.

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 getFavorite Business API includes a REST controller that can be triggered via the following route:

/v1/favorites/:favoriteId

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 getFavorite Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The getFavorite 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
favoriteId ID Yes - urlpath favoriteId
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 getFavorite 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.",

id,userId,listingId,favoritedAt

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.

{$and:[{id:this.favoriteId},{isActive:true}]}

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, socketSettings, 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 getFavorite api has got 1 regular client parameter

Parameter Type Required Population
favoriteId ID true request.params?.[“favoriteId”]

REST Request

To access the api you can use the REST controller with the path GET /v1/favorites/:favoriteId

  axios({
    method: 'GET',
    url: `/v1/favorites/${favoriteId}`,
    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 favorite 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": "favorite",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"favorite": {
		"listing": {
			"isPremium": "Boolean",
			"premiumType": "Enum",
			"premiumType_idx": "Integer",
			"price": "Double",
			"status": "Enum",
			"status_idx": "Integer",
			"title": "String"
		},
		"isActive": true
	}
}

Business API Design Specification - List Favorites

Business API Design Specification - List Favorites

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 listFavorites 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 listFavorites Business API is designed to handle a list operation on the Favorite 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 listings favorited by the current user, joined with listing summary and preview (title, price, cover image, etc). Private; only owner or admin can access.

API Frontend Description By The Backend Architect

AI Dev: Use this to render the user’s entire favorites collection for the profile page. Each item must provide at least listing id, title, price, and main image for visual feed. Paginate and sort newest first by favoritedAt.

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 listFavorites Business API includes a REST controller that can be triggered via the following route:

/v1/favorites

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 listFavorites Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The listFavorites 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 listFavorites 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,listingId,favoritedAt

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.

{isActive:true,userId:this.session?.userId}

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).

[ favoritedAt 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, socketSettings, 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 listFavorites api has got no visible parameters.

REST Request

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

  axios({
    method: 'GET',
    url: '/v1/favorites',
    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 favorites 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": "favorites",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"favorites": [
		{
			"listing": [
				{
					"currency": "String",
					"isPremium": "Boolean",
					"premiumType": "Enum",
					"premiumType_idx": "Integer",
					"price": "Double",
					"status": "Enum",
					"status_idx": "Integer",
					"title": "String"
				},
				{},
				{}
			],
			"mainImage": {
				"sortOrder": "Integer",
				"thumbnailUrl": "String",
				"url": "String"
			},
			"isActive": true
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Business API Design Specification - _fetch Listfavorite

Business API Design Specification - _fetch Listfavorite

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 _fetchListFavorite 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 _fetchListFavorite Business API is designed to handle a list operation on the Favorite data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

System API to fetch list of favorite records for frontend application. Auto-generated, not visible in design.

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 _fetchListFavorite Business API includes a REST controller that can be triggered via the following route:

/v1/_fetchlistfavorite

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 _fetchListFavorite Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The _fetchListFavorite 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 _fetchListFavorite 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.

{isActive:true}

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).

[ createdAt 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, socketSettings, 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 _fetchListFavorite api has got no visible parameters.

REST Request

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

  axios({
    method: 'GET',
    url: '/v1/_fetchlistfavorite',
    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 favorites 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": "favorites",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"favorites": [
		{
			"id": "ID",
			"favoritedAt": "Date",
			"listingId": "ID",
			"userId": "ID",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID",
			"listing": [
				{
					"attributes": "Object",
					"categoryId": "ID",
					"condition": "Enum",
					"condition_idx": "Integer",
					"contactEmail": "String",
					"contactPhone": "String",
					"currency": "String",
					"description": "Text",
					"expiresAt": "Date",
					"favoriteCount": "Integer",
					"isPremium": "Boolean",
					"listingType": "Enum",
					"listingType_idx": "Integer",
					"locationId": "ID",
					"_paymentConfirmation": "String",
					"premiumExpiry": "Date",
					"premiumType": "Enum",
					"premiumType_idx": "Integer",
					"price": "Double",
					"status": "Enum",
					"status_idx": "Integer",
					"subcategoryId": "ID",
					"title": "String",
					"userId": "ID",
					"viewsCount": "Integer"
				},
				{},
				{}
			],
			"user": [
				{
					"fullname": "String"
				},
				{},
				{}
			]
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Listing Service

Service Design Specification

Service Design Specification

clonesahibinden-listing-service documentation Version: 1.0.3

Scope

This document provides a structured architectural overview of the listing 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.

Listing Service Settings

Manages classified listings, their lifecycle, premium features, status transitions, and provides filtering/search for marketplace ads. Integrates with users, categories, locations, and Stripe for premium ad upgrades. Enforces ad and user type business logic.

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 clonesahibinden-listing-service.

This service is accessible via the following environment-specific URLs:

Authentication & Security

This service does not require user authentication for access. It is designed to be publicly accessible, allowing anonymous users to interact with its endpoints. However, certain CRUD routes may still require login based on their specific configurations.

Service Data Objects

The service uses a PostgreSQL database for data storage, with the database name set to clonesahibinden-listing-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
listing Core object for classified ads. Contains main listing information, relations, status, premium logic, price, attributes, contact info, and custom attributes. Supports premium upgrades via Stripe and lifecycle management. accessProtected
sys_listingPayment A payment storage object to store the payment life cyle of orders based on listing object. It is autocreated based on the source object's checkout config accessPrivate
sys_paymentCustomer A payment storage object to store the customer values of the payment platform accessPrivate
sys_paymentMethod A payment storage object to store the payment methods of the platform customers accessPrivate

listing Data Object

Object Overview

Description: Core object for classified ads. Contains main listing information, relations, status, premium logic, price, attributes, contact info, and custom attributes. Supports premium upgrades via Stripe and lifecycle management.

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.

Stripe Integration

This data object is configured to integrate with Stripe for order management of listing. It is designed to handle payment processing and order tracking. To manage payments, Mindbricks will design additional Business API routes arround this data object, which will be used checkout orders and charge customers.

if an error occurs during the checkout process, the API will continue to execute, allowing for custom error handling. In this case, the payment error will ve recorded as a status update. To make a retry a new checkout, a new order will be created with the same data as the original order.

Properties Schema

Property Type Required Description
attributes Object No JSON object for custom per-category attributes (structured as required by category schema).
categoryId ID Yes Main category for the listing (categoryLocation:category).
condition Enum Yes Item condition: new, used, other.
contactEmail String No Contact email (recommended to send via platform only).
contactPhone String No Display phone/contact for listing; may be masked by front end.
currency String Yes Currency (ISO-4217 code, e.g. 'TRY', 'USD').
description Text Yes Full description/body of listing.
expiresAt Date No UTC expiry for listing; after this, listing is automatically expired.
favoriteCount Integer Yes Favorite count (updated asynchronously by favorite service, not directly settable by user).
isPremium Boolean Yes If true, the listing is premium (highlighted/pinned, eligible for special placement).
listingType Enum Yes Type of listing (sale, rent, service, etc.).
locationId ID Yes Location (categoryLocation:location).
_paymentConfirmation String No Stripe payment result details (Stripe webhook metadata, internal use only).
premiumExpiry Date No UTC date when premium status expires. Null if not premium or not applicable.
premiumType Enum No Which premium package (gold, silver, none, etc.).
price Double Yes Listing price.
status Enum Yes Lifecycle status: pending_review, active, denied, sold, expired, deleted.
subcategoryId ID No Subcategory for the listing, can be null for top-level (categoryLocation:category).
title String Yes Listing title, short and clear.
userId ID Yes Owner (poster) of the listing (auth:user).
viewsCount Integer Yes View count (updated asynchronously; not directly settable by user).
paymentConfirmation Enum Yes An automatic property that is used to check the confirmed status of the payment set by webhooks.

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

favoriteCount _paymentConfirmation userId viewsCount

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

attributes categoryId condition contactEmail contactPhone currency description expiresAt isPremium listingType locationId premiumExpiry premiumType price status subcategoryId title

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

attributes categoryId condition currency description expiresAt favoriteCount isPremium listingType locationId premiumExpiry premiumType price status subcategoryId title userId viewsCount paymentConfirmation

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

categoryId condition currency isPremium listingType locationId premiumExpiry premiumType price status subcategoryId userId paymentConfirmation

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

paymentConfirmation

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

categoryId locationId subcategoryId 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

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

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.

Formula Properties

isPremium

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

categoryId condition expiresAt isPremium listingType locationId premiumExpiry premiumType price status subcategoryId title userId paymentConfirmation

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_listingPayment Data Object

Object Overview

Description: A payment storage object to store the payment life cyle of orders based on listing object. It is autocreated based on the source object's checkout config

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
ownerId ID No An ID value to represent owner user who created the order
orderId ID Yes an ID value to represent the orderId which is the ID parameter of the source listing object
paymentId String Yes A String value to represent the paymentId which is generated on the Stripe gateway. This id may represent different objects due to the payment gateway and the chosen flow type
paymentStatus String Yes A string value to represent the payment status which belongs to the lifecyle of a Stripe payment.
statusLiteral String Yes A string value to represent the logical payment status which belongs to the application lifecycle itself.
redirectUrl String No A string value to represent return page of the frontend to show the result of the payment, this is used when the callback is made to server not the client.

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

orderId

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

ownerId orderId paymentId paymentStatus statusLiteral redirectUrl

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

ownerId orderId paymentId paymentStatus statusLiteral redirectUrl

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

ownerId orderId paymentId paymentStatus statusLiteral redirectUrl

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

orderId

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.

Secondary Key Properties

orderId

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.

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

ownerId orderId paymentId paymentStatus statusLiteral redirectUrl

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_paymentCustomer Data Object

Object Overview

Description: A payment storage object to store the customer values of the payment platform

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 No An ID value to represent the user who is created as a stripe customer
customerId String Yes A string value to represent the customer id which is generated on the Stripe gateway. This id is used to represent the customer in the Stripe gateway
platform String Yes A String value to represent payment platform which is used to make the payment. It is stripe as default. It will be used to distinguesh the payment gateways in the future.

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

customerId platform

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 customerId platform

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

userId customerId platform

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 customerId platform

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

userId customerId

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.

Secondary Key Properties

userId customerId

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.

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.

Filter Properties

userId customerId platform

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_paymentMethod Data Object

Object Overview

Description: A payment storage object to store the payment methods of the platform customers

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
paymentMethodId String Yes A string value to represent the id of the payment method on the payment platform.
userId ID Yes An ID value to represent the user who owns the payment method
customerId String Yes A string value to represent the customer id which is generated on the payment gateway.
cardHolderName String No A string value to represent the name of the card holder. It can be different than the registered customer.
cardHolderZip String No A string value to represent the zip code of the card holder. It is used for address verification in specific countries.
platform String Yes A String value to represent payment platform which teh paymentMethod belongs. It is stripe as default. It will be used to distinguesh the payment gateways in the future.
cardInfo Object Yes A Json value to store the card details of the payment method.

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

paymentMethodId userId customerId cardHolderName cardHolderZip platform

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

paymentMethodId userId customerId cardHolderName cardHolderZip platform cardInfo

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

paymentMethodId userId customerId cardHolderName cardHolderZip platform cardInfo

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

paymentMethodId userId customerId platform cardInfo

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

paymentMethodId

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.

Secondary Key Properties

paymentMethodId userId customerId

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.

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.

Filter Properties

paymentMethodId userId customerId cardHolderName cardHolderZip platform cardInfo

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

listing has got 24 Business APIs to manage its internal and crud logic. For the details of each business API refer to its chapter.

Edge Controllers

m2mCreateListing

Configuration:

REST Settings:


m2mBulkCreateListing

Configuration:

REST Settings:


m2mUpdateListingById

Configuration:

REST Settings:


m2mDeleteListingById

Configuration:

REST Settings:


m2mUpdateListingByQuery

Configuration:

REST Settings:


m2mDeleteListingByQuery

Configuration:

REST Settings:


m2mUpdateListingByIdList

Configuration:

REST Settings:


m2mCreateSys_listingPayment

Configuration:

REST Settings:


m2mBulkCreateSys_listingPayment

Configuration:

REST Settings:


m2mUpdateSys_listingPaymentById

Configuration:

REST Settings:


m2mDeleteSys_listingPaymentById

Configuration:

REST Settings:


m2mUpdateSys_listingPaymentByQuery

Configuration:

REST Settings:


m2mDeleteSys_listingPaymentByQuery

Configuration:

REST Settings:


m2mUpdateSys_listingPaymentByIdList

Configuration:

REST Settings:


m2mCreateSys_paymentCustomer

Configuration:

REST Settings:


m2mBulkCreateSys_paymentCustomer

Configuration:

REST Settings:


m2mUpdateSys_paymentCustomerById

Configuration:

REST Settings:


m2mDeleteSys_paymentCustomerById

Configuration:

REST Settings:


m2mUpdateSys_paymentCustomerByQuery

Configuration:

REST Settings:


m2mDeleteSys_paymentCustomerByQuery

Configuration:

REST Settings:


m2mUpdateSys_paymentCustomerByIdList

Configuration:

REST Settings:


m2mCreateSys_paymentMethod

Configuration:

REST Settings:


m2mBulkCreateSys_paymentMethod

Configuration:

REST Settings:


m2mUpdateSys_paymentMethodById

Configuration:

REST Settings:


m2mDeleteSys_paymentMethodById

Configuration:

REST Settings:


m2mUpdateSys_paymentMethodByQuery

Configuration:

REST Settings:


m2mDeleteSys_paymentMethodByQuery

Configuration:

REST Settings:


m2mUpdateSys_paymentMethodByIdList

Configuration:

REST Settings:



Service Library

Functions

No general functions defined.

Hook Functions

No hook functions defined.

Edge Functions

m2mCreateListing.js

module.exports = async (request) => {
        const { createListing } = require("dbLayer");
        const context = { session: request.session, requestId: request.requestId };
        const data = request.body?.data || request.data || request;
        const result = await createListing(data, context);
        return { status: 200, content: result };
      }

m2mBulkCreateListing.js

module.exports = async (request) => {
        const { createBulkListing } = require("dbLayer");
        const context = { session: request.session, requestId: request.requestId };
        const dataList = request.body?.dataList || request.dataList || (Array.isArray(request.body) ? request.body : [request.body]);
        if (!Array.isArray(dataList) || dataList.length === 0) {
          return { status: 400, message: "dataList must be a non-empty array" };
        }
        const result = await createBulkListing(dataList, context);
        return { status: 200, content: result };
      }

m2mUpdateListingById.js

module.exports = async (request) => {
        const { updateListingById } = require("dbLayer");
        const context = { session: request.session, requestId: request.requestId };
        const id = request.body?.id || request.params?.id || request.id;
        const dataClause = request.body?.dataClause || request.dataClause || request.body;
        if (dataClause && dataClause.id) delete dataClause.id;
        if (!id) {
          return { status: 400, message: "ID is required" };
        }
        const result = await updateListingById(id, dataClause, context);
        return { status: 200, content: result };
      }

m2mDeleteListingById.js

module.exports = async (request) => {
        const { deleteListingById } = require("dbLayer");
        const context = { session: request.session, requestId: request.requestId };
        const id = request.body?.id || request.params?.id || request.id;
        if (!id) {
          return { status: 400, message: "ID is required" };
        }
        const result = await deleteListingById(id, context);
        return { status: 200, content: result };
      }

m2mUpdateListingByQuery.js

module.exports = async (request) => {
        const { updateListingByQuery } = require("dbLayer");
        const context = { session: request.session, requestId: request.requestId };
        const dataClause = request.body?.dataClause || request.dataClause || request.body;
        const query = request.body?.query || request.query || {};
        if (!query || typeof query !== "object" || Object.keys(query).length === 0) {
          return { status: 400, message: "Query is required and must be a non-empty object" };
        }
        const result = await updateListingByQuery(dataClause, query, context);
        return { status: 200, content: result };
      }

m2mDeleteListingByQuery.js

module.exports = async (request) => {
        const { deleteListingByQuery } = require("dbLayer");
        const context = { session: request.session, requestId: request.requestId };
        const query = request.body?.query || request.query || {};
        if (!query || typeof query !== "object" || Object.keys(query).length === 0) {
          return { status: 400, message: "Query is required and must be a non-empty object" };
        }
        const result = await deleteListingByQuery(query, context);
        return { status: 200, content: result };
      }

m2mUpdateListingByIdList.js

module.exports = async (request) => {
        const { updateListingByIdList } = require("dbLayer");
        const context = { session: request.session, requestId: request.requestId };
        const idList = request.body?.idList || request.idList || [];
        const dataClause = request.body?.dataClause || request.dataClause || request.body;
        if (dataClause && dataClause.idList) delete dataClause.idList;
        if (!Array.isArray(idList) || idList.length === 0) {
          return { status: 400, message: "idList must be a non-empty array" };
        }
        const result = await updateListingByIdList(idList, dataClause, context);
        return { status: 200, content: result };
      }

m2mCreateSys_listingPayment.js

module.exports = async (request) => {
        const { createSys_listingPayment } = require("dbLayer");
        const context = { session: request.session, requestId: request.requestId };
        const data = request.body?.data || request.data || request;
        const result = await createSys_listingPayment(data, context);
        return { status: 200, content: result };
      }

m2mBulkCreateSys_listingPayment.js

module.exports = async (request) => {
        const { createBulkSys_listingPayment } = require("dbLayer");
        const context = { session: request.session, requestId: request.requestId };
        const dataList = request.body?.dataList || request.dataList || (Array.isArray(request.body) ? request.body : [request.body]);
        if (!Array.isArray(dataList) || dataList.length === 0) {
          return { status: 400, message: "dataList must be a non-empty array" };
        }
        const result = await createBulkSys_listingPayment(dataList, context);
        return { status: 200, content: result };
      }

m2mUpdateSys_listingPaymentById.js

module.exports = async (request) => {
        const { updateSys_listingPaymentById } = require("dbLayer");
        const context = { session: request.session, requestId: request.requestId };
        const id = request.body?.id || request.params?.id || request.id;
        const dataClause = request.body?.dataClause || request.dataClause || request.body;
        if (dataClause && dataClause.id) delete dataClause.id;
        if (!id) {
          return { status: 400, message: "ID is required" };
        }
        const result = await updateSys_listingPaymentById(id, dataClause, context);
        return { status: 200, content: result };
      }

m2mDeleteSys_listingPaymentById.js

module.exports = async (request) => {
        const { deleteSys_listingPaymentById } = require("dbLayer");
        const context = { session: request.session, requestId: request.requestId };
        const id = request.body?.id || request.params?.id || request.id;
        if (!id) {
          return { status: 400, message: "ID is required" };
        }
        const result = await deleteSys_listingPaymentById(id, context);
        return { status: 200, content: result };
      }

m2mUpdateSys_listingPaymentByQuery.js

module.exports = async (request) => {
        const { updateSys_listingPaymentByQuery } = require("dbLayer");
        const context = { session: request.session, requestId: request.requestId };
        const dataClause = request.body?.dataClause || request.dataClause || request.body;
        const query = request.body?.query || request.query || {};
        if (!query || typeof query !== "object" || Object.keys(query).length === 0) {
          return { status: 400, message: "Query is required and must be a non-empty object" };
        }
        const result = await updateSys_listingPaymentByQuery(dataClause, query, context);
        return { status: 200, content: result };
      }

m2mDeleteSys_listingPaymentByQuery.js

module.exports = async (request) => {
        const { deleteSys_listingPaymentByQuery } = require("dbLayer");
        const context = { session: request.session, requestId: request.requestId };
        const query = request.body?.query || request.query || {};
        if (!query || typeof query !== "object" || Object.keys(query).length === 0) {
          return { status: 400, message: "Query is required and must be a non-empty object" };
        }
        const result = await deleteSys_listingPaymentByQuery(query, context);
        return { status: 200, content: result };
      }

m2mUpdateSys_listingPaymentByIdList.js

module.exports = async (request) => {
        const { updateSys_listingPaymentByIdList } = require("dbLayer");
        const context = { session: request.session, requestId: request.requestId };
        const idList = request.body?.idList || request.idList || [];
        const dataClause = request.body?.dataClause || request.dataClause || request.body;
        if (dataClause && dataClause.idList) delete dataClause.idList;
        if (!Array.isArray(idList) || idList.length === 0) {
          return { status: 400, message: "idList must be a non-empty array" };
        }
        const result = await updateSys_listingPaymentByIdList(idList, dataClause, context);
        return { status: 200, content: result };
      }

m2mCreateSys_paymentCustomer.js

module.exports = async (request) => {
        const { createSys_paymentCustomer } = require("dbLayer");
        const context = { session: request.session, requestId: request.requestId };
        const data = request.body?.data || request.data || request;
        const result = await createSys_paymentCustomer(data, context);
        return { status: 200, content: result };
      }

m2mBulkCreateSys_paymentCustomer.js

module.exports = async (request) => {
        const { createBulkSys_paymentCustomer } = require("dbLayer");
        const context = { session: request.session, requestId: request.requestId };
        const dataList = request.body?.dataList || request.dataList || (Array.isArray(request.body) ? request.body : [request.body]);
        if (!Array.isArray(dataList) || dataList.length === 0) {
          return { status: 400, message: "dataList must be a non-empty array" };
        }
        const result = await createBulkSys_paymentCustomer(dataList, context);
        return { status: 200, content: result };
      }

m2mUpdateSys_paymentCustomerById.js

module.exports = async (request) => {
        const { updateSys_paymentCustomerById } = require("dbLayer");
        const context = { session: request.session, requestId: request.requestId };
        const id = request.body?.id || request.params?.id || request.id;
        const dataClause = request.body?.dataClause || request.dataClause || request.body;
        if (dataClause && dataClause.id) delete dataClause.id;
        if (!id) {
          return { status: 400, message: "ID is required" };
        }
        const result = await updateSys_paymentCustomerById(id, dataClause, context);
        return { status: 200, content: result };
      }

m2mDeleteSys_paymentCustomerById.js

module.exports = async (request) => {
        const { deleteSys_paymentCustomerById } = require("dbLayer");
        const context = { session: request.session, requestId: request.requestId };
        const id = request.body?.id || request.params?.id || request.id;
        if (!id) {
          return { status: 400, message: "ID is required" };
        }
        const result = await deleteSys_paymentCustomerById(id, context);
        return { status: 200, content: result };
      }

m2mUpdateSys_paymentCustomerByQuery.js

module.exports = async (request) => {
        const { updateSys_paymentCustomerByQuery } = require("dbLayer");
        const context = { session: request.session, requestId: request.requestId };
        const dataClause = request.body?.dataClause || request.dataClause || request.body;
        const query = request.body?.query || request.query || {};
        if (!query || typeof query !== "object" || Object.keys(query).length === 0) {
          return { status: 400, message: "Query is required and must be a non-empty object" };
        }
        const result = await updateSys_paymentCustomerByQuery(dataClause, query, context);
        return { status: 200, content: result };
      }

m2mDeleteSys_paymentCustomerByQuery.js

module.exports = async (request) => {
        const { deleteSys_paymentCustomerByQuery } = require("dbLayer");
        const context = { session: request.session, requestId: request.requestId };
        const query = request.body?.query || request.query || {};
        if (!query || typeof query !== "object" || Object.keys(query).length === 0) {
          return { status: 400, message: "Query is required and must be a non-empty object" };
        }
        const result = await deleteSys_paymentCustomerByQuery(query, context);
        return { status: 200, content: result };
      }

m2mUpdateSys_paymentCustomerByIdList.js

module.exports = async (request) => {
        const { updateSys_paymentCustomerByIdList } = require("dbLayer");
        const context = { session: request.session, requestId: request.requestId };
        const idList = request.body?.idList || request.idList || [];
        const dataClause = request.body?.dataClause || request.dataClause || request.body;
        if (dataClause && dataClause.idList) delete dataClause.idList;
        if (!Array.isArray(idList) || idList.length === 0) {
          return { status: 400, message: "idList must be a non-empty array" };
        }
        const result = await updateSys_paymentCustomerByIdList(idList, dataClause, context);
        return { status: 200, content: result };
      }

m2mCreateSys_paymentMethod.js

module.exports = async (request) => {
        const { createSys_paymentMethod } = require("dbLayer");
        const context = { session: request.session, requestId: request.requestId };
        const data = request.body?.data || request.data || request;
        const result = await createSys_paymentMethod(data, context);
        return { status: 200, content: result };
      }

m2mBulkCreateSys_paymentMethod.js

module.exports = async (request) => {
        const { createBulkSys_paymentMethod } = require("dbLayer");
        const context = { session: request.session, requestId: request.requestId };
        const dataList = request.body?.dataList || request.dataList || (Array.isArray(request.body) ? request.body : [request.body]);
        if (!Array.isArray(dataList) || dataList.length === 0) {
          return { status: 400, message: "dataList must be a non-empty array" };
        }
        const result = await createBulkSys_paymentMethod(dataList, context);
        return { status: 200, content: result };
      }

m2mUpdateSys_paymentMethodById.js

module.exports = async (request) => {
        const { updateSys_paymentMethodById } = require("dbLayer");
        const context = { session: request.session, requestId: request.requestId };
        const id = request.body?.id || request.params?.id || request.id;
        const dataClause = request.body?.dataClause || request.dataClause || request.body;
        if (dataClause && dataClause.id) delete dataClause.id;
        if (!id) {
          return { status: 400, message: "ID is required" };
        }
        const result = await updateSys_paymentMethodById(id, dataClause, context);
        return { status: 200, content: result };
      }

m2mDeleteSys_paymentMethodById.js

module.exports = async (request) => {
        const { deleteSys_paymentMethodById } = require("dbLayer");
        const context = { session: request.session, requestId: request.requestId };
        const id = request.body?.id || request.params?.id || request.id;
        if (!id) {
          return { status: 400, message: "ID is required" };
        }
        const result = await deleteSys_paymentMethodById(id, context);
        return { status: 200, content: result };
      }

m2mUpdateSys_paymentMethodByQuery.js

module.exports = async (request) => {
        const { updateSys_paymentMethodByQuery } = require("dbLayer");
        const context = { session: request.session, requestId: request.requestId };
        const dataClause = request.body?.dataClause || request.dataClause || request.body;
        const query = request.body?.query || request.query || {};
        if (!query || typeof query !== "object" || Object.keys(query).length === 0) {
          return { status: 400, message: "Query is required and must be a non-empty object" };
        }
        const result = await updateSys_paymentMethodByQuery(dataClause, query, context);
        return { status: 200, content: result };
      }

m2mDeleteSys_paymentMethodByQuery.js

module.exports = async (request) => {
        const { deleteSys_paymentMethodByQuery } = require("dbLayer");
        const context = { session: request.session, requestId: request.requestId };
        const query = request.body?.query || request.query || {};
        if (!query || typeof query !== "object" || Object.keys(query).length === 0) {
          return { status: 400, message: "Query is required and must be a non-empty object" };
        }
        const result = await deleteSys_paymentMethodByQuery(query, context);
        return { status: 200, content: result };
      }

m2mUpdateSys_paymentMethodByIdList.js

module.exports = async (request) => {
        const { updateSys_paymentMethodByIdList } = require("dbLayer");
        const context = { session: request.session, requestId: request.requestId };
        const idList = request.body?.idList || request.idList || [];
        const dataClause = request.body?.dataClause || request.dataClause || request.body;
        if (dataClause && dataClause.idList) delete dataClause.idList;
        if (!Array.isArray(idList) || idList.length === 0) {
          return { status: 400, message: "idList must be a non-empty array" };
        }
        const result = await updateSys_paymentMethodByIdList(idList, dataClause, context);
        return { status: 200, content: result };
      }

Templates

No templates defined.

Assets

No assets defined.

Public Assets

No public assets defined.


Event Emission


Integration Patterns

Deployment Considerations

Environment Configuration

Implementation Guidelines

Development Workflow

  1. Data Model Implementation: Generate database schema from data object definitions
  2. CRUD Route Generation: Implement auto-generated routes with custom logic
  3. Custom Logic Integration: Implement hook functions and edge functions
  4. Authentication Integration: Configure with project-level authentication
  5. Testing: Unit and integration testing for all components

Code Generation Expectations

Custom Code Integration Points

Testing Strategy

Unit Testing

Integration Testing

Performance Testing


Appendices

Data Type Reference

Type Description Storage
ID Unique identifier UUID (SQL) / ObjectID (NoSQL)
String Short text (≤255 chars) VARCHAR
Text Long-form text TEXT
Integer 32-bit whole numbers INT
Boolean True/false values BOOLEAN
Double 64-bit floating point DOUBLE
Float 32-bit floating point FLOAT
Short 16-bit integers SMALLINT
Object JSON object JSONB (PostgreSQL) / Object (MongoDB)
Date ISO 8601 timestamp TIMESTAMP
Enum Fixed numeric values SMALLINT with lookup

Enum Value Mappings

Request Locations

HTTP Methods

Edge Function Signature

async function edgeFunction(request) {
  // Custom request processing
  // Return response object or throw error
  return {
    data: {},
    status: 200,
    message: "Success"
  };
}

This document was generated from the service architecture definition and should be kept in sync with implementation changes.


REST API GUIDE

REST API GUIDE

clonesahibinden-listing-service

Version: 1.0.3

Manages classified listings, their lifecycle, premium features, status transitions, and provides filtering/search for marketplace ads. Integrates with users, categories, locations, and Stripe for premium ad upgrades. Enforces ad and user type business logic.

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 Listing Service’s REST API. This document is designed to provide a comprehensive guide to interfacing with our Listing Service exclusively through RESTful API endpoints.

Intended Audience

This documentation is intended for developers and integrators who are looking to interact with the Listing Service via HTTP requests for purposes such as creating, updating, deleting and querying Listing 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 Listing 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 Listing 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 clonesahibinden-access-token
Cookie clonesahibinden-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 Listing 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 Listing 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 Listing 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 Listing 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 Listing 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 Listing 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

Listing 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.

Listing resource

Resource Definition : Core object for classified ads. Contains main listing information, relations, status, premium logic, price, attributes, contact info, and custom attributes. Supports premium upgrades via Stripe and lifecycle management. Listing Resource Properties

Name Type Required Default Definition
attributes Object JSON object for custom per-category attributes (structured as required by category schema).
categoryId ID Main category for the listing (categoryLocation:category).
condition Enum Item condition: new, used, other.
contactEmail String Contact email (recommended to send via platform only).
contactPhone String Display phone/contact for listing; may be masked by front end.
currency String Currency (ISO-4217 code, e.g. 'TRY', 'USD').
description Text Full description/body of listing.
expiresAt Date UTC expiry for listing; after this, listing is automatically expired.
favoriteCount Integer Favorite count (updated asynchronously by favorite service, not directly settable by user).
isPremium Boolean If true, the listing is premium (highlighted/pinned, eligible for special placement).
listingType Enum Type of listing (sale, rent, service, etc.).
locationId ID Location (categoryLocation:location).
_paymentConfirmation String Stripe payment result details (Stripe webhook metadata, internal use only).
premiumExpiry Date UTC date when premium status expires. Null if not premium or not applicable.
premiumType Enum Which premium package (gold, silver, none, etc.).
price Double Listing price.
status Enum Lifecycle status: pending_review, active, denied, sold, expired, deleted.
subcategoryId ID Subcategory for the listing, can be null for top-level (categoryLocation:category).
title String Listing title, short and clear.
userId ID Owner (poster) of the listing (auth:user).
viewsCount Integer View count (updated asynchronously; not directly settable by user).
paymentConfirmation Enum An automatic property that is used to check the confirmed status of the payment set by webhooks.

Enum Properties

Enum properties are represented as strings in the database. The values are mapped to their corresponding names in the application layer.

condition Enum Property

Property Definition : Item condition: new, used, other.Enum Options

Name Value Index
brand_new "brand_new"" 0
used "used"" 1
other "other"" 2
listingType Enum Property

Property Definition : Type of listing (sale, rent, service, etc.).Enum Options

Name Value Index
sale "sale"" 0
rent "rent"" 1
service "service"" 2
job "job"" 3
premiumType Enum Property

Property Definition : Which premium package (gold, silver, none, etc.).Enum Options

Name Value Index
none "none"" 0
bronze "bronze"" 1
silver "silver"" 2
gold "gold"" 3
status Enum Property

Property Definition : Lifecycle status: pending_review, active, denied, sold, expired, deleted.Enum Options

Name Value Index
pending_review "pending_review"" 0
active "active"" 1
denied "denied"" 2
sold "sold"" 3
expired "expired"" 4
deleted "deleted"" 5
paymentConfirmation Enum Property

Property Definition : An automatic property that is used to check the confirmed status of the payment set by webhooks.Enum Options

Name Value Index
pending "pending"" 0
processing "processing"" 1
paid "paid"" 2
canceled "canceled"" 3

Sys_listingPayment resource

Resource Definition : A payment storage object to store the payment life cyle of orders based on listing object. It is autocreated based on the source object's checkout config Sys_listingPayment Resource Properties

Name Type Required Default Definition
ownerId ID * An ID value to represent owner user who created the order*
orderId ID an ID value to represent the orderId which is the ID parameter of the source listing object
paymentId String A String value to represent the paymentId which is generated on the Stripe gateway. This id may represent different objects due to the payment gateway and the chosen flow type
paymentStatus String A string value to represent the payment status which belongs to the lifecyle of a Stripe payment.
statusLiteral String A string value to represent the logical payment status which belongs to the application lifecycle itself.
redirectUrl String A string value to represent return page of the frontend to show the result of the payment, this is used when the callback is made to server not the client.

Sys_paymentCustomer resource

Resource Definition : A payment storage object to store the customer values of the payment platform Sys_paymentCustomer Resource Properties

Name Type Required Default Definition
userId ID * An ID value to represent the user who is created as a stripe customer*
customerId String A string value to represent the customer id which is generated on the Stripe gateway. This id is used to represent the customer in the Stripe gateway
platform String A String value to represent payment platform which is used to make the payment. It is stripe as default. It will be used to distinguesh the payment gateways in the future.

Sys_paymentMethod resource

Resource Definition : A payment storage object to store the payment methods of the platform customers Sys_paymentMethod Resource Properties

Name Type Required Default Definition
paymentMethodId String A string value to represent the id of the payment method on the payment platform.
userId ID * An ID value to represent the user who owns the payment method*
customerId String A string value to represent the customer id which is generated on the payment gateway.
cardHolderName String A string value to represent the name of the card holder. It can be different than the registered customer.
cardHolderZip String A string value to represent the zip code of the card holder. It is used for address verification in specific countries.
platform String A String value to represent payment platform which teh paymentMethod belongs. It is stripe as default. It will be used to distinguesh the payment gateways in the future.
cardInfo Object A Json value to store the card details of the payment method.

Business Api

Create Listing API

Create a new classified listing. Sets status to ‘pending_review’ (may be updated by moderator process). Accepts all mandatory fields, accepts premiumType for premium upgrade.

API Frontend Description By The Backend Architect

Rest Route

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

/v1/listings

Rest Request Parameters

The createListing api has got 19 regular request parameters

Parameter Type Required Population
attributes Object false request.body?.[“attributes”]
categoryId ID true request.body?.[“categoryId”]
condition Enum true request.body?.[“condition”]
contactEmail String false request.body?.[“contactEmail”]
contactPhone String false request.body?.[“contactPhone”]
currency String true request.body?.[“currency”]
description Text true request.body?.[“description”]
expiresAt Date false request.body?.[“expiresAt”]
favoriteCount Integer true request.body?.[“favoriteCount”]
listingType Enum true request.body?.[“listingType”]
locationId ID true request.body?.[“locationId”]
_paymentConfirmation String false request.body?.[“_paymentConfirmation”]
premiumExpiry Date false request.body?.[“premiumExpiry”]
premiumType Enum false request.body?.[“premiumType”]
price Double true request.body?.[“price”]
status Enum true request.body?.[“status”]
subcategoryId ID false request.body?.[“subcategoryId”]
title String true request.body?.[“title”]
viewsCount Integer true request.body?.[“viewsCount”]
attributes : JSON object for custom per-category attributes (structured as required by category schema).
categoryId : Main category for the listing (categoryLocation:category).
condition : Item condition: new, used, other.
contactEmail : Contact email (recommended to send via platform only).
contactPhone : Display phone/contact for listing; may be masked by front end.
currency : Currency (ISO-4217 code, e.g. ‘TRY’, ‘USD’).
description : Full description/body of listing.
expiresAt : UTC expiry for listing; after this, listing is automatically expired.
favoriteCount : Favorite count (updated asynchronously by favorite service, not directly settable by user).
listingType : Type of listing (sale, rent, service, etc.).
locationId : Location (categoryLocation:location).
_paymentConfirmation : Stripe payment result details (Stripe webhook metadata, internal use only).
premiumExpiry : UTC date when premium status expires. Null if not premium or not applicable.
premiumType : Which premium package (gold, silver, none, etc.).
price : Listing price.
status : Lifecycle status: pending_review, active, denied, sold, expired, deleted.
subcategoryId : Subcategory for the listing, can be null for top-level (categoryLocation:category).
title : Listing title, short and clear.
viewsCount : View count (updated asynchronously; not directly settable by user).

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

  axios({
    method: 'POST',
    url: '/v1/listings',
    data: {
            attributes:"Object",  
            categoryId:"ID",  
            condition:"Enum",  
            contactEmail:"String",  
            contactPhone:"String",  
            currency:"String",  
            description:"Text",  
            expiresAt:"Date",  
            favoriteCount:"Integer",  
            listingType:"Enum",  
            locationId:"ID",  
            _paymentConfirmation:"String",  
            premiumExpiry:"Date",  
            premiumType:"Enum",  
            price:"Double",  
            status:"Enum",  
            subcategoryId:"ID",  
            title:"String",  
            viewsCount:"Integer",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "listing",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"listing": {
		"id": "ID",
		"attributes": "Object",
		"categoryId": "ID",
		"condition": "Enum",
		"condition_idx": "Integer",
		"contactEmail": "String",
		"contactPhone": "String",
		"currency": "String",
		"description": "Text",
		"expiresAt": "Date",
		"favoriteCount": "Integer",
		"isPremium": "Boolean",
		"listingType": "Enum",
		"listingType_idx": "Integer",
		"locationId": "ID",
		"_paymentConfirmation": "String",
		"premiumExpiry": "Date",
		"premiumType": "Enum",
		"premiumType_idx": "Integer",
		"price": "Double",
		"status": "Enum",
		"status_idx": "Integer",
		"subcategoryId": "ID",
		"title": "String",
		"userId": "ID",
		"viewsCount": "Integer",
		"paymentConfirmation": "Enum",
		"paymentConfirmation_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Delete Listing API

Delete a listing (soft delete, sets status to ‘deleted’). Only allowed by listing owner, admin, or moderator.

API Frontend Description By The Backend Architect

Rest Route

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

/v1/listings/:listingId

Rest Request Parameters

The deleteListing api has got 1 regular request parameter

Parameter Type Required Population
listingId ID true request.params?.[“listingId”]
listingId : 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/listings/:listingId

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

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "listing",
	"method": "DELETE",
	"action": "delete",
	"appVersion": "Version",
	"rowCount": 1,
	"listing": {
		"id": "ID",
		"attributes": "Object",
		"categoryId": "ID",
		"condition": "Enum",
		"condition_idx": "Integer",
		"contactEmail": "String",
		"contactPhone": "String",
		"currency": "String",
		"description": "Text",
		"expiresAt": "Date",
		"favoriteCount": "Integer",
		"isPremium": "Boolean",
		"listingType": "Enum",
		"listingType_idx": "Integer",
		"locationId": "ID",
		"_paymentConfirmation": "String",
		"premiumExpiry": "Date",
		"premiumType": "Enum",
		"premiumType_idx": "Integer",
		"price": "Double",
		"status": "Enum",
		"status_idx": "Integer",
		"subcategoryId": "ID",
		"title": "String",
		"userId": "ID",
		"viewsCount": "Integer",
		"paymentConfirmation": "Enum",
		"paymentConfirmation_idx": "Integer",
		"isActive": false,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Get Listing API

Retrieve one listing with all primary fields, including category, subcategory, location, user info. Optionally, frontend can request joined images/favorites from other services.

API Frontend Description By The Backend Architect

Rest Route

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

/v1/listings/:listingId

Rest Request Parameters

The getListing api has got 1 regular request parameter

Parameter Type Required Population
listingId ID true request.params?.[“listingId”]
listingId : 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/listings/:listingId

  axios({
    method: 'GET',
    url: `/v1/listings/${listingId}`,
    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": "listing",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"listing": {
		"user": {
			"fullname": "String",
			"avatar": "String",
			"roleId": "String"
		},
		"category": {
			"name": "String",
			"parentCategoryId": "ID",
			"slug": "String"
		},
		"subcategory": {
			"name": "String",
			"parentCategoryId": "ID",
			"slug": "String"
		},
		"location": {
			"city": "String",
			"country": "String",
			"district": "String"
		},
		"isActive": true
	}
}

List Listings API

Search/browse listings with advanced filtering (category, location, keyword, price range, condition, type, premium, status, etc.) and sorting. Publicly accessible. Supports pagination and all major sort orders. Full-text search on title/description.

API Frontend Description By The Backend Architect

Rest Route

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

/v1/listings

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

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

  axios({
    method: 'GET',
    url: '/v1/listings',
    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": "listings",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"listings": [
		{
			"user": [
				{
					"fullname": "String",
					"avatar": "String"
				},
				{},
				{}
			],
			"category": [
				{
					"name": "String"
				},
				{},
				{}
			],
			"subcategory": [
				{
					"name": "String"
				},
				{},
				{}
			],
			"location": [
				{
					"city": "String",
					"district": "String"
				},
				{},
				{}
			],
			"isActive": true
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Update Listing API

Update any mutable field of a listing. Only allowed by owner, admin, or moderator. If significant fields change and listing is active, status may return to pending_review until approved.

API Frontend Description By The Backend Architect

Rest Route

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

/v1/listings/:listingId

Rest Request Parameters

The updateListing api has got 17 regular request parameters

Parameter Type Required Population
listingId ID true request.params?.[“listingId”]
attributes Object false request.body?.[“attributes”]
categoryId ID false request.body?.[“categoryId”]
condition Enum false request.body?.[“condition”]
contactEmail String false request.body?.[“contactEmail”]
contactPhone String false request.body?.[“contactPhone”]
currency String false request.body?.[“currency”]
description Text false request.body?.[“description”]
expiresAt Date false request.body?.[“expiresAt”]
listingType Enum false request.body?.[“listingType”]
locationId ID false request.body?.[“locationId”]
premiumExpiry Date false request.body?.[“premiumExpiry”]
premiumType Enum false request.body?.[“premiumType”]
price Double false request.body?.[“price”]
status Enum false request.body?.[“status”]
subcategoryId ID false request.body?.[“subcategoryId”]
title String false request.body?.[“title”]
listingId : This id paremeter is used to select the required data object that will be updated
attributes : JSON object for custom per-category attributes (structured as required by category schema).
categoryId : Main category for the listing (categoryLocation:category).
condition : Item condition: new, used, other.
contactEmail : Contact email (recommended to send via platform only).
contactPhone : Display phone/contact for listing; may be masked by front end.
currency : Currency (ISO-4217 code, e.g. ‘TRY’, ‘USD’).
description : Full description/body of listing.
expiresAt : UTC expiry for listing; after this, listing is automatically expired.
listingType : Type of listing (sale, rent, service, etc.).
locationId : Location (categoryLocation:location).
premiumExpiry : UTC date when premium status expires. Null if not premium or not applicable.
premiumType : Which premium package (gold, silver, none, etc.).
price : Listing price.
status : Lifecycle status: pending_review, active, denied, sold, expired, deleted.
subcategoryId : Subcategory for the listing, can be null for top-level (categoryLocation:category).
title : Listing title, short and clear.

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

  axios({
    method: 'PATCH',
    url: `/v1/listings/${listingId}`,
    data: {
            attributes:"Object",  
            categoryId:"ID",  
            condition:"Enum",  
            contactEmail:"String",  
            contactPhone:"String",  
            currency:"String",  
            description:"Text",  
            expiresAt:"Date",  
            listingType:"Enum",  
            locationId:"ID",  
            premiumExpiry:"Date",  
            premiumType:"Enum",  
            price:"Double",  
            status:"Enum",  
            subcategoryId:"ID",  
            title:"String",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "listing",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"listing": {
		"id": "ID",
		"attributes": "Object",
		"categoryId": "ID",
		"condition": "Enum",
		"condition_idx": "Integer",
		"contactEmail": "String",
		"contactPhone": "String",
		"currency": "String",
		"description": "Text",
		"expiresAt": "Date",
		"favoriteCount": "Integer",
		"isPremium": "Boolean",
		"listingType": "Enum",
		"listingType_idx": "Integer",
		"locationId": "ID",
		"_paymentConfirmation": "String",
		"premiumExpiry": "Date",
		"premiumType": "Enum",
		"premiumType_idx": "Integer",
		"price": "Double",
		"status": "Enum",
		"status_idx": "Integer",
		"subcategoryId": "ID",
		"title": "String",
		"userId": "ID",
		"viewsCount": "Integer",
		"paymentConfirmation": "Enum",
		"paymentConfirmation_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Upgrade Listingpremium API

Upgrades a listing to premium status after successful payment. Sets isPremium=true, premiumType, premiumExpiry based on duration, and records payment confirmation. Called internally by payment service via interservice call.

API Frontend Description By The Backend Architect

Rest Route

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

/v1/listings/upgrade-premium

Rest Request Parameters

The upgradeListingPremium api has got 4 regular request parameters

Parameter Type Required Population
listingId ID true request.body?.[“listingId”]
premiumType Enum true request.body?.[“premiumType”]
premiumDuration Integer true request.body?.[“premiumDuration”]
paymentTransactionId ID true request.body?.[“paymentTransactionId”]
listingId : ID of the listing to upgrade
premiumType : Premium package type (bronze, silver, gold)
premiumDuration : Duration of premium in days
paymentTransactionId : Payment transaction ID for confirmation record

REST Request To access the api you can use the REST controller with the path POST /v1/listings/upgrade-premium

  axios({
    method: 'POST',
    url: '/v1/listings/upgrade-premium',
    data: {
            listingId:"ID",  
            premiumType:"Enum",  
            premiumDuration:"Integer",  
            paymentTransactionId:"ID",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "listing",
	"method": "POST",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"listing": {
		"id": "ID",
		"attributes": "Object",
		"categoryId": "ID",
		"condition": "Enum",
		"condition_idx": "Integer",
		"contactEmail": "String",
		"contactPhone": "String",
		"currency": "String",
		"description": "Text",
		"expiresAt": "Date",
		"favoriteCount": "Integer",
		"isPremium": "Boolean",
		"listingType": "Enum",
		"listingType_idx": "Integer",
		"locationId": "ID",
		"_paymentConfirmation": "String",
		"premiumExpiry": "Date",
		"premiumType": "Enum",
		"premiumType_idx": "Integer",
		"price": "Double",
		"status": "Enum",
		"status_idx": "Integer",
		"subcategoryId": "ID",
		"title": "String",
		"userId": "ID",
		"viewsCount": "Integer",
		"paymentConfirmation": "Enum",
		"paymentConfirmation_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Get Listingpayment API

This route is used to get the payment information by ID.

Rest Route

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

/v1/listingpayment/:sys_listingPaymentId

Rest Request Parameters

The getListingPayment api has got 1 regular request parameter

Parameter Type Required Population
sys_listingPaymentId ID true request.params?.[“sys_listingPaymentId”]
sys_listingPaymentId : 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/listingpayment/:sys_listingPaymentId

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

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_listingPayment",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"sys_listingPayment": {
		"id": "ID",
		"ownerId": "ID",
		"orderId": "ID",
		"paymentId": "String",
		"paymentStatus": "String",
		"statusLiteral": "String",
		"redirectUrl": "String",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

List Listingpayments API

This route is used to list all payments.

Rest Route

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

/v1/listingpayments

Rest Request Parameters

Filter Parameters

The listListingPayments api supports 6 optional filter parameters for filtering list results:

ownerId (ID): An ID value to represent owner user who created the order

orderId (ID): an ID value to represent the orderId which is the ID parameter of the source listing object

paymentId (String): A String value to represent the paymentId which is generated on the Stripe gateway. This id may represent different objects due to the payment gateway and the chosen flow type

paymentStatus (String): A string value to represent the payment status which belongs to the lifecyle of a Stripe payment.

statusLiteral (String): A string value to represent the logical payment status which belongs to the application lifecycle itself.

redirectUrl (String): A string value to represent return page of the frontend to show the result of the payment, this is used when the callback is made to server not the client.

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

  axios({
    method: 'GET',
    url: '/v1/listingpayments',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section above)
        // ownerId: '<value>' // Filter by ownerId
        // orderId: '<value>' // Filter by orderId
        // paymentId: '<value>' // Filter by paymentId
        // paymentStatus: '<value>' // Filter by paymentStatus
        // statusLiteral: '<value>' // Filter by statusLiteral
        // redirectUrl: '<value>' // Filter by redirectUrl
            }
  });

REST Response

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

Create Listingpayment API

This route is used to create a new payment.

Rest Route

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

/v1/listingpayment

Rest Request Parameters

The createListingPayment api has got 5 regular request parameters

Parameter Type Required Population
orderId ID true request.body?.[“orderId”]
paymentId String true request.body?.[“paymentId”]
paymentStatus String true request.body?.[“paymentStatus”]
statusLiteral String true request.body?.[“statusLiteral”]
redirectUrl String false request.body?.[“redirectUrl”]
orderId : an ID value to represent the orderId which is the ID parameter of the source listing object
paymentId : A String value to represent the paymentId which is generated on the Stripe gateway. This id may represent different objects due to the payment gateway and the chosen flow type
paymentStatus : A string value to represent the payment status which belongs to the lifecyle of a Stripe payment.
statusLiteral : A string value to represent the logical payment status which belongs to the application lifecycle itself.
redirectUrl : A string value to represent return page of the frontend to show the result of the payment, this is used when the callback is made to server not the client.

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

  axios({
    method: 'POST',
    url: '/v1/listingpayment',
    data: {
            orderId:"ID",  
            paymentId:"String",  
            paymentStatus:"String",  
            statusLiteral:"String",  
            redirectUrl:"String",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_listingPayment",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"sys_listingPayment": {
		"id": "ID",
		"ownerId": "ID",
		"orderId": "ID",
		"paymentId": "String",
		"paymentStatus": "String",
		"statusLiteral": "String",
		"redirectUrl": "String",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Update Listingpayment API

This route is used to update an existing payment.

Rest Route

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

/v1/listingpayment/:sys_listingPaymentId

Rest Request Parameters

The updateListingPayment api has got 5 regular request parameters

Parameter Type Required Population
sys_listingPaymentId ID true request.params?.[“sys_listingPaymentId”]
paymentId String false request.body?.[“paymentId”]
paymentStatus String false request.body?.[“paymentStatus”]
statusLiteral String false request.body?.[“statusLiteral”]
redirectUrl String false request.body?.[“redirectUrl”]
sys_listingPaymentId : This id paremeter is used to select the required data object that will be updated
paymentId : A String value to represent the paymentId which is generated on the Stripe gateway. This id may represent different objects due to the payment gateway and the chosen flow type
paymentStatus : A string value to represent the payment status which belongs to the lifecyle of a Stripe payment.
statusLiteral : A string value to represent the logical payment status which belongs to the application lifecycle itself.
redirectUrl : A string value to represent return page of the frontend to show the result of the payment, this is used when the callback is made to server not the client.

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

  axios({
    method: 'PATCH',
    url: `/v1/listingpayment/${sys_listingPaymentId}`,
    data: {
            paymentId:"String",  
            paymentStatus:"String",  
            statusLiteral:"String",  
            redirectUrl:"String",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_listingPayment",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"sys_listingPayment": {
		"id": "ID",
		"ownerId": "ID",
		"orderId": "ID",
		"paymentId": "String",
		"paymentStatus": "String",
		"statusLiteral": "String",
		"redirectUrl": "String",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Delete Listingpayment API

This route is used to delete a payment.

Rest Route

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

/v1/listingpayment/:sys_listingPaymentId

Rest Request Parameters

The deleteListingPayment api has got 1 regular request parameter

Parameter Type Required Population
sys_listingPaymentId ID true request.params?.[“sys_listingPaymentId”]
sys_listingPaymentId : 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/listingpayment/:sys_listingPaymentId

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

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_listingPayment",
	"method": "DELETE",
	"action": "delete",
	"appVersion": "Version",
	"rowCount": 1,
	"sys_listingPayment": {
		"id": "ID",
		"ownerId": "ID",
		"orderId": "ID",
		"paymentId": "String",
		"paymentStatus": "String",
		"statusLiteral": "String",
		"redirectUrl": "String",
		"isActive": false,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Get Listingpaymentbyorderid API

This route is used to get the payment information by order id.

Rest Route

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

/v1/listingpaymentbyorderid/:orderId

Rest Request Parameters

The getListingPaymentByOrderId api has got 2 regular request parameters

Parameter Type Required Population
sys_listingPaymentId ID true request.params?.[“sys_listingPaymentId”]
orderId ID true request.params?.[“orderId”]
sys_listingPaymentId : This id paremeter is used to query the required data object.
orderId : an ID value to represent the orderId which is the ID parameter of the source listing object. The parameter is used to query data.

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

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

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_listingPayment",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"sys_listingPayment": {
		"id": "ID",
		"ownerId": "ID",
		"orderId": "ID",
		"paymentId": "String",
		"paymentStatus": "String",
		"statusLiteral": "String",
		"redirectUrl": "String",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Get Listingpaymentbypaymentid API

This route is used to get the payment information by payment id.

Rest Route

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

/v1/listingpaymentbypaymentid/:paymentId

Rest Request Parameters

The getListingPaymentByPaymentId api has got 2 regular request parameters

Parameter Type Required Population
sys_listingPaymentId ID true request.params?.[“sys_listingPaymentId”]
paymentId String true request.params?.[“paymentId”]
sys_listingPaymentId : This id paremeter is used to query the required data object.
paymentId : A String value to represent the paymentId which is generated on the Stripe gateway. This id may represent different objects due to the payment gateway and the chosen flow type. The parameter is used to query data.

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

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

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_listingPayment",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"sys_listingPayment": {
		"id": "ID",
		"ownerId": "ID",
		"orderId": "ID",
		"paymentId": "String",
		"paymentStatus": "String",
		"statusLiteral": "String",
		"redirectUrl": "String",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Start Listingpayment API

Start payment for listing

Rest Route

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

/v1/startlistingpayment/:listingId

Rest Request Parameters

The startListingPayment api has got 2 regular request parameters

Parameter Type Required Population
listingId ID true request.params?.[“listingId”]
paymentUserParams Object false request.body?.[“paymentUserParams”]
listingId : This id paremeter is used to select the required data object that will be updated
paymentUserParams : The user parameters that should be defined to start a stripe payment process

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

  axios({
    method: 'PATCH',
    url: `/v1/startlistingpayment/${listingId}`,
    data: {
            paymentUserParams:"Object",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "listing",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"listing": {
		"id": "ID",
		"attributes": "Object",
		"categoryId": "ID",
		"condition": "Enum",
		"condition_idx": "Integer",
		"contactEmail": "String",
		"contactPhone": "String",
		"currency": "String",
		"description": "Text",
		"expiresAt": "Date",
		"favoriteCount": "Integer",
		"isPremium": "Boolean",
		"listingType": "Enum",
		"listingType_idx": "Integer",
		"locationId": "ID",
		"_paymentConfirmation": "String",
		"premiumExpiry": "Date",
		"premiumType": "Enum",
		"premiumType_idx": "Integer",
		"price": "Double",
		"status": "Enum",
		"status_idx": "Integer",
		"subcategoryId": "ID",
		"title": "String",
		"userId": "ID",
		"viewsCount": "Integer",
		"paymentConfirmation": "Enum",
		"paymentConfirmation_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	},
	"paymentResult": {
		"paymentTicketId": "ID",
		"orderId": "ID",
		"paymentId": "String",
		"paymentStatus": "Enum",
		"paymentIntentInfo": "Object",
		"statusLiteral": "String",
		"amount": "Double",
		"currency": "String",
		"success": true,
		"description": "String",
		"metadata": "Object",
		"paymentUserParams": "Object"
	}
}

Refresh Listingpayment API

Refresh payment info for listing from Stripe

Rest Route

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

/v1/refreshlistingpayment/:listingId

Rest Request Parameters

The refreshListingPayment api has got 2 regular request parameters

Parameter Type Required Population
listingId ID true request.params?.[“listingId”]
paymentUserParams Object false request.body?.[“paymentUserParams”]
listingId : This id paremeter is used to select the required data object that will be updated
paymentUserParams : The user parameters that should be defined to refresh a stripe payment process

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

  axios({
    method: 'PATCH',
    url: `/v1/refreshlistingpayment/${listingId}`,
    data: {
            paymentUserParams:"Object",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "listing",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"listing": {
		"id": "ID",
		"attributes": "Object",
		"categoryId": "ID",
		"condition": "Enum",
		"condition_idx": "Integer",
		"contactEmail": "String",
		"contactPhone": "String",
		"currency": "String",
		"description": "Text",
		"expiresAt": "Date",
		"favoriteCount": "Integer",
		"isPremium": "Boolean",
		"listingType": "Enum",
		"listingType_idx": "Integer",
		"locationId": "ID",
		"_paymentConfirmation": "String",
		"premiumExpiry": "Date",
		"premiumType": "Enum",
		"premiumType_idx": "Integer",
		"price": "Double",
		"status": "Enum",
		"status_idx": "Integer",
		"subcategoryId": "ID",
		"title": "String",
		"userId": "ID",
		"viewsCount": "Integer",
		"paymentConfirmation": "Enum",
		"paymentConfirmation_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	},
	"paymentResult": {
		"paymentTicketId": "ID",
		"orderId": "ID",
		"paymentId": "String",
		"paymentStatus": "Enum",
		"paymentIntentInfo": "Object",
		"statusLiteral": "String",
		"amount": "Double",
		"currency": "String",
		"success": true,
		"description": "String",
		"metadata": "Object",
		"paymentUserParams": "Object"
	}
}

Callback Listingpayment API

Refresh payment values by gateway webhook call for listing

Rest Route

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

/v1/callbacklistingpayment

Rest Request Parameters

The callbackListingPayment api has got 1 regular request parameter

Parameter Type Required Population
listingId ID true request.body?.[“listingId”]
listingId : The order id parameter that will be read from webhook callback params

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

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

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "listing",
	"method": "POST",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"listing": {
		"id": "ID",
		"attributes": "Object",
		"categoryId": "ID",
		"condition": "Enum",
		"condition_idx": "Integer",
		"contactEmail": "String",
		"contactPhone": "String",
		"currency": "String",
		"description": "Text",
		"expiresAt": "Date",
		"favoriteCount": "Integer",
		"isPremium": "Boolean",
		"listingType": "Enum",
		"listingType_idx": "Integer",
		"locationId": "ID",
		"_paymentConfirmation": "String",
		"premiumExpiry": "Date",
		"premiumType": "Enum",
		"premiumType_idx": "Integer",
		"price": "Double",
		"status": "Enum",
		"status_idx": "Integer",
		"subcategoryId": "ID",
		"title": "String",
		"userId": "ID",
		"viewsCount": "Integer",
		"paymentConfirmation": "Enum",
		"paymentConfirmation_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	},
	"paymentResult": {
		"paymentTicketId": "ID",
		"orderId": "ID",
		"paymentId": "String",
		"paymentStatus": "Enum",
		"paymentIntentInfo": "Object",
		"statusLiteral": "String",
		"amount": "Double",
		"currency": "String",
		"success": true,
		"description": "String",
		"metadata": "Object",
		"paymentUserParams": "Object"
	}
}

Get Paymentcustomerbyuserid API

This route is used to get the payment customer information by user id.

Rest Route

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

/v1/paymentcustomers/:userId

Rest Request Parameters

The getPaymentCustomerByUserId api has got 2 regular request parameters

Parameter Type Required Population
sys_paymentCustomerId ID true request.params?.[“sys_paymentCustomerId”]
userId ID true request.params?.[“userId”]
sys_paymentCustomerId : This id paremeter is used to query the required data object.
userId : An ID value to represent the user who is created as a stripe customer. The parameter is used to query data.

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

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

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_paymentCustomer",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"sys_paymentCustomer": {
		"id": "ID",
		"userId": "ID",
		"customerId": "String",
		"platform": "String",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

List Paymentcustomers API

This route is used to list all payment customers.

Rest Route

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

/v1/paymentcustomers

Rest Request Parameters

Filter Parameters

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

userId (ID): An ID value to represent the user who is created as a stripe customer

customerId (String): A string value to represent the customer id which is generated on the Stripe gateway. This id is used to represent the customer in the Stripe gateway

platform (String): A String value to represent payment platform which is used to make the payment. It is stripe as default. It will be used to distinguesh the payment gateways in the future.

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

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

REST Response

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

List Paymentcustomermethods API

This route is used to list all payment customer methods.

Rest Route

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

/v1/paymentcustomermethods/:userId

Rest Request Parameters

Filter Parameters

The listPaymentCustomerMethods api supports 6 optional filter parameters for filtering list results:

paymentMethodId (String): A string value to represent the id of the payment method on the payment platform.

customerId (String): A string value to represent the customer id which is generated on the payment gateway.

cardHolderName (String): A string value to represent the name of the card holder. It can be different than the registered customer.

cardHolderZip (String): A string value to represent the zip code of the card holder. It is used for address verification in specific countries.

platform (String): A String value to represent payment platform which teh paymentMethod belongs. It is stripe as default. It will be used to distinguesh the payment gateways in the future.

cardInfo (Object): A Json value to store the card details of the payment method.

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

  axios({
    method: 'GET',
    url: `/v1/paymentcustomermethods/${userId}`,
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section above)
        // paymentMethodId: '<value>' // Filter by paymentMethodId
        // customerId: '<value>' // Filter by customerId
        // cardHolderName: '<value>' // Filter by cardHolderName
        // cardHolderZip: '<value>' // Filter by cardHolderZip
        // platform: '<value>' // Filter by platform
        // cardInfo: '<value>' // Filter by cardInfo
            }
  });

REST Response

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

_fetch Listlisting API

System API to fetch list of listing records for frontend application. Auto-generated, not visible in design.

Rest Route

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

/v1/_fetchlistlisting

Rest Request Parameters

Filter Parameters

The _fetchListListing api supports 14 optional filter parameters for filtering list results:

categoryId (ID): Main category for the listing (categoryLocation:category).

condition (Enum): Item condition: new, used, other.

expiresAt (Date): UTC expiry for listing; after this, listing is automatically expired.

isPremium (Boolean): If true, the listing is premium (highlighted/pinned, eligible for special placement).

listingType (Enum): Type of listing (sale, rent, service, etc.).

locationId (ID): Location (categoryLocation:location).

premiumExpiry (Date): UTC date when premium status expires. Null if not premium or not applicable.

premiumType (Enum): Which premium package (gold, silver, none, etc.).

price (Double): Listing price.

status (Enum): Lifecycle status: pending_review, active, denied, sold, expired, deleted.

subcategoryId (ID): Subcategory for the listing, can be null for top-level (categoryLocation:category).

title (String): Listing title, short and clear.

userId (ID): Owner (poster) of the listing (auth:user).

paymentConfirmation (Enum): An automatic property that is used to check the confirmed status of the payment set by webhooks.

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

  axios({
    method: 'GET',
    url: '/v1/_fetchlistlisting',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section above)
        // categoryId: '<value>' // Filter by categoryId
        // condition: '<value>' // Filter by condition
        // expiresAt: '<value>' // Filter by expiresAt
        // isPremium: '<value>' // Filter by isPremium
        // listingType: '<value>' // Filter by listingType
        // locationId: '<value>' // Filter by locationId
        // premiumExpiry: '<value>' // Filter by premiumExpiry
        // premiumType: '<value>' // Filter by premiumType
        // price: '<value>' // Filter by price
        // status: '<value>' // Filter by status
        // subcategoryId: '<value>' // Filter by subcategoryId
        // title: '<value>' // Filter by title
        // userId: '<value>' // Filter by userId
        // paymentConfirmation: '<value>' // Filter by paymentConfirmation
            }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "listings",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"listings": [
		{
			"id": "ID",
			"attributes": "Object",
			"categoryId": "ID",
			"condition": "Enum",
			"condition_idx": "Integer",
			"contactEmail": "String",
			"contactPhone": "String",
			"currency": "String",
			"description": "Text",
			"expiresAt": "Date",
			"favoriteCount": "Integer",
			"isPremium": "Boolean",
			"listingType": "Enum",
			"listingType_idx": "Integer",
			"locationId": "ID",
			"_paymentConfirmation": "String",
			"premiumExpiry": "Date",
			"premiumType": "Enum",
			"premiumType_idx": "Integer",
			"price": "Double",
			"status": "Enum",
			"status_idx": "Integer",
			"subcategoryId": "ID",
			"title": "String",
			"userId": "ID",
			"viewsCount": "Integer",
			"paymentConfirmation": "Enum",
			"paymentConfirmation_idx": "Integer",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID",
			"mainCategory": [
				{
					"description": "Text",
					"icon": "String",
					"name": "String",
					"parentCategoryId": "ID",
					"slug": "String",
					"sortOrder": "Integer"
				},
				{},
				{}
			],
			"location": [
				{
					"city": "String",
					"country": "String",
					"district": "String",
					"latitude": "Double",
					"longitude": "Double",
					"postalCode": "String"
				},
				{},
				{}
			],
			"subCategory": [
				{
					"description": "Text",
					"icon": "String",
					"name": "String",
					"parentCategoryId": "ID",
					"slug": "String",
					"sortOrder": "Integer"
				},
				{},
				{}
			],
			"user": [
				{
					"fullname": "String"
				},
				{},
				{}
			]
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

_fetch Listsys_listingpayment API

System API to fetch list of sys_listingPayment records for frontend application. Auto-generated, not visible in design.

Rest Route

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

/v1/_fetchlistsys_listingpayment

Rest Request Parameters

Filter Parameters

The _fetchListSys_listingPayment api supports 6 optional filter parameters for filtering list results:

ownerId (ID): An ID value to represent owner user who created the order

orderId (ID): an ID value to represent the orderId which is the ID parameter of the source listing object

paymentId (String): A String value to represent the paymentId which is generated on the Stripe gateway. This id may represent different objects due to the payment gateway and the chosen flow type

paymentStatus (String): A string value to represent the payment status which belongs to the lifecyle of a Stripe payment.

statusLiteral (String): A string value to represent the logical payment status which belongs to the application lifecycle itself.

redirectUrl (String): A string value to represent return page of the frontend to show the result of the payment, this is used when the callback is made to server not the client.

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

  axios({
    method: 'GET',
    url: '/v1/_fetchlistsys_listingpayment',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section above)
        // ownerId: '<value>' // Filter by ownerId
        // orderId: '<value>' // Filter by orderId
        // paymentId: '<value>' // Filter by paymentId
        // paymentStatus: '<value>' // Filter by paymentStatus
        // statusLiteral: '<value>' // Filter by statusLiteral
        // redirectUrl: '<value>' // Filter by redirectUrl
            }
  });

REST Response

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

_fetch Listsys_paymentcustomer API

System API to fetch list of sys_paymentCustomer records for frontend application. Auto-generated, not visible in design.

Rest Route

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

/v1/_fetchlistsys_paymentcustomer

Rest Request Parameters

Filter Parameters

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

userId (ID): An ID value to represent the user who is created as a stripe customer

customerId (String): A string value to represent the customer id which is generated on the Stripe gateway. This id is used to represent the customer in the Stripe gateway

platform (String): A String value to represent payment platform which is used to make the payment. It is stripe as default. It will be used to distinguesh the payment gateways in the future.

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

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

REST Response

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

_fetch Listsys_paymentmethod API

System API to fetch list of sys_paymentMethod records for frontend application. Auto-generated, not visible in design.

Rest Route

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

/v1/_fetchlistsys_paymentmethod

Rest Request Parameters

Filter Parameters

The _fetchListSys_paymentMethod api supports 7 optional filter parameters for filtering list results:

paymentMethodId (String): A string value to represent the id of the payment method on the payment platform.

userId (ID): An ID value to represent the user who owns the payment method

customerId (String): A string value to represent the customer id which is generated on the payment gateway.

cardHolderName (String): A string value to represent the name of the card holder. It can be different than the registered customer.

cardHolderZip (String): A string value to represent the zip code of the card holder. It is used for address verification in specific countries.

platform (String): A String value to represent payment platform which teh paymentMethod belongs. It is stripe as default. It will be used to distinguesh the payment gateways in the future.

cardInfo (Object): A Json value to store the card details of the payment method.

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

  axios({
    method: 'GET',
    url: '/v1/_fetchlistsys_paymentmethod',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section above)
        // paymentMethodId: '<value>' // Filter by paymentMethodId
        // userId: '<value>' // Filter by userId
        // customerId: '<value>' // Filter by customerId
        // cardHolderName: '<value>' // Filter by cardHolderName
        // cardHolderZip: '<value>' // Filter by cardHolderZip
        // platform: '<value>' // Filter by platform
        // cardInfo: '<value>' // Filter by cardInfo
            }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_paymentMethods",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"sys_paymentMethods": [
		{
			"id": "ID",
			"paymentMethodId": "String",
			"userId": "ID",
			"customerId": "String",
			"cardHolderName": "String",
			"cardHolderZip": "String",
			"platform": "String",
			"cardInfo": "Object",
			"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

clonesahibinden-listing-service

Manages classified listings, their lifecycle, premium features, status transitions, and provides filtering/search for marketplace ads. Integrates with users, categories, locations, and Stripe for premium ad upgrades. Enforces ad and user type business logic.

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 Listing Service Event descriptions. This guide is dedicated to detailing how to subscribe to and listen for state changes within the Listing Service, offering an exclusive focus on event subscription mechanisms.

Intended Audience

This documentation is aimed at developers and integrators looking to monitor Listing Service state changes. It is especially relevant for those wishing to implement or enhance business logic based on interactions with Listing 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 Listing 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 listing-created

Event topic: clonesahibinden-listing-service-dbevent-listing-created

This event is triggered upon the creation of a listing data object in the database. The event payload encompasses the newly created data, encapsulated within the root of the paylod.

Event payload:

{"id":"ID","attributes":"Object","categoryId":"ID","condition":"Enum","condition_idx":"Integer","contactEmail":"String","contactPhone":"String","currency":"String","description":"Text","expiresAt":"Date","favoriteCount":"Integer","isPremium":"Boolean","listingType":"Enum","listingType_idx":"Integer","locationId":"ID","_paymentConfirmation":"String","premiumExpiry":"Date","premiumType":"Enum","premiumType_idx":"Integer","price":"Double","status":"Enum","status_idx":"Integer","subcategoryId":"ID","title":"String","userId":"ID","viewsCount":"Integer","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

DbEvent listing-updated

Event topic: clonesahibinden-listing-service-dbevent-listing-updated

Activation of this event follows the update of a listing data object. The payload contains the updated information under the listing attribute, along with the original data prior to update, labeled as old_listing and also you can find the old and new versions of updated-only portion of the data…

Event payload:

{
old_listing:{"id":"ID","attributes":"Object","categoryId":"ID","condition":"Enum","condition_idx":"Integer","contactEmail":"String","contactPhone":"String","currency":"String","description":"Text","expiresAt":"Date","favoriteCount":"Integer","isPremium":"Boolean","listingType":"Enum","listingType_idx":"Integer","locationId":"ID","_paymentConfirmation":"String","premiumExpiry":"Date","premiumType":"Enum","premiumType_idx":"Integer","price":"Double","status":"Enum","status_idx":"Integer","subcategoryId":"ID","title":"String","userId":"ID","viewsCount":"Integer","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},
listing:{"id":"ID","attributes":"Object","categoryId":"ID","condition":"Enum","condition_idx":"Integer","contactEmail":"String","contactPhone":"String","currency":"String","description":"Text","expiresAt":"Date","favoriteCount":"Integer","isPremium":"Boolean","listingType":"Enum","listingType_idx":"Integer","locationId":"ID","_paymentConfirmation":"String","premiumExpiry":"Date","premiumType":"Enum","premiumType_idx":"Integer","price":"Double","status":"Enum","status_idx":"Integer","subcategoryId":"ID","title":"String","userId":"ID","viewsCount":"Integer","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},
oldDataValues,
newDataValues
}

DbEvent listing-deleted

Event topic: clonesahibinden-listing-service-dbevent-listing-deleted

This event announces the deletion of a listing 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","attributes":"Object","categoryId":"ID","condition":"Enum","condition_idx":"Integer","contactEmail":"String","contactPhone":"String","currency":"String","description":"Text","expiresAt":"Date","favoriteCount":"Integer","isPremium":"Boolean","listingType":"Enum","listingType_idx":"Integer","locationId":"ID","_paymentConfirmation":"String","premiumExpiry":"Date","premiumType":"Enum","premiumType_idx":"Integer","price":"Double","status":"Enum","status_idx":"Integer","subcategoryId":"ID","title":"String","userId":"ID","viewsCount":"Integer","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

DbEvent sys_listingPayment-created

Event topic: clonesahibinden-listing-service-dbevent-sys_listingpayment-created

This event is triggered upon the creation of a sys_listingPayment data object in the database. The event payload encompasses the newly created data, encapsulated within the root of the paylod.

Event payload:

{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

DbEvent sys_listingPayment-updated

Event topic: clonesahibinden-listing-service-dbevent-sys_listingpayment-updated

Activation of this event follows the update of a sys_listingPayment data object. The payload contains the updated information under the sys_listingPayment attribute, along with the original data prior to update, labeled as old_sys_listingPayment and also you can find the old and new versions of updated-only portion of the data…

Event payload:

{
old_sys_listingPayment:{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},
sys_listingPayment:{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},
oldDataValues,
newDataValues
}

DbEvent sys_listingPayment-deleted

Event topic: clonesahibinden-listing-service-dbevent-sys_listingpayment-deleted

This event announces the deletion of a sys_listingPayment 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","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

DbEvent sys_paymentCustomer-created

Event topic: clonesahibinden-listing-service-dbevent-sys_paymentcustomer-created

This event is triggered upon the creation of a sys_paymentCustomer 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","customerId":"String","platform":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

DbEvent sys_paymentCustomer-updated

Event topic: clonesahibinden-listing-service-dbevent-sys_paymentcustomer-updated

Activation of this event follows the update of a sys_paymentCustomer data object. The payload contains the updated information under the sys_paymentCustomer attribute, along with the original data prior to update, labeled as old_sys_paymentCustomer and also you can find the old and new versions of updated-only portion of the data…

Event payload:

{
old_sys_paymentCustomer:{"id":"ID","userId":"ID","customerId":"String","platform":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},
sys_paymentCustomer:{"id":"ID","userId":"ID","customerId":"String","platform":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},
oldDataValues,
newDataValues
}

DbEvent sys_paymentCustomer-deleted

Event topic: clonesahibinden-listing-service-dbevent-sys_paymentcustomer-deleted

This event announces the deletion of a sys_paymentCustomer 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","customerId":"String","platform":"String","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

DbEvent sys_paymentMethod-created

Event topic: clonesahibinden-listing-service-dbevent-sys_paymentmethod-created

This event is triggered upon the creation of a sys_paymentMethod data object in the database. The event payload encompasses the newly created data, encapsulated within the root of the paylod.

Event payload:

{"id":"ID","paymentMethodId":"String","userId":"ID","customerId":"String","cardHolderName":"String","cardHolderZip":"String","platform":"String","cardInfo":"Object","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

DbEvent sys_paymentMethod-updated

Event topic: clonesahibinden-listing-service-dbevent-sys_paymentmethod-updated

Activation of this event follows the update of a sys_paymentMethod data object. The payload contains the updated information under the sys_paymentMethod attribute, along with the original data prior to update, labeled as old_sys_paymentMethod and also you can find the old and new versions of updated-only portion of the data…

Event payload:

{
old_sys_paymentMethod:{"id":"ID","paymentMethodId":"String","userId":"ID","customerId":"String","cardHolderName":"String","cardHolderZip":"String","platform":"String","cardInfo":"Object","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},
sys_paymentMethod:{"id":"ID","paymentMethodId":"String","userId":"ID","customerId":"String","cardHolderName":"String","cardHolderZip":"String","platform":"String","cardInfo":"Object","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},
oldDataValues,
newDataValues
}

DbEvent sys_paymentMethod-deleted

Event topic: clonesahibinden-listing-service-dbevent-sys_paymentmethod-deleted

This event announces the deletion of a sys_paymentMethod 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","paymentMethodId":"String","userId":"ID","customerId":"String","cardHolderName":"String","cardHolderZip":"String","platform":"String","cardInfo":"Object","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

ElasticSearch Index Events

Within the Listing 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 listing-created

Event topic: elastic-index-clonesahibinden_listing-created

Event payload:

{"id":"ID","attributes":"Object","categoryId":"ID","condition":"Enum","condition_idx":"Integer","contactEmail":"String","contactPhone":"String","currency":"String","description":"Text","expiresAt":"Date","favoriteCount":"Integer","isPremium":"Boolean","listingType":"Enum","listingType_idx":"Integer","locationId":"ID","_paymentConfirmation":"String","premiumExpiry":"Date","premiumType":"Enum","premiumType_idx":"Integer","price":"Double","status":"Enum","status_idx":"Integer","subcategoryId":"ID","title":"String","userId":"ID","viewsCount":"Integer","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event listing-updated

Event topic: elastic-index-clonesahibinden_listing-created

Event payload:

{"id":"ID","attributes":"Object","categoryId":"ID","condition":"Enum","condition_idx":"Integer","contactEmail":"String","contactPhone":"String","currency":"String","description":"Text","expiresAt":"Date","favoriteCount":"Integer","isPremium":"Boolean","listingType":"Enum","listingType_idx":"Integer","locationId":"ID","_paymentConfirmation":"String","premiumExpiry":"Date","premiumType":"Enum","premiumType_idx":"Integer","price":"Double","status":"Enum","status_idx":"Integer","subcategoryId":"ID","title":"String","userId":"ID","viewsCount":"Integer","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event listing-deleted

Event topic: elastic-index-clonesahibinden_listing-deleted

Event payload:

{"id":"ID","attributes":"Object","categoryId":"ID","condition":"Enum","condition_idx":"Integer","contactEmail":"String","contactPhone":"String","currency":"String","description":"Text","expiresAt":"Date","favoriteCount":"Integer","isPremium":"Boolean","listingType":"Enum","listingType_idx":"Integer","locationId":"ID","_paymentConfirmation":"String","premiumExpiry":"Date","premiumType":"Enum","premiumType_idx":"Integer","price":"Double","status":"Enum","status_idx":"Integer","subcategoryId":"ID","title":"String","userId":"ID","viewsCount":"Integer","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event listing-extended

Event topic: elastic-index-clonesahibinden_listing-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 listing-created

Event topic : clonesahibinden-listing-service-listing-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 listing data object itself.

The following JSON included in the payload illustrates the fullest representation of the listing 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":"listing","method":"POST","action":"create","appVersion":"Version","rowCount":1,"listing":{"id":"ID","attributes":"Object","categoryId":"ID","condition":"Enum","condition_idx":"Integer","contactEmail":"String","contactPhone":"String","currency":"String","description":"Text","expiresAt":"Date","favoriteCount":"Integer","isPremium":"Boolean","listingType":"Enum","listingType_idx":"Integer","locationId":"ID","_paymentConfirmation":"String","premiumExpiry":"Date","premiumType":"Enum","premiumType_idx":"Integer","price":"Double","status":"Enum","status_idx":"Integer","subcategoryId":"ID","title":"String","userId":"ID","viewsCount":"Integer","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event listing-deleted

Event topic : clonesahibinden-listing-service-listing-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 listing data object itself.

The following JSON included in the payload illustrates the fullest representation of the listing 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":"listing","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"listing":{"id":"ID","attributes":"Object","categoryId":"ID","condition":"Enum","condition_idx":"Integer","contactEmail":"String","contactPhone":"String","currency":"String","description":"Text","expiresAt":"Date","favoriteCount":"Integer","isPremium":"Boolean","listingType":"Enum","listingType_idx":"Integer","locationId":"ID","_paymentConfirmation":"String","premiumExpiry":"Date","premiumType":"Enum","premiumType_idx":"Integer","price":"Double","status":"Enum","status_idx":"Integer","subcategoryId":"ID","title":"String","userId":"ID","viewsCount":"Integer","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event listing-retrived

Event topic : clonesahibinden-listing-service-listing-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 listing data object itself.

The following JSON included in the payload illustrates the fullest representation of the listing 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":"listing","method":"GET","action":"get","appVersion":"Version","rowCount":1,"listing":{"user":{"fullname":"String","avatar":"String","roleId":"String"},"category":{"name":"String","parentCategoryId":"ID","slug":"String"},"subcategory":{"name":"String","parentCategoryId":"ID","slug":"String"},"location":{"city":"String","country":"String","district":"String"},"isActive":true}}

Route Event listings-listed

Event topic : clonesahibinden-listing-service-listings-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 listings data object itself.

The following JSON included in the payload illustrates the fullest representation of the listings 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":"listings","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","listings":[{"user":[{"fullname":"String","avatar":"String"},{},{}],"category":[{"name":"String"},{},{}],"subcategory":[{"name":"String"},{},{}],"location":[{"city":"String","district":"String"},{},{}],"isActive":true},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]}

Route Event listing-updated

Event topic : clonesahibinden-listing-service-listing-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 listing data object itself.

The following JSON included in the payload illustrates the fullest representation of the listing 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":"listing","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"listing":{"id":"ID","attributes":"Object","categoryId":"ID","condition":"Enum","condition_idx":"Integer","contactEmail":"String","contactPhone":"String","currency":"String","description":"Text","expiresAt":"Date","favoriteCount":"Integer","isPremium":"Boolean","listingType":"Enum","listingType_idx":"Integer","locationId":"ID","_paymentConfirmation":"String","premiumExpiry":"Date","premiumType":"Enum","premiumType_idx":"Integer","price":"Double","status":"Enum","status_idx":"Integer","subcategoryId":"ID","title":"String","userId":"ID","viewsCount":"Integer","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event listingpremium-upgraded

Event topic : clonesahibinden-listing-service-listingpremium-upgraded

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 listing data object itself.

The following JSON included in the payload illustrates the fullest representation of the listing 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":"listing","method":"POST","action":"update","appVersion":"Version","rowCount":1,"listing":{"id":"ID","attributes":"Object","categoryId":"ID","condition":"Enum","condition_idx":"Integer","contactEmail":"String","contactPhone":"String","currency":"String","description":"Text","expiresAt":"Date","favoriteCount":"Integer","isPremium":"Boolean","listingType":"Enum","listingType_idx":"Integer","locationId":"ID","_paymentConfirmation":"String","premiumExpiry":"Date","premiumType":"Enum","premiumType_idx":"Integer","price":"Double","status":"Enum","status_idx":"Integer","subcategoryId":"ID","title":"String","userId":"ID","viewsCount":"Integer","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event listingpayment-retrived

Event topic : clonesahibinden-listing-service-listingpayment-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_listingPayment data object itself.

The following JSON included in the payload illustrates the fullest representation of the sys_listingPayment 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_listingPayment","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_listingPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event listingpayments-listed

Event topic : clonesahibinden-listing-service-listingpayments-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_listingPayments data object itself.

The following JSON included in the payload illustrates the fullest representation of the sys_listingPayments 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_listingPayments","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_listingPayments":[{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]}

Route Event listingpayment-created

Event topic : clonesahibinden-listing-service-listingpayment-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_listingPayment data object itself.

The following JSON included in the payload illustrates the fullest representation of the sys_listingPayment 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_listingPayment","method":"POST","action":"create","appVersion":"Version","rowCount":1,"sys_listingPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event listingpayment-updated

Event topic : clonesahibinden-listing-service-listingpayment-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_listingPayment data object itself.

The following JSON included in the payload illustrates the fullest representation of the sys_listingPayment 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_listingPayment","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"sys_listingPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event listingpayment-deleted

Event topic : clonesahibinden-listing-service-listingpayment-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_listingPayment data object itself.

The following JSON included in the payload illustrates the fullest representation of the sys_listingPayment 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_listingPayment","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"sys_listingPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event listingpaymentbyorderid-retrived

Event topic : clonesahibinden-listing-service-listingpaymentbyorderid-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_listingPayment data object itself.

The following JSON included in the payload illustrates the fullest representation of the sys_listingPayment 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_listingPayment","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_listingPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event listingpaymentbypaymentid-retrived

Event topic : clonesahibinden-listing-service-listingpaymentbypaymentid-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_listingPayment data object itself.

The following JSON included in the payload illustrates the fullest representation of the sys_listingPayment 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_listingPayment","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_listingPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event listingpayment-started

Event topic : clonesahibinden-listing-service-listingpayment-started

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 listing data object itself.

The following JSON included in the payload illustrates the fullest representation of the listing 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":"listing","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"listing":{"id":"ID","attributes":"Object","categoryId":"ID","condition":"Enum","condition_idx":"Integer","contactEmail":"String","contactPhone":"String","currency":"String","description":"Text","expiresAt":"Date","favoriteCount":"Integer","isPremium":"Boolean","listingType":"Enum","listingType_idx":"Integer","locationId":"ID","_paymentConfirmation":"String","premiumExpiry":"Date","premiumType":"Enum","premiumType_idx":"Integer","price":"Double","status":"Enum","status_idx":"Integer","subcategoryId":"ID","title":"String","userId":"ID","viewsCount":"Integer","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"paymentResult":{"paymentTicketId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"Enum","paymentIntentInfo":"Object","statusLiteral":"String","amount":"Double","currency":"String","success":true,"description":"String","metadata":"Object","paymentUserParams":"Object"}}

Route Event listingpayment-refreshed

Event topic : clonesahibinden-listing-service-listingpayment-refreshed

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 listing data object itself.

The following JSON included in the payload illustrates the fullest representation of the listing 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":"listing","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"listing":{"id":"ID","attributes":"Object","categoryId":"ID","condition":"Enum","condition_idx":"Integer","contactEmail":"String","contactPhone":"String","currency":"String","description":"Text","expiresAt":"Date","favoriteCount":"Integer","isPremium":"Boolean","listingType":"Enum","listingType_idx":"Integer","locationId":"ID","_paymentConfirmation":"String","premiumExpiry":"Date","premiumType":"Enum","premiumType_idx":"Integer","price":"Double","status":"Enum","status_idx":"Integer","subcategoryId":"ID","title":"String","userId":"ID","viewsCount":"Integer","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"paymentResult":{"paymentTicketId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"Enum","paymentIntentInfo":"Object","statusLiteral":"String","amount":"Double","currency":"String","success":true,"description":"String","metadata":"Object","paymentUserParams":"Object"}}

Route Event listingpayment-calledback

Event topic : clonesahibinden-listing-service-listingpayment-calledback

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 listing data object itself.

The following JSON included in the payload illustrates the fullest representation of the listing 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":"listing","method":"POST","action":"update","appVersion":"Version","rowCount":1,"listing":{"id":"ID","attributes":"Object","categoryId":"ID","condition":"Enum","condition_idx":"Integer","contactEmail":"String","contactPhone":"String","currency":"String","description":"Text","expiresAt":"Date","favoriteCount":"Integer","isPremium":"Boolean","listingType":"Enum","listingType_idx":"Integer","locationId":"ID","_paymentConfirmation":"String","premiumExpiry":"Date","premiumType":"Enum","premiumType_idx":"Integer","price":"Double","status":"Enum","status_idx":"Integer","subcategoryId":"ID","title":"String","userId":"ID","viewsCount":"Integer","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"paymentResult":{"paymentTicketId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"Enum","paymentIntentInfo":"Object","statusLiteral":"String","amount":"Double","currency":"String","success":true,"description":"String","metadata":"Object","paymentUserParams":"Object"}}

Route Event paymentcustomerbyuserid-retrived

Event topic : clonesahibinden-listing-service-paymentcustomerbyuserid-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_paymentCustomer data object itself.

The following JSON included in the payload illustrates the fullest representation of the sys_paymentCustomer 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_paymentCustomer","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_paymentCustomer":{"id":"ID","userId":"ID","customerId":"String","platform":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event paymentcustomers-listed

Event topic : clonesahibinden-listing-service-paymentcustomers-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_paymentCustomers data object itself.

The following JSON included in the payload illustrates the fullest representation of the sys_paymentCustomers 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_paymentCustomers","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_paymentCustomers":[{"id":"ID","userId":"ID","customerId":"String","platform":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]}

Route Event paymentcustomermethods-listed

Event topic : clonesahibinden-listing-service-paymentcustomermethods-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_paymentMethods data object itself.

The following JSON included in the payload illustrates the fullest representation of the sys_paymentMethods 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_paymentMethods","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_paymentMethods":[{"id":"ID","paymentMethodId":"String","userId":"ID","customerId":"String","cardHolderName":"String","cardHolderZip":"String","platform":"String","cardInfo":"Object","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]}

Index Event sys_listingpayment-created

Event topic: elastic-index-clonesahibinden_sys_listingpayment-created

Event payload:

{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event sys_listingpayment-updated

Event topic: elastic-index-clonesahibinden_sys_listingpayment-created

Event payload:

{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event sys_listingpayment-deleted

Event topic: elastic-index-clonesahibinden_sys_listingpayment-deleted

Event payload:

{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event sys_listingpayment-extended

Event topic: elastic-index-clonesahibinden_sys_listingpayment-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 listing-created

Event topic : clonesahibinden-listing-service-listing-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 listing data object itself.

The following JSON included in the payload illustrates the fullest representation of the listing 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":"listing","method":"POST","action":"create","appVersion":"Version","rowCount":1,"listing":{"id":"ID","attributes":"Object","categoryId":"ID","condition":"Enum","condition_idx":"Integer","contactEmail":"String","contactPhone":"String","currency":"String","description":"Text","expiresAt":"Date","favoriteCount":"Integer","isPremium":"Boolean","listingType":"Enum","listingType_idx":"Integer","locationId":"ID","_paymentConfirmation":"String","premiumExpiry":"Date","premiumType":"Enum","premiumType_idx":"Integer","price":"Double","status":"Enum","status_idx":"Integer","subcategoryId":"ID","title":"String","userId":"ID","viewsCount":"Integer","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event listing-deleted

Event topic : clonesahibinden-listing-service-listing-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 listing data object itself.

The following JSON included in the payload illustrates the fullest representation of the listing 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":"listing","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"listing":{"id":"ID","attributes":"Object","categoryId":"ID","condition":"Enum","condition_idx":"Integer","contactEmail":"String","contactPhone":"String","currency":"String","description":"Text","expiresAt":"Date","favoriteCount":"Integer","isPremium":"Boolean","listingType":"Enum","listingType_idx":"Integer","locationId":"ID","_paymentConfirmation":"String","premiumExpiry":"Date","premiumType":"Enum","premiumType_idx":"Integer","price":"Double","status":"Enum","status_idx":"Integer","subcategoryId":"ID","title":"String","userId":"ID","viewsCount":"Integer","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event listing-retrived

Event topic : clonesahibinden-listing-service-listing-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 listing data object itself.

The following JSON included in the payload illustrates the fullest representation of the listing 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":"listing","method":"GET","action":"get","appVersion":"Version","rowCount":1,"listing":{"user":{"fullname":"String","avatar":"String","roleId":"String"},"category":{"name":"String","parentCategoryId":"ID","slug":"String"},"subcategory":{"name":"String","parentCategoryId":"ID","slug":"String"},"location":{"city":"String","country":"String","district":"String"},"isActive":true}}

Route Event listings-listed

Event topic : clonesahibinden-listing-service-listings-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 listings data object itself.

The following JSON included in the payload illustrates the fullest representation of the listings 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":"listings","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","listings":[{"user":[{"fullname":"String","avatar":"String"},{},{}],"category":[{"name":"String"},{},{}],"subcategory":[{"name":"String"},{},{}],"location":[{"city":"String","district":"String"},{},{}],"isActive":true},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]}

Route Event listing-updated

Event topic : clonesahibinden-listing-service-listing-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 listing data object itself.

The following JSON included in the payload illustrates the fullest representation of the listing 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":"listing","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"listing":{"id":"ID","attributes":"Object","categoryId":"ID","condition":"Enum","condition_idx":"Integer","contactEmail":"String","contactPhone":"String","currency":"String","description":"Text","expiresAt":"Date","favoriteCount":"Integer","isPremium":"Boolean","listingType":"Enum","listingType_idx":"Integer","locationId":"ID","_paymentConfirmation":"String","premiumExpiry":"Date","premiumType":"Enum","premiumType_idx":"Integer","price":"Double","status":"Enum","status_idx":"Integer","subcategoryId":"ID","title":"String","userId":"ID","viewsCount":"Integer","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event listingpremium-upgraded

Event topic : clonesahibinden-listing-service-listingpremium-upgraded

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 listing data object itself.

The following JSON included in the payload illustrates the fullest representation of the listing 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":"listing","method":"POST","action":"update","appVersion":"Version","rowCount":1,"listing":{"id":"ID","attributes":"Object","categoryId":"ID","condition":"Enum","condition_idx":"Integer","contactEmail":"String","contactPhone":"String","currency":"String","description":"Text","expiresAt":"Date","favoriteCount":"Integer","isPremium":"Boolean","listingType":"Enum","listingType_idx":"Integer","locationId":"ID","_paymentConfirmation":"String","premiumExpiry":"Date","premiumType":"Enum","premiumType_idx":"Integer","price":"Double","status":"Enum","status_idx":"Integer","subcategoryId":"ID","title":"String","userId":"ID","viewsCount":"Integer","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event listingpayment-retrived

Event topic : clonesahibinden-listing-service-listingpayment-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_listingPayment data object itself.

The following JSON included in the payload illustrates the fullest representation of the sys_listingPayment 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_listingPayment","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_listingPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event listingpayments-listed

Event topic : clonesahibinden-listing-service-listingpayments-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_listingPayments data object itself.

The following JSON included in the payload illustrates the fullest representation of the sys_listingPayments 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_listingPayments","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_listingPayments":[{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]}

Route Event listingpayment-created

Event topic : clonesahibinden-listing-service-listingpayment-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_listingPayment data object itself.

The following JSON included in the payload illustrates the fullest representation of the sys_listingPayment 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_listingPayment","method":"POST","action":"create","appVersion":"Version","rowCount":1,"sys_listingPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event listingpayment-updated

Event topic : clonesahibinden-listing-service-listingpayment-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_listingPayment data object itself.

The following JSON included in the payload illustrates the fullest representation of the sys_listingPayment 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_listingPayment","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"sys_listingPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event listingpayment-deleted

Event topic : clonesahibinden-listing-service-listingpayment-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_listingPayment data object itself.

The following JSON included in the payload illustrates the fullest representation of the sys_listingPayment 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_listingPayment","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"sys_listingPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event listingpaymentbyorderid-retrived

Event topic : clonesahibinden-listing-service-listingpaymentbyorderid-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_listingPayment data object itself.

The following JSON included in the payload illustrates the fullest representation of the sys_listingPayment 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_listingPayment","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_listingPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event listingpaymentbypaymentid-retrived

Event topic : clonesahibinden-listing-service-listingpaymentbypaymentid-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_listingPayment data object itself.

The following JSON included in the payload illustrates the fullest representation of the sys_listingPayment 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_listingPayment","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_listingPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event listingpayment-started

Event topic : clonesahibinden-listing-service-listingpayment-started

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 listing data object itself.

The following JSON included in the payload illustrates the fullest representation of the listing 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":"listing","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"listing":{"id":"ID","attributes":"Object","categoryId":"ID","condition":"Enum","condition_idx":"Integer","contactEmail":"String","contactPhone":"String","currency":"String","description":"Text","expiresAt":"Date","favoriteCount":"Integer","isPremium":"Boolean","listingType":"Enum","listingType_idx":"Integer","locationId":"ID","_paymentConfirmation":"String","premiumExpiry":"Date","premiumType":"Enum","premiumType_idx":"Integer","price":"Double","status":"Enum","status_idx":"Integer","subcategoryId":"ID","title":"String","userId":"ID","viewsCount":"Integer","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"paymentResult":{"paymentTicketId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"Enum","paymentIntentInfo":"Object","statusLiteral":"String","amount":"Double","currency":"String","success":true,"description":"String","metadata":"Object","paymentUserParams":"Object"}}

Route Event listingpayment-refreshed

Event topic : clonesahibinden-listing-service-listingpayment-refreshed

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 listing data object itself.

The following JSON included in the payload illustrates the fullest representation of the listing 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":"listing","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"listing":{"id":"ID","attributes":"Object","categoryId":"ID","condition":"Enum","condition_idx":"Integer","contactEmail":"String","contactPhone":"String","currency":"String","description":"Text","expiresAt":"Date","favoriteCount":"Integer","isPremium":"Boolean","listingType":"Enum","listingType_idx":"Integer","locationId":"ID","_paymentConfirmation":"String","premiumExpiry":"Date","premiumType":"Enum","premiumType_idx":"Integer","price":"Double","status":"Enum","status_idx":"Integer","subcategoryId":"ID","title":"String","userId":"ID","viewsCount":"Integer","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"paymentResult":{"paymentTicketId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"Enum","paymentIntentInfo":"Object","statusLiteral":"String","amount":"Double","currency":"String","success":true,"description":"String","metadata":"Object","paymentUserParams":"Object"}}

Route Event listingpayment-calledback

Event topic : clonesahibinden-listing-service-listingpayment-calledback

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 listing data object itself.

The following JSON included in the payload illustrates the fullest representation of the listing 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":"listing","method":"POST","action":"update","appVersion":"Version","rowCount":1,"listing":{"id":"ID","attributes":"Object","categoryId":"ID","condition":"Enum","condition_idx":"Integer","contactEmail":"String","contactPhone":"String","currency":"String","description":"Text","expiresAt":"Date","favoriteCount":"Integer","isPremium":"Boolean","listingType":"Enum","listingType_idx":"Integer","locationId":"ID","_paymentConfirmation":"String","premiumExpiry":"Date","premiumType":"Enum","premiumType_idx":"Integer","price":"Double","status":"Enum","status_idx":"Integer","subcategoryId":"ID","title":"String","userId":"ID","viewsCount":"Integer","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"paymentResult":{"paymentTicketId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"Enum","paymentIntentInfo":"Object","statusLiteral":"String","amount":"Double","currency":"String","success":true,"description":"String","metadata":"Object","paymentUserParams":"Object"}}

Route Event paymentcustomerbyuserid-retrived

Event topic : clonesahibinden-listing-service-paymentcustomerbyuserid-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_paymentCustomer data object itself.

The following JSON included in the payload illustrates the fullest representation of the sys_paymentCustomer 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_paymentCustomer","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_paymentCustomer":{"id":"ID","userId":"ID","customerId":"String","platform":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event paymentcustomers-listed

Event topic : clonesahibinden-listing-service-paymentcustomers-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_paymentCustomers data object itself.

The following JSON included in the payload illustrates the fullest representation of the sys_paymentCustomers 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_paymentCustomers","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_paymentCustomers":[{"id":"ID","userId":"ID","customerId":"String","platform":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]}

Route Event paymentcustomermethods-listed

Event topic : clonesahibinden-listing-service-paymentcustomermethods-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_paymentMethods data object itself.

The following JSON included in the payload illustrates the fullest representation of the sys_paymentMethods 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_paymentMethods","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_paymentMethods":[{"id":"ID","paymentMethodId":"String","userId":"ID","customerId":"String","cardHolderName":"String","cardHolderZip":"String","platform":"String","cardInfo":"Object","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]}

Index Event sys_paymentcustomer-created

Event topic: elastic-index-clonesahibinden_sys_paymentcustomer-created

Event payload:

{"id":"ID","userId":"ID","customerId":"String","platform":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event sys_paymentcustomer-updated

Event topic: elastic-index-clonesahibinden_sys_paymentcustomer-created

Event payload:

{"id":"ID","userId":"ID","customerId":"String","platform":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event sys_paymentcustomer-deleted

Event topic: elastic-index-clonesahibinden_sys_paymentcustomer-deleted

Event payload:

{"id":"ID","userId":"ID","customerId":"String","platform":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event sys_paymentcustomer-extended

Event topic: elastic-index-clonesahibinden_sys_paymentcustomer-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 listing-created

Event topic : clonesahibinden-listing-service-listing-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 listing data object itself.

The following JSON included in the payload illustrates the fullest representation of the listing 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":"listing","method":"POST","action":"create","appVersion":"Version","rowCount":1,"listing":{"id":"ID","attributes":"Object","categoryId":"ID","condition":"Enum","condition_idx":"Integer","contactEmail":"String","contactPhone":"String","currency":"String","description":"Text","expiresAt":"Date","favoriteCount":"Integer","isPremium":"Boolean","listingType":"Enum","listingType_idx":"Integer","locationId":"ID","_paymentConfirmation":"String","premiumExpiry":"Date","premiumType":"Enum","premiumType_idx":"Integer","price":"Double","status":"Enum","status_idx":"Integer","subcategoryId":"ID","title":"String","userId":"ID","viewsCount":"Integer","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event listing-deleted

Event topic : clonesahibinden-listing-service-listing-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 listing data object itself.

The following JSON included in the payload illustrates the fullest representation of the listing 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":"listing","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"listing":{"id":"ID","attributes":"Object","categoryId":"ID","condition":"Enum","condition_idx":"Integer","contactEmail":"String","contactPhone":"String","currency":"String","description":"Text","expiresAt":"Date","favoriteCount":"Integer","isPremium":"Boolean","listingType":"Enum","listingType_idx":"Integer","locationId":"ID","_paymentConfirmation":"String","premiumExpiry":"Date","premiumType":"Enum","premiumType_idx":"Integer","price":"Double","status":"Enum","status_idx":"Integer","subcategoryId":"ID","title":"String","userId":"ID","viewsCount":"Integer","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event listing-retrived

Event topic : clonesahibinden-listing-service-listing-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 listing data object itself.

The following JSON included in the payload illustrates the fullest representation of the listing 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":"listing","method":"GET","action":"get","appVersion":"Version","rowCount":1,"listing":{"user":{"fullname":"String","avatar":"String","roleId":"String"},"category":{"name":"String","parentCategoryId":"ID","slug":"String"},"subcategory":{"name":"String","parentCategoryId":"ID","slug":"String"},"location":{"city":"String","country":"String","district":"String"},"isActive":true}}

Route Event listings-listed

Event topic : clonesahibinden-listing-service-listings-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 listings data object itself.

The following JSON included in the payload illustrates the fullest representation of the listings 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":"listings","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","listings":[{"user":[{"fullname":"String","avatar":"String"},{},{}],"category":[{"name":"String"},{},{}],"subcategory":[{"name":"String"},{},{}],"location":[{"city":"String","district":"String"},{},{}],"isActive":true},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]}

Route Event listing-updated

Event topic : clonesahibinden-listing-service-listing-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 listing data object itself.

The following JSON included in the payload illustrates the fullest representation of the listing 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":"listing","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"listing":{"id":"ID","attributes":"Object","categoryId":"ID","condition":"Enum","condition_idx":"Integer","contactEmail":"String","contactPhone":"String","currency":"String","description":"Text","expiresAt":"Date","favoriteCount":"Integer","isPremium":"Boolean","listingType":"Enum","listingType_idx":"Integer","locationId":"ID","_paymentConfirmation":"String","premiumExpiry":"Date","premiumType":"Enum","premiumType_idx":"Integer","price":"Double","status":"Enum","status_idx":"Integer","subcategoryId":"ID","title":"String","userId":"ID","viewsCount":"Integer","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event listingpremium-upgraded

Event topic : clonesahibinden-listing-service-listingpremium-upgraded

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 listing data object itself.

The following JSON included in the payload illustrates the fullest representation of the listing 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":"listing","method":"POST","action":"update","appVersion":"Version","rowCount":1,"listing":{"id":"ID","attributes":"Object","categoryId":"ID","condition":"Enum","condition_idx":"Integer","contactEmail":"String","contactPhone":"String","currency":"String","description":"Text","expiresAt":"Date","favoriteCount":"Integer","isPremium":"Boolean","listingType":"Enum","listingType_idx":"Integer","locationId":"ID","_paymentConfirmation":"String","premiumExpiry":"Date","premiumType":"Enum","premiumType_idx":"Integer","price":"Double","status":"Enum","status_idx":"Integer","subcategoryId":"ID","title":"String","userId":"ID","viewsCount":"Integer","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event listingpayment-retrived

Event topic : clonesahibinden-listing-service-listingpayment-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_listingPayment data object itself.

The following JSON included in the payload illustrates the fullest representation of the sys_listingPayment 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_listingPayment","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_listingPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event listingpayments-listed

Event topic : clonesahibinden-listing-service-listingpayments-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_listingPayments data object itself.

The following JSON included in the payload illustrates the fullest representation of the sys_listingPayments 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_listingPayments","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_listingPayments":[{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]}

Route Event listingpayment-created

Event topic : clonesahibinden-listing-service-listingpayment-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_listingPayment data object itself.

The following JSON included in the payload illustrates the fullest representation of the sys_listingPayment 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_listingPayment","method":"POST","action":"create","appVersion":"Version","rowCount":1,"sys_listingPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event listingpayment-updated

Event topic : clonesahibinden-listing-service-listingpayment-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_listingPayment data object itself.

The following JSON included in the payload illustrates the fullest representation of the sys_listingPayment 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_listingPayment","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"sys_listingPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event listingpayment-deleted

Event topic : clonesahibinden-listing-service-listingpayment-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_listingPayment data object itself.

The following JSON included in the payload illustrates the fullest representation of the sys_listingPayment 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_listingPayment","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"sys_listingPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event listingpaymentbyorderid-retrived

Event topic : clonesahibinden-listing-service-listingpaymentbyorderid-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_listingPayment data object itself.

The following JSON included in the payload illustrates the fullest representation of the sys_listingPayment 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_listingPayment","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_listingPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event listingpaymentbypaymentid-retrived

Event topic : clonesahibinden-listing-service-listingpaymentbypaymentid-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_listingPayment data object itself.

The following JSON included in the payload illustrates the fullest representation of the sys_listingPayment 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_listingPayment","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_listingPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event listingpayment-started

Event topic : clonesahibinden-listing-service-listingpayment-started

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 listing data object itself.

The following JSON included in the payload illustrates the fullest representation of the listing 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":"listing","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"listing":{"id":"ID","attributes":"Object","categoryId":"ID","condition":"Enum","condition_idx":"Integer","contactEmail":"String","contactPhone":"String","currency":"String","description":"Text","expiresAt":"Date","favoriteCount":"Integer","isPremium":"Boolean","listingType":"Enum","listingType_idx":"Integer","locationId":"ID","_paymentConfirmation":"String","premiumExpiry":"Date","premiumType":"Enum","premiumType_idx":"Integer","price":"Double","status":"Enum","status_idx":"Integer","subcategoryId":"ID","title":"String","userId":"ID","viewsCount":"Integer","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"paymentResult":{"paymentTicketId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"Enum","paymentIntentInfo":"Object","statusLiteral":"String","amount":"Double","currency":"String","success":true,"description":"String","metadata":"Object","paymentUserParams":"Object"}}

Route Event listingpayment-refreshed

Event topic : clonesahibinden-listing-service-listingpayment-refreshed

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 listing data object itself.

The following JSON included in the payload illustrates the fullest representation of the listing 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":"listing","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"listing":{"id":"ID","attributes":"Object","categoryId":"ID","condition":"Enum","condition_idx":"Integer","contactEmail":"String","contactPhone":"String","currency":"String","description":"Text","expiresAt":"Date","favoriteCount":"Integer","isPremium":"Boolean","listingType":"Enum","listingType_idx":"Integer","locationId":"ID","_paymentConfirmation":"String","premiumExpiry":"Date","premiumType":"Enum","premiumType_idx":"Integer","price":"Double","status":"Enum","status_idx":"Integer","subcategoryId":"ID","title":"String","userId":"ID","viewsCount":"Integer","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"paymentResult":{"paymentTicketId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"Enum","paymentIntentInfo":"Object","statusLiteral":"String","amount":"Double","currency":"String","success":true,"description":"String","metadata":"Object","paymentUserParams":"Object"}}

Route Event listingpayment-calledback

Event topic : clonesahibinden-listing-service-listingpayment-calledback

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 listing data object itself.

The following JSON included in the payload illustrates the fullest representation of the listing 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":"listing","method":"POST","action":"update","appVersion":"Version","rowCount":1,"listing":{"id":"ID","attributes":"Object","categoryId":"ID","condition":"Enum","condition_idx":"Integer","contactEmail":"String","contactPhone":"String","currency":"String","description":"Text","expiresAt":"Date","favoriteCount":"Integer","isPremium":"Boolean","listingType":"Enum","listingType_idx":"Integer","locationId":"ID","_paymentConfirmation":"String","premiumExpiry":"Date","premiumType":"Enum","premiumType_idx":"Integer","price":"Double","status":"Enum","status_idx":"Integer","subcategoryId":"ID","title":"String","userId":"ID","viewsCount":"Integer","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"paymentResult":{"paymentTicketId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"Enum","paymentIntentInfo":"Object","statusLiteral":"String","amount":"Double","currency":"String","success":true,"description":"String","metadata":"Object","paymentUserParams":"Object"}}

Route Event paymentcustomerbyuserid-retrived

Event topic : clonesahibinden-listing-service-paymentcustomerbyuserid-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_paymentCustomer data object itself.

The following JSON included in the payload illustrates the fullest representation of the sys_paymentCustomer 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_paymentCustomer","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_paymentCustomer":{"id":"ID","userId":"ID","customerId":"String","platform":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event paymentcustomers-listed

Event topic : clonesahibinden-listing-service-paymentcustomers-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_paymentCustomers data object itself.

The following JSON included in the payload illustrates the fullest representation of the sys_paymentCustomers 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_paymentCustomers","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_paymentCustomers":[{"id":"ID","userId":"ID","customerId":"String","platform":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]}

Route Event paymentcustomermethods-listed

Event topic : clonesahibinden-listing-service-paymentcustomermethods-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_paymentMethods data object itself.

The following JSON included in the payload illustrates the fullest representation of the sys_paymentMethods 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_paymentMethods","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_paymentMethods":[{"id":"ID","paymentMethodId":"String","userId":"ID","customerId":"String","cardHolderName":"String","cardHolderZip":"String","platform":"String","cardInfo":"Object","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]}

Index Event sys_paymentmethod-created

Event topic: elastic-index-clonesahibinden_sys_paymentmethod-created

Event payload:

{"id":"ID","paymentMethodId":"String","userId":"ID","customerId":"String","cardHolderName":"String","cardHolderZip":"String","platform":"String","cardInfo":"Object","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event sys_paymentmethod-updated

Event topic: elastic-index-clonesahibinden_sys_paymentmethod-created

Event payload:

{"id":"ID","paymentMethodId":"String","userId":"ID","customerId":"String","cardHolderName":"String","cardHolderZip":"String","platform":"String","cardInfo":"Object","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event sys_paymentmethod-deleted

Event topic: elastic-index-clonesahibinden_sys_paymentmethod-deleted

Event payload:

{"id":"ID","paymentMethodId":"String","userId":"ID","customerId":"String","cardHolderName":"String","cardHolderZip":"String","platform":"String","cardInfo":"Object","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event sys_paymentmethod-extended

Event topic: elastic-index-clonesahibinden_sys_paymentmethod-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 listing-created

Event topic : clonesahibinden-listing-service-listing-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 listing data object itself.

The following JSON included in the payload illustrates the fullest representation of the listing 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":"listing","method":"POST","action":"create","appVersion":"Version","rowCount":1,"listing":{"id":"ID","attributes":"Object","categoryId":"ID","condition":"Enum","condition_idx":"Integer","contactEmail":"String","contactPhone":"String","currency":"String","description":"Text","expiresAt":"Date","favoriteCount":"Integer","isPremium":"Boolean","listingType":"Enum","listingType_idx":"Integer","locationId":"ID","_paymentConfirmation":"String","premiumExpiry":"Date","premiumType":"Enum","premiumType_idx":"Integer","price":"Double","status":"Enum","status_idx":"Integer","subcategoryId":"ID","title":"String","userId":"ID","viewsCount":"Integer","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event listing-deleted

Event topic : clonesahibinden-listing-service-listing-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 listing data object itself.

The following JSON included in the payload illustrates the fullest representation of the listing 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":"listing","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"listing":{"id":"ID","attributes":"Object","categoryId":"ID","condition":"Enum","condition_idx":"Integer","contactEmail":"String","contactPhone":"String","currency":"String","description":"Text","expiresAt":"Date","favoriteCount":"Integer","isPremium":"Boolean","listingType":"Enum","listingType_idx":"Integer","locationId":"ID","_paymentConfirmation":"String","premiumExpiry":"Date","premiumType":"Enum","premiumType_idx":"Integer","price":"Double","status":"Enum","status_idx":"Integer","subcategoryId":"ID","title":"String","userId":"ID","viewsCount":"Integer","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event listing-retrived

Event topic : clonesahibinden-listing-service-listing-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 listing data object itself.

The following JSON included in the payload illustrates the fullest representation of the listing 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":"listing","method":"GET","action":"get","appVersion":"Version","rowCount":1,"listing":{"user":{"fullname":"String","avatar":"String","roleId":"String"},"category":{"name":"String","parentCategoryId":"ID","slug":"String"},"subcategory":{"name":"String","parentCategoryId":"ID","slug":"String"},"location":{"city":"String","country":"String","district":"String"},"isActive":true}}

Route Event listings-listed

Event topic : clonesahibinden-listing-service-listings-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 listings data object itself.

The following JSON included in the payload illustrates the fullest representation of the listings 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":"listings","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","listings":[{"user":[{"fullname":"String","avatar":"String"},{},{}],"category":[{"name":"String"},{},{}],"subcategory":[{"name":"String"},{},{}],"location":[{"city":"String","district":"String"},{},{}],"isActive":true},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]}

Route Event listing-updated

Event topic : clonesahibinden-listing-service-listing-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 listing data object itself.

The following JSON included in the payload illustrates the fullest representation of the listing 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":"listing","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"listing":{"id":"ID","attributes":"Object","categoryId":"ID","condition":"Enum","condition_idx":"Integer","contactEmail":"String","contactPhone":"String","currency":"String","description":"Text","expiresAt":"Date","favoriteCount":"Integer","isPremium":"Boolean","listingType":"Enum","listingType_idx":"Integer","locationId":"ID","_paymentConfirmation":"String","premiumExpiry":"Date","premiumType":"Enum","premiumType_idx":"Integer","price":"Double","status":"Enum","status_idx":"Integer","subcategoryId":"ID","title":"String","userId":"ID","viewsCount":"Integer","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event listingpremium-upgraded

Event topic : clonesahibinden-listing-service-listingpremium-upgraded

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 listing data object itself.

The following JSON included in the payload illustrates the fullest representation of the listing 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":"listing","method":"POST","action":"update","appVersion":"Version","rowCount":1,"listing":{"id":"ID","attributes":"Object","categoryId":"ID","condition":"Enum","condition_idx":"Integer","contactEmail":"String","contactPhone":"String","currency":"String","description":"Text","expiresAt":"Date","favoriteCount":"Integer","isPremium":"Boolean","listingType":"Enum","listingType_idx":"Integer","locationId":"ID","_paymentConfirmation":"String","premiumExpiry":"Date","premiumType":"Enum","premiumType_idx":"Integer","price":"Double","status":"Enum","status_idx":"Integer","subcategoryId":"ID","title":"String","userId":"ID","viewsCount":"Integer","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event listingpayment-retrived

Event topic : clonesahibinden-listing-service-listingpayment-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_listingPayment data object itself.

The following JSON included in the payload illustrates the fullest representation of the sys_listingPayment 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_listingPayment","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_listingPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event listingpayments-listed

Event topic : clonesahibinden-listing-service-listingpayments-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_listingPayments data object itself.

The following JSON included in the payload illustrates the fullest representation of the sys_listingPayments 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_listingPayments","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_listingPayments":[{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]}

Route Event listingpayment-created

Event topic : clonesahibinden-listing-service-listingpayment-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_listingPayment data object itself.

The following JSON included in the payload illustrates the fullest representation of the sys_listingPayment 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_listingPayment","method":"POST","action":"create","appVersion":"Version","rowCount":1,"sys_listingPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event listingpayment-updated

Event topic : clonesahibinden-listing-service-listingpayment-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_listingPayment data object itself.

The following JSON included in the payload illustrates the fullest representation of the sys_listingPayment 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_listingPayment","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"sys_listingPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event listingpayment-deleted

Event topic : clonesahibinden-listing-service-listingpayment-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_listingPayment data object itself.

The following JSON included in the payload illustrates the fullest representation of the sys_listingPayment 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_listingPayment","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"sys_listingPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event listingpaymentbyorderid-retrived

Event topic : clonesahibinden-listing-service-listingpaymentbyorderid-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_listingPayment data object itself.

The following JSON included in the payload illustrates the fullest representation of the sys_listingPayment 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_listingPayment","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_listingPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event listingpaymentbypaymentid-retrived

Event topic : clonesahibinden-listing-service-listingpaymentbypaymentid-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_listingPayment data object itself.

The following JSON included in the payload illustrates the fullest representation of the sys_listingPayment 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_listingPayment","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_listingPayment":{"id":"ID","ownerId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"String","statusLiteral":"String","redirectUrl":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event listingpayment-started

Event topic : clonesahibinden-listing-service-listingpayment-started

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 listing data object itself.

The following JSON included in the payload illustrates the fullest representation of the listing 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":"listing","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"listing":{"id":"ID","attributes":"Object","categoryId":"ID","condition":"Enum","condition_idx":"Integer","contactEmail":"String","contactPhone":"String","currency":"String","description":"Text","expiresAt":"Date","favoriteCount":"Integer","isPremium":"Boolean","listingType":"Enum","listingType_idx":"Integer","locationId":"ID","_paymentConfirmation":"String","premiumExpiry":"Date","premiumType":"Enum","premiumType_idx":"Integer","price":"Double","status":"Enum","status_idx":"Integer","subcategoryId":"ID","title":"String","userId":"ID","viewsCount":"Integer","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"paymentResult":{"paymentTicketId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"Enum","paymentIntentInfo":"Object","statusLiteral":"String","amount":"Double","currency":"String","success":true,"description":"String","metadata":"Object","paymentUserParams":"Object"}}

Route Event listingpayment-refreshed

Event topic : clonesahibinden-listing-service-listingpayment-refreshed

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 listing data object itself.

The following JSON included in the payload illustrates the fullest representation of the listing 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":"listing","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"listing":{"id":"ID","attributes":"Object","categoryId":"ID","condition":"Enum","condition_idx":"Integer","contactEmail":"String","contactPhone":"String","currency":"String","description":"Text","expiresAt":"Date","favoriteCount":"Integer","isPremium":"Boolean","listingType":"Enum","listingType_idx":"Integer","locationId":"ID","_paymentConfirmation":"String","premiumExpiry":"Date","premiumType":"Enum","premiumType_idx":"Integer","price":"Double","status":"Enum","status_idx":"Integer","subcategoryId":"ID","title":"String","userId":"ID","viewsCount":"Integer","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"paymentResult":{"paymentTicketId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"Enum","paymentIntentInfo":"Object","statusLiteral":"String","amount":"Double","currency":"String","success":true,"description":"String","metadata":"Object","paymentUserParams":"Object"}}

Route Event listingpayment-calledback

Event topic : clonesahibinden-listing-service-listingpayment-calledback

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 listing data object itself.

The following JSON included in the payload illustrates the fullest representation of the listing 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":"listing","method":"POST","action":"update","appVersion":"Version","rowCount":1,"listing":{"id":"ID","attributes":"Object","categoryId":"ID","condition":"Enum","condition_idx":"Integer","contactEmail":"String","contactPhone":"String","currency":"String","description":"Text","expiresAt":"Date","favoriteCount":"Integer","isPremium":"Boolean","listingType":"Enum","listingType_idx":"Integer","locationId":"ID","_paymentConfirmation":"String","premiumExpiry":"Date","premiumType":"Enum","premiumType_idx":"Integer","price":"Double","status":"Enum","status_idx":"Integer","subcategoryId":"ID","title":"String","userId":"ID","viewsCount":"Integer","paymentConfirmation":"Enum","paymentConfirmation_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},"paymentResult":{"paymentTicketId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"Enum","paymentIntentInfo":"Object","statusLiteral":"String","amount":"Double","currency":"String","success":true,"description":"String","metadata":"Object","paymentUserParams":"Object"}}

Route Event paymentcustomerbyuserid-retrived

Event topic : clonesahibinden-listing-service-paymentcustomerbyuserid-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_paymentCustomer data object itself.

The following JSON included in the payload illustrates the fullest representation of the sys_paymentCustomer 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_paymentCustomer","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_paymentCustomer":{"id":"ID","userId":"ID","customerId":"String","platform":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event paymentcustomers-listed

Event topic : clonesahibinden-listing-service-paymentcustomers-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_paymentCustomers data object itself.

The following JSON included in the payload illustrates the fullest representation of the sys_paymentCustomers 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_paymentCustomers","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_paymentCustomers":[{"id":"ID","userId":"ID","customerId":"String","platform":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]}

Route Event paymentcustomermethods-listed

Event topic : clonesahibinden-listing-service-paymentcustomermethods-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_paymentMethods data object itself.

The following JSON included in the payload illustrates the fullest representation of the sys_paymentMethods 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_paymentMethods","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_paymentMethods":[{"id":"ID","paymentMethodId":"String","userId":"ID","customerId":"String","cardHolderName":"String","cardHolderZip":"String","platform":"String","cardInfo":"Object","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]}

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 listing

Service Design Specification - Object Design for listing

clonesahibinden-listing-service documentation

Document Overview

This document outlines the object design for the listing model in our application. It includes details about the model’s attributes, relationships, and any specific validation or business logic that applies.

listing Data Object

Object Overview

Description: Core object for classified ads. Contains main listing information, relations, status, premium logic, price, attributes, contact info, and custom attributes. Supports premium upgrades via Stripe and lifecycle management.

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.

Stripe Integration

This data object is configured to integrate with Stripe for order management of listing. It is designed to handle payment processing and order tracking. To manage payments, Mindbricks will design additional Business API routes arround this data object, which will be used checkout orders and charge customers.

if an error occurs during the checkout process, the API will continue to execute, allowing for custom error handling. In this case, the payment error will ve recorded as a status update. To make a retry a new checkout, a new order will be created with the same data as the original order.

Properties Schema

Property Type Required Description
attributes Object No JSON object for custom per-category attributes (structured as required by category schema).
categoryId ID Yes Main category for the listing (categoryLocation:category).
condition Enum Yes Item condition: new, used, other.
contactEmail String No Contact email (recommended to send via platform only).
contactPhone String No Display phone/contact for listing; may be masked by front end.
currency String Yes Currency (ISO-4217 code, e.g. 'TRY', 'USD').
description Text Yes Full description/body of listing.
expiresAt Date No UTC expiry for listing; after this, listing is automatically expired.
favoriteCount Integer Yes Favorite count (updated asynchronously by favorite service, not directly settable by user).
isPremium Boolean Yes If true, the listing is premium (highlighted/pinned, eligible for special placement).
listingType Enum Yes Type of listing (sale, rent, service, etc.).
locationId ID Yes Location (categoryLocation:location).
_paymentConfirmation String No Stripe payment result details (Stripe webhook metadata, internal use only).
premiumExpiry Date No UTC date when premium status expires. Null if not premium or not applicable.
premiumType Enum No Which premium package (gold, silver, none, etc.).
price Double Yes Listing price.
status Enum Yes Lifecycle status: pending_review, active, denied, sold, expired, deleted.
subcategoryId ID No Subcategory for the listing, can be null for top-level (categoryLocation:category).
title String Yes Listing title, short and clear.
userId ID Yes Owner (poster) of the listing (auth:user).
viewsCount Integer Yes View count (updated asynchronously; not directly settable by user).
paymentConfirmation Enum Yes An automatic property that is used to check the confirmed status of the payment set by webhooks.

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

favoriteCount _paymentConfirmation userId viewsCount

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

attributes categoryId condition contactEmail contactPhone currency description expiresAt isPremium listingType locationId premiumExpiry premiumType price status subcategoryId title

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

attributes categoryId condition currency description expiresAt favoriteCount isPremium listingType locationId premiumExpiry premiumType price status subcategoryId title userId viewsCount paymentConfirmation

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

categoryId condition currency isPremium listingType locationId premiumExpiry premiumType price status subcategoryId userId paymentConfirmation

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

paymentConfirmation

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

categoryId locationId subcategoryId 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

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

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.

Formula Properties

isPremium

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

categoryId condition expiresAt isPremium listingType locationId premiumExpiry premiumType price status subcategoryId title userId paymentConfirmation

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_listingPayment

Service Design Specification - Object Design for sys_listingPayment

clonesahibinden-listing-service documentation

Document Overview

This document outlines the object design for the sys_listingPayment model in our application. It includes details about the model’s attributes, relationships, and any specific validation or business logic that applies.

sys_listingPayment Data Object

Object Overview

Description: A payment storage object to store the payment life cyle of orders based on listing object. It is autocreated based on the source object's checkout config

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
ownerId ID No An ID value to represent owner user who created the order
orderId ID Yes an ID value to represent the orderId which is the ID parameter of the source listing object
paymentId String Yes A String value to represent the paymentId which is generated on the Stripe gateway. This id may represent different objects due to the payment gateway and the chosen flow type
paymentStatus String Yes A string value to represent the payment status which belongs to the lifecyle of a Stripe payment.
statusLiteral String Yes A string value to represent the logical payment status which belongs to the application lifecycle itself.
redirectUrl String No A string value to represent return page of the frontend to show the result of the payment, this is used when the callback is made to server not the client.

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

orderId

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

ownerId orderId paymentId paymentStatus statusLiteral redirectUrl

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

ownerId orderId paymentId paymentStatus statusLiteral redirectUrl

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

ownerId orderId paymentId paymentStatus statusLiteral redirectUrl

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

orderId

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.

Secondary Key Properties

orderId

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.

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

ownerId orderId paymentId paymentStatus statusLiteral redirectUrl

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_paymentCustomer

Service Design Specification - Object Design for sys_paymentCustomer

clonesahibinden-listing-service documentation

Document Overview

This document outlines the object design for the sys_paymentCustomer model in our application. It includes details about the model’s attributes, relationships, and any specific validation or business logic that applies.

sys_paymentCustomer Data Object

Object Overview

Description: A payment storage object to store the customer values of the payment platform

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 No An ID value to represent the user who is created as a stripe customer
customerId String Yes A string value to represent the customer id which is generated on the Stripe gateway. This id is used to represent the customer in the Stripe gateway
platform String Yes A String value to represent payment platform which is used to make the payment. It is stripe as default. It will be used to distinguesh the payment gateways in the future.

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

customerId platform

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 customerId platform

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

userId customerId platform

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 customerId platform

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

userId customerId

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.

Secondary Key Properties

userId customerId

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.

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.

Filter Properties

userId customerId platform

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_paymentMethod

Service Design Specification - Object Design for sys_paymentMethod

clonesahibinden-listing-service documentation

Document Overview

This document outlines the object design for the sys_paymentMethod model in our application. It includes details about the model’s attributes, relationships, and any specific validation or business logic that applies.

sys_paymentMethod Data Object

Object Overview

Description: A payment storage object to store the payment methods of the platform customers

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
paymentMethodId String Yes A string value to represent the id of the payment method on the payment platform.
userId ID Yes An ID value to represent the user who owns the payment method
customerId String Yes A string value to represent the customer id which is generated on the payment gateway.
cardHolderName String No A string value to represent the name of the card holder. It can be different than the registered customer.
cardHolderZip String No A string value to represent the zip code of the card holder. It is used for address verification in specific countries.
platform String Yes A String value to represent payment platform which teh paymentMethod belongs. It is stripe as default. It will be used to distinguesh the payment gateways in the future.
cardInfo Object Yes A Json value to store the card details of the payment method.

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

paymentMethodId userId customerId cardHolderName cardHolderZip platform

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

paymentMethodId userId customerId cardHolderName cardHolderZip platform cardInfo

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

paymentMethodId userId customerId cardHolderName cardHolderZip platform cardInfo

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

paymentMethodId userId customerId platform cardInfo

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

paymentMethodId

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.

Secondary Key Properties

paymentMethodId userId customerId

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.

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.

Filter Properties

paymentMethodId userId customerId cardHolderName cardHolderZip platform cardInfo

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 Listing

Business API Design Specification - Create Listing

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 createListing 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 createListing Business API is designed to handle a create operation on the Listing 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 classified listing. Sets status to ‘pending_review’ (may be updated by moderator process). Accepts all mandatory fields, accepts premiumType for premium upgrade.

API Frontend Description By The Backend Architect

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 createListing Business API includes a REST controller that can be triggered via the following route:

/v1/listings

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 createListing Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The createListing Business API has 22 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
listingId ID No - body listingId
Description: This id paremeter is used to create the data object with a given specific id. Leave null for automatic id.
attributes Object No - body attributes
Description: JSON object for custom per-category attributes (structured as required by category schema).
categoryId ID Yes - body categoryId
Description: Main category for the listing (categoryLocation:category).
condition Enum Yes - body condition
Description: Item condition: new, used, other.
contactEmail String No - body contactEmail
Description: Contact email (recommended to send via platform only).
contactPhone String No - body contactPhone
Description: Display phone/contact for listing; may be masked by front end.
currency String Yes - body currency
Description: Currency (ISO-4217 code, e.g. ‘TRY’, ‘USD’).
description Text Yes - body description
Description: Full description/body of listing.
expiresAt Date No - body expiresAt
Description: UTC expiry for listing; after this, listing is automatically expired.
favoriteCount Integer Yes - body favoriteCount
Description: Favorite count (updated asynchronously by favorite service, not directly settable by user).
isPremium Boolean Yes - body isPremium
Description: If true, the listing is premium (highlighted/pinned, eligible for special placement).
listingType Enum Yes - body listingType
Description: Type of listing (sale, rent, service, etc.).
locationId ID Yes - body locationId
Description: Location (categoryLocation:location).
_paymentConfirmation String No - body _paymentConfirmation
Description: Stripe payment result details (Stripe webhook metadata, internal use only).
premiumExpiry Date No - body premiumExpiry
Description: UTC date when premium status expires. Null if not premium or not applicable.
premiumType Enum No - body premiumType
Description: Which premium package (gold, silver, none, etc.).
price Double Yes - body price
Description: Listing price.
status Enum Yes - body status
Description: Lifecycle status: pending_review, active, denied, sold, expired, deleted.
subcategoryId ID No - body subcategoryId
Description: Subcategory for the listing, can be null for top-level (categoryLocation:category).
title String Yes - body title
Description: Listing title, short and clear.
userId ID Yes - session userId
Description: Owner (poster) of the listing (auth:user).
viewsCount Integer Yes - body viewsCount
Description: View count (updated asynchronously; not directly settable by 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.

No parameters are transformed in this API.

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the createListing 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.listingId,
  attributes: this.attributes ? (typeof this.attributes == 'string' ? JSON.parse(this.attributes) : this.attributes) : null,
  categoryId: this.categoryId,
  condition: this.condition,
  contactEmail: this.contactEmail,
  contactPhone: this.contactPhone,
  currency: this.currency,
  description: this.description,
  expiresAt: this.expiresAt,
  favoriteCount: this.favoriteCount,
  isPremium: this.isPremium,
  listingType: this.listingType,
  locationId: this.locationId,
  _paymentConfirmation: this._paymentConfirmation,
  premiumExpiry: this.premiumExpiry,
  premiumType: this.premiumType,
  price: this.price,
  status: this.status,
  subcategoryId: this.subcategoryId,
  title: this.title,
  userId: this.userId,
  viewsCount: this.viewsCount,
  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, socketSettings, 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 createListing api has got 19 regular client parameters

Parameter Type Required Population
attributes Object false request.body?.[“attributes”]
categoryId ID true request.body?.[“categoryId”]
condition Enum true request.body?.[“condition”]
contactEmail String false request.body?.[“contactEmail”]
contactPhone String false request.body?.[“contactPhone”]
currency String true request.body?.[“currency”]
description Text true request.body?.[“description”]
expiresAt Date false request.body?.[“expiresAt”]
favoriteCount Integer true request.body?.[“favoriteCount”]
listingType Enum true request.body?.[“listingType”]
locationId ID true request.body?.[“locationId”]
_paymentConfirmation String false request.body?.[“_paymentConfirmation”]
premiumExpiry Date false request.body?.[“premiumExpiry”]
premiumType Enum false request.body?.[“premiumType”]
price Double true request.body?.[“price”]
status Enum true request.body?.[“status”]
subcategoryId ID false request.body?.[“subcategoryId”]
title String true request.body?.[“title”]
viewsCount Integer true request.body?.[“viewsCount”]

REST Request

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

  axios({
    method: 'POST',
    url: '/v1/listings',
    data: {
            attributes:"Object",  
            categoryId:"ID",  
            condition:"Enum",  
            contactEmail:"String",  
            contactPhone:"String",  
            currency:"String",  
            description:"Text",  
            expiresAt:"Date",  
            favoriteCount:"Integer",  
            listingType:"Enum",  
            locationId:"ID",  
            _paymentConfirmation:"String",  
            premiumExpiry:"Date",  
            premiumType:"Enum",  
            price:"Double",  
            status:"Enum",  
            subcategoryId:"ID",  
            title:"String",  
            viewsCount:"Integer",  
    
    },
    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 listing 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": "listing",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"listing": {
		"id": "ID",
		"attributes": "Object",
		"categoryId": "ID",
		"condition": "Enum",
		"condition_idx": "Integer",
		"contactEmail": "String",
		"contactPhone": "String",
		"currency": "String",
		"description": "Text",
		"expiresAt": "Date",
		"favoriteCount": "Integer",
		"isPremium": "Boolean",
		"listingType": "Enum",
		"listingType_idx": "Integer",
		"locationId": "ID",
		"_paymentConfirmation": "String",
		"premiumExpiry": "Date",
		"premiumType": "Enum",
		"premiumType_idx": "Integer",
		"price": "Double",
		"status": "Enum",
		"status_idx": "Integer",
		"subcategoryId": "ID",
		"title": "String",
		"userId": "ID",
		"viewsCount": "Integer",
		"paymentConfirmation": "Enum",
		"paymentConfirmation_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Business API Design Specification - Delete Listing

Business API Design Specification - Delete Listing

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 deleteListing 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 deleteListing Business API is designed to handle a delete operation on the Listing data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

Delete a listing (soft delete, sets status to ‘deleted’). Only allowed by listing owner, admin, or moderator.

API Frontend Description By The Backend Architect

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 deleteListing Business API includes a REST controller that can be triggered via the following route:

/v1/listings/:listingId

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 deleteListing Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The deleteListing 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
listingId ID Yes - urlpath listingId
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 deleteListing 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.

{$and:[{id:this.listingId},{isActive:true}]}

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, socketSettings, 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 deleteListing api has got 1 regular client parameter

Parameter Type Required Population
listingId ID true request.params?.[“listingId”]

REST Request

To access the api you can use the REST controller with the path DELETE /v1/listings/:listingId

  axios({
    method: 'DELETE',
    url: `/v1/listings/${listingId}`,
    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 listing 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": "listing",
	"method": "DELETE",
	"action": "delete",
	"appVersion": "Version",
	"rowCount": 1,
	"listing": {
		"id": "ID",
		"attributes": "Object",
		"categoryId": "ID",
		"condition": "Enum",
		"condition_idx": "Integer",
		"contactEmail": "String",
		"contactPhone": "String",
		"currency": "String",
		"description": "Text",
		"expiresAt": "Date",
		"favoriteCount": "Integer",
		"isPremium": "Boolean",
		"listingType": "Enum",
		"listingType_idx": "Integer",
		"locationId": "ID",
		"_paymentConfirmation": "String",
		"premiumExpiry": "Date",
		"premiumType": "Enum",
		"premiumType_idx": "Integer",
		"price": "Double",
		"status": "Enum",
		"status_idx": "Integer",
		"subcategoryId": "ID",
		"title": "String",
		"userId": "ID",
		"viewsCount": "Integer",
		"paymentConfirmation": "Enum",
		"paymentConfirmation_idx": "Integer",
		"isActive": false,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Business API Design Specification - Expire Premiumsandlistings

Business API Design Specification - Expire Premiumsandlistings

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 expirePremiumsAndListings 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 expirePremiumsAndListings Business API is designed to handle a update operation on the Listing data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

Scheduled job to expire listings or premium status as needed (cron call, not user). Sets status to expired, or disables isPremium when premiumExpiry is in the past.

API Frontend Description By The Backend Architect

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.

Cron Controller

The expirePremiumsAndListings Business API includes a Cron controller, which triggers the API automatically at specified time intervals within the system.

The schedule for executing the API is defined by the following cron expression:

0 * * * *

The result of the Business API execution will be recorded in the service logs.

Note: Cron controllers cannot provide any parameters to the Business API.

API Parameters

The expirePremiumsAndListings 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
listingId ID Yes - urlpath listingId
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 expirePremiumsAndListings 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


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.

{$and:[{id:this.listingId},{isActive:true}]}

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.

{}

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, socketSettings, 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 expirePremiumsAndListings api has got 1 regular client parameter

Parameter Type Required Population
listingId ID true request.params?.[“listingId”]

REST Request

To access the api you can use the REST controller with the path ** /v1/expirepremiumsandlistings/:listingId**

  axios({
    method: '',
    url: `/v1/expirepremiumsandlistings/${listingId}`,
    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 listing 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": "listing",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"listing": {
		"id": "ID",
		"attributes": "Object",
		"categoryId": "ID",
		"condition": "Enum",
		"condition_idx": "Integer",
		"contactEmail": "String",
		"contactPhone": "String",
		"currency": "String",
		"description": "Text",
		"expiresAt": "Date",
		"favoriteCount": "Integer",
		"isPremium": "Boolean",
		"listingType": "Enum",
		"listingType_idx": "Integer",
		"locationId": "ID",
		"_paymentConfirmation": "String",
		"premiumExpiry": "Date",
		"premiumType": "Enum",
		"premiumType_idx": "Integer",
		"price": "Double",
		"status": "Enum",
		"status_idx": "Integer",
		"subcategoryId": "ID",
		"title": "String",
		"userId": "ID",
		"viewsCount": "Integer",
		"paymentConfirmation": "Enum",
		"paymentConfirmation_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Business API Design Specification - Get Listing

Business API Design Specification - Get Listing

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 getListing 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 getListing Business API is designed to handle a get operation on the Listing data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

Retrieve one listing with all primary fields, including category, subcategory, location, user info. Optionally, frontend can request joined images/favorites from other services.

API Frontend Description By The Backend Architect

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 getListing Business API includes a REST controller that can be triggered via the following route:

/v1/listings/:listingId

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 getListing Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The getListing 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
listingId ID Yes - urlpath listingId
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 getListing 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,price,currency,condition,listingType,status,isPremium,premiumType,premiumExpiry,viewsCount,favoriteCount,contactPhone,contactEmail,expiresAt,attributes,userId,categoryId,subcategoryId,locationId

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.

{$and:[{id:this.listingId},{isActive:true}]}

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, socketSettings, 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 getListing api has got 1 regular client parameter

Parameter Type Required Population
listingId ID true request.params?.[“listingId”]

REST Request

To access the api you can use the REST controller with the path GET /v1/listings/:listingId

  axios({
    method: 'GET',
    url: `/v1/listings/${listingId}`,
    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 listing 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": "listing",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"listing": {
		"user": {
			"fullname": "String",
			"avatar": "String",
			"roleId": "String"
		},
		"category": {
			"name": "String",
			"parentCategoryId": "ID",
			"slug": "String"
		},
		"subcategory": {
			"name": "String",
			"parentCategoryId": "ID",
			"slug": "String"
		},
		"location": {
			"city": "String",
			"country": "String",
			"district": "String"
		},
		"isActive": true
	}
}

Business API Design Specification - List Listings

Business API Design Specification - List Listings

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 listListings 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 listListings Business API is designed to handle a list operation on the Listing data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

Search/browse listings with advanced filtering (category, location, keyword, price range, condition, type, premium, status, etc.) and sorting. Publicly accessible. Supports pagination and all major sort orders. Full-text search on title/description.

API Frontend Description By The Backend Architect

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 listListings Business API includes a REST controller that can be triggered via the following route:

/v1/listings

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 listListings Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The listListings 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 listListings 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,price,currency,condition,listingType,status,isPremium,premiumType,premiumExpiry,viewsCount,favoriteCount,expiresAt,userId,categoryId,subcategoryId,locationId

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 : keywordSearch

// condition doWhen 
// this.keyword != null &amp;&amp; this.keyword.length &gt; 0

// condition excludeWhen
// No excludeWhen condtion defined

// clause object
{"$or": [ {"title": { "$ilike": `%${this.keyword}%` } }, { "description": { "$ilike": `%${this.keyword}%` } } ] }

// Addtional Clause Name : categoryFilter

// condition doWhen 
// this.categoryId != null

// condition excludeWhen
// No excludeWhen condtion defined

// clause object
{"categoryId": this.categoryId}

// Addtional Clause Name : subcategoryFilter

// condition doWhen 
// this.subcategoryId != null

// condition excludeWhen
// No excludeWhen condtion defined

// clause object
{"subcategoryId": this.subcategoryId}

// Addtional Clause Name : locationFilter

// condition doWhen 
// this.locationId != null

// condition excludeWhen
// No excludeWhen condtion defined

// clause object
{"locationId": this.locationId}

// Addtional Clause Name : priceMinFilter

// condition doWhen 
// this.priceMin != null

// condition excludeWhen
// No excludeWhen condtion defined

// clause object
{"price": { "$gte": this.priceMin }}

// Addtional Clause Name : priceMaxFilter

// condition doWhen 
// this.priceMax != null

// condition excludeWhen
// No excludeWhen condtion defined

// clause object
{"price": { "$lte": this.priceMax }}

// Addtional Clause Name : conditionFilter

// condition doWhen 
// this.condition != null

// condition excludeWhen
// No excludeWhen condtion defined

// clause object
{"condition": this.condition}

// Addtional Clause Name : listingTypeFilter

// condition doWhen 
// this.listingType != null

// condition excludeWhen
// No excludeWhen condtion defined

// clause object
{"listingType": this.listingType}

// Addtional Clause Name : premiumFilter

// condition doWhen 
// this.isPremium != null

// condition excludeWhen
// No excludeWhen condtion defined

// clause object
{"isPremium": this.isPremium}

// Addtional Clause Name : statusFilter

// condition doWhen 
// this.status != null

// condition excludeWhen
// No excludeWhen condtion defined

// clause object
{"status": this.status}

// Addtional Clause Name : expiresAtFilter

// condition doWhen 
// this.expiresAt != null

// condition excludeWhen
// No excludeWhen condtion defined

// clause object
{"expiresAt": this.expiresAt}

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

{isActive:true}

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).

[ createdAt desc,createdAt asc,price asc,price desc,isPremium desc,viewsCount 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, socketSettings, 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 listListings api has got no visible parameters.

REST Request

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

  axios({
    method: 'GET',
    url: '/v1/listings',
    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 listings 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": "listings",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"listings": [
		{
			"user": [
				{
					"fullname": "String",
					"avatar": "String"
				},
				{},
				{}
			],
			"category": [
				{
					"name": "String"
				},
				{},
				{}
			],
			"subcategory": [
				{
					"name": "String"
				},
				{},
				{}
			],
			"location": [
				{
					"city": "String",
					"district": "String"
				},
				{},
				{}
			],
			"isActive": true
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Business API Design Specification - Update Listing

Business API Design Specification - Update Listing

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 updateListing 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 updateListing Business API is designed to handle a update operation on the Listing data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

Update any mutable field of a listing. Only allowed by owner, admin, or moderator. If significant fields change and listing is active, status may return to pending_review until approved.

API Frontend Description By The Backend Architect

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 updateListing Business API includes a REST controller that can be triggered via the following route:

/v1/listings/:listingId

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 updateListing Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The updateListing Business API has 18 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
listingId ID Yes - urlpath listingId
Description: This id paremeter is used to select the required data object that will be updated
attributes Object No - body attributes
Description: JSON object for custom per-category attributes (structured as required by category schema).
categoryId ID No - body categoryId
Description: Main category for the listing (categoryLocation:category).
condition Enum No - body condition
Description: Item condition: new, used, other.
contactEmail String No - body contactEmail
Description: Contact email (recommended to send via platform only).
contactPhone String No - body contactPhone
Description: Display phone/contact for listing; may be masked by front end.
currency String No - body currency
Description: Currency (ISO-4217 code, e.g. ‘TRY’, ‘USD’).
description Text No - body description
Description: Full description/body of listing.
expiresAt Date No - body expiresAt
Description: UTC expiry for listing; after this, listing is automatically expired.
isPremium Boolean No - body isPremium
Description: If true, the listing is premium (highlighted/pinned, eligible for special placement).
listingType Enum No - body listingType
Description: Type of listing (sale, rent, service, etc.).
locationId ID No - body locationId
Description: Location (categoryLocation:location).
premiumExpiry Date No - body premiumExpiry
Description: UTC date when premium status expires. Null if not premium or not applicable.
premiumType Enum No - body premiumType
Description: Which premium package (gold, silver, none, etc.).
price Double No - body price
Description: Listing price.
status Enum No - body status
Description: Lifecycle status: pending_review, active, denied, sold, expired, deleted.
subcategoryId ID No - body subcategoryId
Description: Subcategory for the listing, can be null for top-level (categoryLocation:category).
title String No - body title
Description: Listing title, short and clear.

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 updateListing 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.

{$and:[{id:this.listingId},{isActive:true}]}

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.

{
  attributes: this.attributes ? (typeof this.attributes == 'string' ? JSON.parse(this.attributes) : this.attributes) : null,
  categoryId: this.categoryId,
  condition: this.condition,
  contactEmail: this.contactEmail,
  contactPhone: this.contactPhone,
  currency: this.currency,
  description: this.description,
  expiresAt: this.expiresAt,
  isPremium: this.isPremium,
  listingType: this.listingType,
  locationId: this.locationId,
  premiumExpiry: this.premiumExpiry,
  premiumType: this.premiumType,
  price: this.price,
  status: this.status,
  subcategoryId: this.subcategoryId,
  title: this.title,
}

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, socketSettings, 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 updateListing api has got 17 regular client parameters

Parameter Type Required Population
listingId ID true request.params?.[“listingId”]
attributes Object false request.body?.[“attributes”]
categoryId ID false request.body?.[“categoryId”]
condition Enum false request.body?.[“condition”]
contactEmail String false request.body?.[“contactEmail”]
contactPhone String false request.body?.[“contactPhone”]
currency String false request.body?.[“currency”]
description Text false request.body?.[“description”]
expiresAt Date false request.body?.[“expiresAt”]
listingType Enum false request.body?.[“listingType”]
locationId ID false request.body?.[“locationId”]
premiumExpiry Date false request.body?.[“premiumExpiry”]
premiumType Enum false request.body?.[“premiumType”]
price Double false request.body?.[“price”]
status Enum false request.body?.[“status”]
subcategoryId ID false request.body?.[“subcategoryId”]
title String false request.body?.[“title”]

REST Request

To access the api you can use the REST controller with the path PATCH /v1/listings/:listingId

  axios({
    method: 'PATCH',
    url: `/v1/listings/${listingId}`,
    data: {
            attributes:"Object",  
            categoryId:"ID",  
            condition:"Enum",  
            contactEmail:"String",  
            contactPhone:"String",  
            currency:"String",  
            description:"Text",  
            expiresAt:"Date",  
            listingType:"Enum",  
            locationId:"ID",  
            premiumExpiry:"Date",  
            premiumType:"Enum",  
            price:"Double",  
            status:"Enum",  
            subcategoryId:"ID",  
            title:"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 listing 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": "listing",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"listing": {
		"id": "ID",
		"attributes": "Object",
		"categoryId": "ID",
		"condition": "Enum",
		"condition_idx": "Integer",
		"contactEmail": "String",
		"contactPhone": "String",
		"currency": "String",
		"description": "Text",
		"expiresAt": "Date",
		"favoriteCount": "Integer",
		"isPremium": "Boolean",
		"listingType": "Enum",
		"listingType_idx": "Integer",
		"locationId": "ID",
		"_paymentConfirmation": "String",
		"premiumExpiry": "Date",
		"premiumType": "Enum",
		"premiumType_idx": "Integer",
		"price": "Double",
		"status": "Enum",
		"status_idx": "Integer",
		"subcategoryId": "ID",
		"title": "String",
		"userId": "ID",
		"viewsCount": "Integer",
		"paymentConfirmation": "Enum",
		"paymentConfirmation_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Business API Design Specification - Upgrade Listingpremium

Business API Design Specification - Upgrade Listingpremium

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 upgradeListingPremium 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 upgradeListingPremium Business API is designed to handle a update operation on the Listing data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

Upgrades a listing to premium status after successful payment. Sets isPremium=true, premiumType, premiumExpiry based on duration, and records payment confirmation. Called internally by payment service via interservice call.

API Frontend Description By The Backend Architect

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 upgradeListingPremium Business API includes a REST controller that can be triggered via the following route:

/v1/listings/upgrade-premium

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 upgradeListingPremium Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The upgradeListingPremium 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
listingId ID Yes - body listingId
Description: ID of the listing to upgrade
premiumType Enum Yes `` body premiumType
Description: Premium package type (bronze, silver, gold)
premiumDuration Integer Yes `` body premiumDuration
Description: Duration of premium in days
paymentTransactionId ID Yes `` body paymentTransactionId
Description: Payment transaction ID for confirmation record

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 upgradeListingPremium 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


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 :

{id: this.listingId}

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.

{$and:[{id: this.listingId},{isActive:true}]}

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

{
    isPremium: true,
    premiumType: this.premiumType,
    premiumExpiry: new Date(Date.now() + this.premiumDuration * 24 * 60 * 60 * 1000).toISOString(),
    _paymentConfirmation: this.paymentTransactionId,
   
}

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.

{
  isPremium: true,
  premiumType: this.premiumType,
  premiumExpiry: new Date(Date.now() + this.premiumDuration * 24 * 60 * 60 * 1000).toISOString(),
  // _paymentConfirmation parameter is closed to update by client request 
  // include it in data clause unless you are sure 
  _paymentConfirmation: this.paymentTransactionId,
}

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, socketSettings, 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 upgradeListingPremium api has got 4 regular client parameters

Parameter Type Required Population
listingId ID true request.body?.[“listingId”]
premiumType Enum true request.body?.[“premiumType”]
premiumDuration Integer true request.body?.[“premiumDuration”]
paymentTransactionId ID true request.body?.[“paymentTransactionId”]

REST Request

To access the api you can use the REST controller with the path POST /v1/listings/upgrade-premium

  axios({
    method: 'POST',
    url: '/v1/listings/upgrade-premium',
    data: {
            listingId:"ID",  
            premiumType:"Enum",  
            premiumDuration:"Integer",  
            paymentTransactionId:"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 listing 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": "listing",
	"method": "POST",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"listing": {
		"id": "ID",
		"attributes": "Object",
		"categoryId": "ID",
		"condition": "Enum",
		"condition_idx": "Integer",
		"contactEmail": "String",
		"contactPhone": "String",
		"currency": "String",
		"description": "Text",
		"expiresAt": "Date",
		"favoriteCount": "Integer",
		"isPremium": "Boolean",
		"listingType": "Enum",
		"listingType_idx": "Integer",
		"locationId": "ID",
		"_paymentConfirmation": "String",
		"premiumExpiry": "Date",
		"premiumType": "Enum",
		"premiumType_idx": "Integer",
		"price": "Double",
		"status": "Enum",
		"status_idx": "Integer",
		"subcategoryId": "ID",
		"title": "String",
		"userId": "ID",
		"viewsCount": "Integer",
		"paymentConfirmation": "Enum",
		"paymentConfirmation_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Business API Design Specification - Get Listingpayment

Business API Design Specification - Get Listingpayment

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 getListingPayment 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 getListingPayment Business API is designed to handle a get operation on the Sys_listingPayment 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 get the payment information by ID.

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 getListingPayment Business API includes a REST controller that can be triggered via the following route:

/v1/listingpayment/:sys_listingPaymentId

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 getListingPayment Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The getListingPayment 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_listingPaymentId ID Yes - urlpath sys_listingPaymentId
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 getListingPayment 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.

{$and:[{id:this.sys_listingPaymentId},{isActive:true}]}

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, socketSettings, 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 getListingPayment api has got 1 regular client parameter

Parameter Type Required Population
sys_listingPaymentId ID true request.params?.[“sys_listingPaymentId”]

REST Request

To access the api you can use the REST controller with the path GET /v1/listingpayment/:sys_listingPaymentId

  axios({
    method: 'GET',
    url: `/v1/listingpayment/${sys_listingPaymentId}`,
    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_listingPayment 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_listingPayment",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"sys_listingPayment": {
		"id": "ID",
		"ownerId": "ID",
		"orderId": "ID",
		"paymentId": "String",
		"paymentStatus": "String",
		"statusLiteral": "String",
		"redirectUrl": "String",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Business API Design Specification - List Listingpayments

Business API Design Specification - List Listingpayments

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 listListingPayments 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 listListingPayments Business API is designed to handle a list operation on the Sys_listingPayment 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 list all payments.

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 listListingPayments Business API includes a REST controller that can be triggered via the following route:

/v1/listingpayments

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 listListingPayments Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The listListingPayments 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:

Filter Parameters

The listListingPayments api supports 6 optional filter parameters for filtering list results using URL query parameters. These parameters are only available for list type APIs.

ownerId Filter

Type: ID
Description: An ID value to represent owner user who created the order
Location: Query Parameter

Usage:

Non-Array Property:

Examples:

// Get records with a specific ID
GET /v1/listingpayments?ownerId=550e8400-e29b-41d4-a716-446655440000

// Get records with multiple IDs (use multiple parameters)
GET /v1/listingpayments?ownerId=550e8400-e29b-41d4-a716-446655440000&ownerId=660e8400-e29b-41d4-a716-446655440001

// Get records without this field
GET /v1/listingpayments?ownerId=null

orderId Filter

Type: ID
Description: an ID value to represent the orderId which is the ID parameter of the source listing object
Location: Query Parameter

Usage:

Non-Array Property:

Examples:

// Get records with a specific ID
GET /v1/listingpayments?orderId=550e8400-e29b-41d4-a716-446655440000

// Get records with multiple IDs (use multiple parameters)
GET /v1/listingpayments?orderId=550e8400-e29b-41d4-a716-446655440000&orderId=660e8400-e29b-41d4-a716-446655440001

// Get records without this field
GET /v1/listingpayments?orderId=null

paymentId Filter

Type: String
Description: A String value to represent the paymentId which is generated on the Stripe gateway. This id may represent different objects due to the payment gateway and the chosen flow type
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/listingpayments?paymentId=john
// Matches: "John", "Johnny", "johnson", "McJohn", etc.

// Find records with multiple values (use multiple parameters)
GET /v1/listingpayments?paymentId=laptop&paymentId=phone&paymentId=tablet
// Matches records containing "laptop", "phone", or "tablet" anywhere in the field

// Find records without this field
GET /v1/listingpayments?paymentId=null

paymentStatus Filter

Type: String
Description: A string value to represent the payment status which belongs to the lifecyle of a Stripe payment.
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/listingpayments?paymentStatus=john
// Matches: "John", "Johnny", "johnson", "McJohn", etc.

// Find records with multiple values (use multiple parameters)
GET /v1/listingpayments?paymentStatus=laptop&paymentStatus=phone&paymentStatus=tablet
// Matches records containing "laptop", "phone", or "tablet" anywhere in the field

// Find records without this field
GET /v1/listingpayments?paymentStatus=null

statusLiteral Filter

Type: String
Description: A string value to represent the logical payment status which belongs to the application lifecycle itself.
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/listingpayments?statusLiteral=john
// Matches: "John", "Johnny", "johnson", "McJohn", etc.

// Find records with multiple values (use multiple parameters)
GET /v1/listingpayments?statusLiteral=laptop&statusLiteral=phone&statusLiteral=tablet
// Matches records containing "laptop", "phone", or "tablet" anywhere in the field

// Find records without this field
GET /v1/listingpayments?statusLiteral=null

redirectUrl Filter

Type: String
Description: A string value to represent return page of the frontend to show the result of the payment, this is used when the callback is made to server not the client.
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/listingpayments?redirectUrl=john
// Matches: "John", "Johnny", "johnson", "McJohn", etc.

// Find records with multiple values (use multiple parameters)
GET /v1/listingpayments?redirectUrl=laptop&redirectUrl=phone&redirectUrl=tablet
// Matches records containing "laptop", "phone", or "tablet" anywhere in the field

// Find records without this field
GET /v1/listingpayments?redirectUrl=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 listListingPayments 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.

{isActive:true}

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, socketSettings, 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 listListingPayments api has 6 filter parameters available for filtering list results. See the Filter Parameters section above for detailed usage examples.

Filter Parameter Type Array Property Description
ownerId ID No An ID value to represent owner user who created the order
orderId ID No an ID value to represent the orderId which is the ID parameter of the source listing object
paymentId String No A String value to represent the paymentId which is generated on the Stripe gateway. This id may represent different objects due to the payment gateway and the chosen flow type
paymentStatus String No A string value to represent the payment status which belongs to the lifecyle of a Stripe payment.
statusLiteral String No A string value to represent the logical payment status which belongs to the application lifecycle itself.
redirectUrl String No A string value to represent return page of the frontend to show the result of the payment, this is used when the callback is made to server not the client.

REST Request

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

  axios({
    method: 'GET',
    url: '/v1/listingpayments',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section for usage examples)
        // ownerId: '<value>' // Filter by ownerId
        // orderId: '<value>' // Filter by orderId
        // paymentId: '<value>' // Filter by paymentId
        // paymentStatus: '<value>' // Filter by paymentStatus
        // statusLiteral: '<value>' // Filter by statusLiteral
        // redirectUrl: '<value>' // Filter by redirectUrl
            }
  });

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_listingPayments 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_listingPayments",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"sys_listingPayments": [
		{
			"id": "ID",
			"ownerId": "ID",
			"orderId": "ID",
			"paymentId": "String",
			"paymentStatus": "String",
			"statusLiteral": "String",
			"redirectUrl": "String",
			"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 Listingpayment

Business API Design Specification - Create Listingpayment

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 createListingPayment 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 createListingPayment Business API is designed to handle a create operation on the Sys_listingPayment 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 create a new payment.

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 createListingPayment Business API includes a REST controller that can be triggered via the following route:

/v1/listingpayment

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 createListingPayment Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The createListingPayment 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
sys_listingPaymentId ID No - body sys_listingPaymentId
Description: This id paremeter is used to create the data object with a given specific id. Leave null for automatic id.
ownerId ID No - session userId
Description: An ID value to represent owner user who created the order
orderId ID Yes - body orderId
Description: an ID value to represent the orderId which is the ID parameter of the source listing object
paymentId String Yes - body paymentId
Description: A String value to represent the paymentId which is generated on the Stripe gateway. This id may represent different objects due to the payment gateway and the chosen flow type
paymentStatus String Yes - body paymentStatus
Description: A string value to represent the payment status which belongs to the lifecyle of a Stripe payment.
statusLiteral String Yes - body statusLiteral
Description: A string value to represent the logical payment status which belongs to the application lifecycle itself.
redirectUrl String No - body redirectUrl
Description: A string value to represent return page of the frontend to show the result of the payment, this is used when the callback is made to server not the client.

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 createListingPayment 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_listingPaymentId,
  ownerId: this.ownerId,
  orderId: this.orderId,
  paymentId: this.paymentId,
  paymentStatus: this.paymentStatus,
  statusLiteral: this.statusLiteral,
  redirectUrl: this.redirectUrl,
  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, socketSettings, 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 createListingPayment api has got 5 regular client parameters

Parameter Type Required Population
orderId ID true request.body?.[“orderId”]
paymentId String true request.body?.[“paymentId”]
paymentStatus String true request.body?.[“paymentStatus”]
statusLiteral String true request.body?.[“statusLiteral”]
redirectUrl String false request.body?.[“redirectUrl”]

REST Request

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

  axios({
    method: 'POST',
    url: '/v1/listingpayment',
    data: {
            orderId:"ID",  
            paymentId:"String",  
            paymentStatus:"String",  
            statusLiteral:"String",  
            redirectUrl:"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 sys_listingPayment 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_listingPayment",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"sys_listingPayment": {
		"id": "ID",
		"ownerId": "ID",
		"orderId": "ID",
		"paymentId": "String",
		"paymentStatus": "String",
		"statusLiteral": "String",
		"redirectUrl": "String",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Business API Design Specification - Update Listingpayment

Business API Design Specification - Update Listingpayment

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 updateListingPayment 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 updateListingPayment Business API is designed to handle a update operation on the Sys_listingPayment 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 an existing payment.

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 updateListingPayment Business API includes a REST controller that can be triggered via the following route:

/v1/listingpayment/:sys_listingPaymentId

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 updateListingPayment Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The updateListingPayment 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
sys_listingPaymentId ID Yes - urlpath sys_listingPaymentId
Description: This id paremeter is used to select the required data object that will be updated
ownerId ID No - session userId
Description: An ID value to represent owner user who created the order
paymentId String No - body paymentId
Description: A String value to represent the paymentId which is generated on the Stripe gateway. This id may represent different objects due to the payment gateway and the chosen flow type
paymentStatus String No - body paymentStatus
Description: A string value to represent the payment status which belongs to the lifecyle of a Stripe payment.
statusLiteral String No - body statusLiteral
Description: A string value to represent the logical payment status which belongs to the application lifecycle itself.
redirectUrl String No - body redirectUrl
Description: A string value to represent return page of the frontend to show the result of the payment, this is used when the callback is made to server not the client.

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 updateListingPayment 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.

{$and:[{id:this.sys_listingPaymentId},{isActive:true}]}

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.

{
  ownerId: this.ownerId,
  paymentId: this.paymentId,
  paymentStatus: this.paymentStatus,
  statusLiteral: this.statusLiteral,
  redirectUrl: this.redirectUrl,
}

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, socketSettings, 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 updateListingPayment api has got 5 regular client parameters

Parameter Type Required Population
sys_listingPaymentId ID true request.params?.[“sys_listingPaymentId”]
paymentId String false request.body?.[“paymentId”]
paymentStatus String false request.body?.[“paymentStatus”]
statusLiteral String false request.body?.[“statusLiteral”]
redirectUrl String false request.body?.[“redirectUrl”]

REST Request

To access the api you can use the REST controller with the path PATCH /v1/listingpayment/:sys_listingPaymentId

  axios({
    method: 'PATCH',
    url: `/v1/listingpayment/${sys_listingPaymentId}`,
    data: {
            paymentId:"String",  
            paymentStatus:"String",  
            statusLiteral:"String",  
            redirectUrl:"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 sys_listingPayment 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_listingPayment",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"sys_listingPayment": {
		"id": "ID",
		"ownerId": "ID",
		"orderId": "ID",
		"paymentId": "String",
		"paymentStatus": "String",
		"statusLiteral": "String",
		"redirectUrl": "String",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Business API Design Specification - Delete Listingpayment

Business API Design Specification - Delete Listingpayment

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 deleteListingPayment 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 deleteListingPayment Business API is designed to handle a delete operation on the Sys_listingPayment 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 delete a payment.

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 deleteListingPayment Business API includes a REST controller that can be triggered via the following route:

/v1/listingpayment/:sys_listingPaymentId

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 deleteListingPayment Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The deleteListingPayment 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_listingPaymentId ID Yes - urlpath sys_listingPaymentId
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 deleteListingPayment 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.

{$and:[{id:this.sys_listingPaymentId},{isActive:true}]}

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, socketSettings, 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 deleteListingPayment api has got 1 regular client parameter

Parameter Type Required Population
sys_listingPaymentId ID true request.params?.[“sys_listingPaymentId”]

REST Request

To access the api you can use the REST controller with the path DELETE /v1/listingpayment/:sys_listingPaymentId

  axios({
    method: 'DELETE',
    url: `/v1/listingpayment/${sys_listingPaymentId}`,
    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_listingPayment 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_listingPayment",
	"method": "DELETE",
	"action": "delete",
	"appVersion": "Version",
	"rowCount": 1,
	"sys_listingPayment": {
		"id": "ID",
		"ownerId": "ID",
		"orderId": "ID",
		"paymentId": "String",
		"paymentStatus": "String",
		"statusLiteral": "String",
		"redirectUrl": "String",
		"isActive": false,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Business API Design Specification - Get Listingpaymentbyorderid

Business API Design Specification - Get Listingpaymentbyorderid

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 getListingPaymentByOrderId 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 getListingPaymentByOrderId Business API is designed to handle a get operation on the Sys_listingPayment 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 get the payment information by order id.

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 getListingPaymentByOrderId Business API includes a REST controller that can be triggered via the following route:

/v1/listingpaymentbyorderid/:orderId

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 getListingPaymentByOrderId Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The getListingPaymentByOrderId 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
sys_listingPaymentId ID Yes - urlpath sys_listingPaymentId
Description: This id paremeter is used to query the required data object.
orderId ID Yes - urlpath orderId
Description: an ID value to represent the orderId which is the ID parameter of the source listing object. The parameter is used to query data.

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 getListingPaymentByOrderId 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 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.

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.

{$and:[{orderId:{"$eq":this.orderId}},{isActive:true}]}

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, socketSettings, 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 getListingPaymentByOrderId api has got 2 regular client parameters

Parameter Type Required Population
sys_listingPaymentId ID true request.params?.[“sys_listingPaymentId”]
orderId ID true request.params?.[“orderId”]

REST Request

To access the api you can use the REST controller with the path GET /v1/listingpaymentbyorderid/:orderId

  axios({
    method: 'GET',
    url: `/v1/listingpaymentbyorderid/${orderId}`,
    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_listingPayment 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_listingPayment",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"sys_listingPayment": {
		"id": "ID",
		"ownerId": "ID",
		"orderId": "ID",
		"paymentId": "String",
		"paymentStatus": "String",
		"statusLiteral": "String",
		"redirectUrl": "String",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Business API Design Specification - Get Listingpaymentbypaymentid

Business API Design Specification - Get Listingpaymentbypaymentid

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 getListingPaymentByPaymentId 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 getListingPaymentByPaymentId Business API is designed to handle a get operation on the Sys_listingPayment 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 get the payment information by payment id.

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 getListingPaymentByPaymentId Business API includes a REST controller that can be triggered via the following route:

/v1/listingpaymentbypaymentid/:paymentId

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 getListingPaymentByPaymentId Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The getListingPaymentByPaymentId 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
sys_listingPaymentId ID Yes - urlpath sys_listingPaymentId
Description: This id paremeter is used to query the required data object.
paymentId String Yes - urlpath paymentId
Description: A String value to represent the paymentId which is generated on the Stripe gateway. This id may represent different objects due to the payment gateway and the chosen flow type. The parameter is used to query data.

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 getListingPaymentByPaymentId 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 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.

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.

{$and:[{paymentId:{"$eq":this.paymentId}},{isActive:true}]}

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, socketSettings, 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 getListingPaymentByPaymentId api has got 2 regular client parameters

Parameter Type Required Population
sys_listingPaymentId ID true request.params?.[“sys_listingPaymentId”]
paymentId String true request.params?.[“paymentId”]

REST Request

To access the api you can use the REST controller with the path GET /v1/listingpaymentbypaymentid/:paymentId

  axios({
    method: 'GET',
    url: `/v1/listingpaymentbypaymentid/${paymentId}`,
    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_listingPayment 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_listingPayment",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"sys_listingPayment": {
		"id": "ID",
		"ownerId": "ID",
		"orderId": "ID",
		"paymentId": "String",
		"paymentStatus": "String",
		"statusLiteral": "String",
		"redirectUrl": "String",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Business API Design Specification - Start Listingpayment

Business API Design Specification - Start Listingpayment

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 startListingPayment 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 startListingPayment Business API is designed to handle a update operation on the Listing data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

Start payment for listing

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 startListingPayment Business API includes a REST controller that can be triggered via the following route:

/v1/startlistingpayment/:listingId

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 startListingPayment Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The startListingPayment 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
listingId ID Yes - urlpath listingId
Description: This id paremeter is used to select the required data object that will be updated
paymentUserParams Object No - body paymentUserParams
Description: The user parameters that should be defined to start a stripe payment process

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 startListingPayment 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.

{$and:[{id:this.listingId},{isActive:true}]}

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: this.status,
    updatedAt: new Date(),
    paymentConfirmation: this.paymentConfirmation,
   
}

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,
  updatedAt: new Date(),
  // paymentConfirmation parameter is closed to update by client request 
  // include it in data clause unless you are sure 
  paymentConfirmation: this.paymentConfirmation,
}

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, socketSettings, 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 : doStartPayment

Action Type: PaymentAction

Start a payment on Stripe platform

class Api {
  getOrderId() {
    return this.listingId;
  }

  getPaymentStatusTopic(actionType) {
    switch (actionType) {
      case "started":
        return "clonesahibinden-listing-service-listingpaymentstatus-started";
      case "updated":
        return "clonesahibinden-listing-service-listingpaymentstatus-updated";
      case "succeeded":
        return "clonesahibinden-listing-service-listingpaymentstatus-succeeded";
      case "failed":
        return "clonesahibinden-listing-service-listingpaymentstatus-failed";
      case "paymentdone":
        return "clonesahibinden-listing-service-listing-paymentdone";
    }
  }

  async paymentUpdated(statusLiteral) {
    switch (statusLiteral) {
      case "started":
        await this.paymentStarted();
        break;
      case "canceled":
        await this.paymentCanceled();
        break;
      case "failed":
        await this.paymentFailed();
        break;
      case "success":
        await this.paymentDone();
        break;
      default:
        await this.paymentFailed();
        break;
    }
  }

  async paymentStarted() {
    this.status = "pending_review";
    this.paymentConfirmation = "processing";
    this.paymentManager.raisePaymentStatusEvent("started");
  }

  async paymentCanceled() {
    this.status = "pending_review";
    this.paymentConfirmation = "canceled";
    this.paymentManager.raisePaymentStatusEvent("failed");
  }

  async paymentFailed() {
    this.status = "denied";
    this.paymentConfirmation = "canceled";
    this.paymentManager.raisePaymentStatusEvent("failed");
  }

  async paymentDone() {
    this.status =
      this.listing.status === "pending_review" ? "active" : this.listing.status;
    this.paymentConfirmation = "paid";
    this.paymentManager.raisePaymentStatusEvent("succeeded");
  }

  getPaymentParameters(userParams) {
    const description = `Premium upgrade for listing ${this.listing.title}`;

    const metadata = {
      order: "Listing-Listing-order",
      orderId: this.listing.id,
      paymentName: "listing",
    };

    return {
      userId: this.session._USERID,
      fullname: this.session.fullname,
      email: this.session.email,
      description,
      amount: this.listing.price,
      currency: this.listing.currency,
      orderId: this.listing.id,
      metadata: metadata,
      storeCard: userParams?.storeCard,
      paymentUserParams: userParams,
      bodyParams: this.bodyParams,
    };
  }

  async doStartPayment() {
    // Handle Payment Action

    try {
      if (!this.paymentManager) {
        throw new Error(
          "This dboject is not an order object. So auto-payment process can not be started.",
        );
      }
      this.paymentResult = await this.paymentManager.startPayment(
        this.paymentUserParams,
      );
    } catch (err) {
      if (err instanceof PaymentGateError) {
        this.paymentResult = err.serializeError();
        //**errorLog
      } else throw err;
    }
    return this.paymentResult;
  }
}

[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 startListingPayment api has got 2 regular client parameters

Parameter Type Required Population
listingId ID true request.params?.[“listingId”]
paymentUserParams Object false request.body?.[“paymentUserParams”]

REST Request

To access the api you can use the REST controller with the path PATCH /v1/startlistingpayment/:listingId

  axios({
    method: 'PATCH',
    url: `/v1/startlistingpayment/${listingId}`,
    data: {
            paymentUserParams:"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 listing 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": "listing",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"listing": {
		"id": "ID",
		"attributes": "Object",
		"categoryId": "ID",
		"condition": "Enum",
		"condition_idx": "Integer",
		"contactEmail": "String",
		"contactPhone": "String",
		"currency": "String",
		"description": "Text",
		"expiresAt": "Date",
		"favoriteCount": "Integer",
		"isPremium": "Boolean",
		"listingType": "Enum",
		"listingType_idx": "Integer",
		"locationId": "ID",
		"_paymentConfirmation": "String",
		"premiumExpiry": "Date",
		"premiumType": "Enum",
		"premiumType_idx": "Integer",
		"price": "Double",
		"status": "Enum",
		"status_idx": "Integer",
		"subcategoryId": "ID",
		"title": "String",
		"userId": "ID",
		"viewsCount": "Integer",
		"paymentConfirmation": "Enum",
		"paymentConfirmation_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	},
	"paymentResult": {
		"paymentTicketId": "ID",
		"orderId": "ID",
		"paymentId": "String",
		"paymentStatus": "Enum",
		"paymentIntentInfo": "Object",
		"statusLiteral": "String",
		"amount": "Double",
		"currency": "String",
		"success": true,
		"description": "String",
		"metadata": "Object",
		"paymentUserParams": "Object"
	}
}

Business API Design Specification - Refresh Listingpayment

Business API Design Specification - Refresh Listingpayment

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 refreshListingPayment 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 refreshListingPayment Business API is designed to handle a update operation on the Listing data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

Refresh payment info for listing from Stripe

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 refreshListingPayment Business API includes a REST controller that can be triggered via the following route:

/v1/refreshlistingpayment/:listingId

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 refreshListingPayment Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The refreshListingPayment 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
listingId ID Yes - urlpath listingId
Description: This id paremeter is used to select the required data object that will be updated
paymentUserParams Object No - body paymentUserParams
Description: The user parameters that should be defined to refresh a stripe payment process

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 refreshListingPayment 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.

{$and:[{id:this.listingId},{isActive:true}]}

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: this.status,
    updatedAt: new Date(),
    paymentConfirmation: this.paymentConfirmation,
   
}

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,
  updatedAt: new Date(),
  // paymentConfirmation parameter is closed to update by client request 
  // include it in data clause unless you are sure 
  paymentConfirmation: this.paymentConfirmation,
}

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, socketSettings, 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 : doRefreshPayment

Action Type: PaymentAction

Refresh payment from Stripe platform, the payment operation data in the gateway server will be fetched and the application payment tickets and order status will be refreshed according to the server. This api may be used if you dont want to use a webhook.

class Api {
  getOrderId() {
    return this.listingId;
  }

  getPaymentStatusTopic(actionType) {
    switch (actionType) {
      case "started":
        return "clonesahibinden-listing-service-listingpaymentstatus-started";
      case "updated":
        return "clonesahibinden-listing-service-listingpaymentstatus-updated";
      case "succeeded":
        return "clonesahibinden-listing-service-listingpaymentstatus-succeeded";
      case "failed":
        return "clonesahibinden-listing-service-listingpaymentstatus-failed";
      case "paymentdone":
        return "clonesahibinden-listing-service-listing-paymentdone";
    }
  }

  async paymentUpdated(statusLiteral) {
    switch (statusLiteral) {
      case "started":
        await this.paymentStarted();
        break;
      case "canceled":
        await this.paymentCanceled();
        break;
      case "failed":
        await this.paymentFailed();
        break;
      case "success":
        await this.paymentDone();
        break;
      default:
        await this.paymentFailed();
        break;
    }
  }

  async paymentStarted() {
    this.status = "pending_review";
    this.paymentConfirmation = "processing";
    this.paymentManager.raisePaymentStatusEvent("started");
  }

  async paymentCanceled() {
    this.status = "pending_review";
    this.paymentConfirmation = "canceled";
    this.paymentManager.raisePaymentStatusEvent("failed");
  }

  async paymentFailed() {
    this.status = "denied";
    this.paymentConfirmation = "canceled";
    this.paymentManager.raisePaymentStatusEvent("failed");
  }

  async paymentDone() {
    this.status =
      this.listing.status === "pending_review" ? "active" : this.listing.status;
    this.paymentConfirmation = "paid";
    this.paymentManager.raisePaymentStatusEvent("succeeded");
  }

  getPaymentParameters(userParams) {
    const description = `Premium upgrade for listing ${this.listing.title}`;

    const metadata = {
      order: "Listing-Listing-order",
      orderId: this.listing.id,
      paymentName: "listing",
    };

    return {
      userId: this.session._USERID,
      fullname: this.session.fullname,
      email: this.session.email,
      description,
      amount: this.listing.price,
      currency: this.listing.currency,
      orderId: this.listing.id,
      metadata: metadata,
      storeCard: userParams?.storeCard,
      paymentUserParams: userParams,
      bodyParams: this.bodyParams,
    };
  }

  async doRefreshPayment() {
    // Handle Payment Action

    try {
      if (!this.paymentManager) {
        throw new Error(
          "This dboject is not an order object. So auto-payment process can not be started.",
        );
      }

      this.paymentResult = await this.paymentManager.refreshPayment(
        this.paymentUserParams,
      );
    } catch (err) {
      if (err instanceof PaymentGateError) {
        this.paymentResult = err.serializeError();
        //**errorLog
      } else throw err;
    }
    return this.paymentResult;
  }
}

[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 refreshListingPayment api has got 2 regular client parameters

Parameter Type Required Population
listingId ID true request.params?.[“listingId”]
paymentUserParams Object false request.body?.[“paymentUserParams”]

REST Request

To access the api you can use the REST controller with the path PATCH /v1/refreshlistingpayment/:listingId

  axios({
    method: 'PATCH',
    url: `/v1/refreshlistingpayment/${listingId}`,
    data: {
            paymentUserParams:"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 listing 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": "listing",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"listing": {
		"id": "ID",
		"attributes": "Object",
		"categoryId": "ID",
		"condition": "Enum",
		"condition_idx": "Integer",
		"contactEmail": "String",
		"contactPhone": "String",
		"currency": "String",
		"description": "Text",
		"expiresAt": "Date",
		"favoriteCount": "Integer",
		"isPremium": "Boolean",
		"listingType": "Enum",
		"listingType_idx": "Integer",
		"locationId": "ID",
		"_paymentConfirmation": "String",
		"premiumExpiry": "Date",
		"premiumType": "Enum",
		"premiumType_idx": "Integer",
		"price": "Double",
		"status": "Enum",
		"status_idx": "Integer",
		"subcategoryId": "ID",
		"title": "String",
		"userId": "ID",
		"viewsCount": "Integer",
		"paymentConfirmation": "Enum",
		"paymentConfirmation_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	},
	"paymentResult": {
		"paymentTicketId": "ID",
		"orderId": "ID",
		"paymentId": "String",
		"paymentStatus": "Enum",
		"paymentIntentInfo": "Object",
		"statusLiteral": "String",
		"amount": "Double",
		"currency": "String",
		"success": true,
		"description": "String",
		"metadata": "Object",
		"paymentUserParams": "Object"
	}
}

Business API Design Specification - Callback Listingpayment

Business API Design Specification - Callback Listingpayment

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 callbackListingPayment 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 callbackListingPayment Business API is designed to handle a update operation on the Listing data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

Refresh payment values by gateway webhook call for listing

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 callbackListingPayment Business API includes a REST controller that can be triggered via the following route:

/v1/callbacklistingpayment

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 callbackListingPayment Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The callbackListingPayment 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
listingId ID Yes - body listingId
Description: The order id parameter that will be read from webhook callback params

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.listingId = 
  this.paymentCallbackParams?.orderId

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the callbackListingPayment 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


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.

{$and:[{id:this.listingId},{isActive:true}]}

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: this.status,
    updatedAt: new Date(),
    paymentConfirmation: this.paymentConfirmation,
   
}

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,
  updatedAt: new Date(),
  // paymentConfirmation parameter is closed to update by client request 
  // include it in data clause unless you are sure 
  paymentConfirmation: this.paymentConfirmation,
}

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, socketSettings, 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] Action : verifyPaymentWebhook

Action Type: VerifyWebhookAction

Verify a providers webhook call with the secret signature and read the params, write the callback parameters to the context. Only stripe webhooks is supported for now.

class Api {
  // Code for VerifyWebhookAction
  async verifyPaymentWebhook() {
    const secretKey = process.env.STRIPE_WEBHOOK_SECRET;
    await this.paymentManager.ensurePaymentGate();
    const stripeGateway = this.paymentManager.paymentGate;
    const result = await stripeGateway.webhookController(this.request);
    console.log("VerifyWebhookAction result -->", result);

    if (result.statusLiteral == "unhandled") {
      throw new BadRequestError(
        `Unhandled stripe webhook event [${result.eventType}]`,
      );
    }

    return result;
  }
}

[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] 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] Action : doPaymentCallback

Action Type: PaymentAction

Refresh payment by Stripe platform webhook, the payment operation data in the gateway server will be given by webhook call and the application payment tickets and order status will be refreshed according to the server.

class Api {
  getOrderId() {
    return this.listingId;
  }

  getPaymentStatusTopic(actionType) {
    switch (actionType) {
      case "started":
        return "clonesahibinden-listing-service-listingpaymentstatus-started";
      case "updated":
        return "clonesahibinden-listing-service-listingpaymentstatus-updated";
      case "succeeded":
        return "clonesahibinden-listing-service-listingpaymentstatus-succeeded";
      case "failed":
        return "clonesahibinden-listing-service-listingpaymentstatus-failed";
      case "paymentdone":
        return "clonesahibinden-listing-service-listing-paymentdone";
    }
  }

  async paymentUpdated(statusLiteral) {
    switch (statusLiteral) {
      case "started":
        await this.paymentStarted();
        break;
      case "canceled":
        await this.paymentCanceled();
        break;
      case "failed":
        await this.paymentFailed();
        break;
      case "success":
        await this.paymentDone();
        break;
      default:
        await this.paymentFailed();
        break;
    }
  }

  async paymentStarted() {
    this.status = "pending_review";
    this.paymentConfirmation = "processing";
    this.paymentManager.raisePaymentStatusEvent("started");
  }

  async paymentCanceled() {
    this.status = "pending_review";
    this.paymentConfirmation = "canceled";
    this.paymentManager.raisePaymentStatusEvent("failed");
  }

  async paymentFailed() {
    this.status = "denied";
    this.paymentConfirmation = "canceled";
    this.paymentManager.raisePaymentStatusEvent("failed");
  }

  async paymentDone() {
    this.status =
      this.listing.status === "pending_review" ? "active" : this.listing.status;
    this.paymentConfirmation = "paid";
    this.paymentManager.raisePaymentStatusEvent("succeeded");
  }

  getPaymentParameters(userParams) {
    const description = `Premium upgrade for listing ${this.listing.title}`;

    const metadata = {
      order: "Listing-Listing-order",
      orderId: this.listing.id,
      paymentName: "listing",
    };

    return {
      userId: this.session._USERID,
      fullname: this.session.fullname,
      email: this.session.email,
      description,
      amount: this.listing.price,
      currency: this.listing.currency,
      orderId: this.listing.id,
      metadata: metadata,
      storeCard: userParams?.storeCard,
      paymentUserParams: userParams,
      bodyParams: this.bodyParams,
    };
  }

  async doPaymentCallback() {
    // Handle Payment Action

    try {
      if (!this.paymentManager) {
        throw new Error(
          "This dboject is not an order object. So auto-payment process can not be started.",
        );
      }
      this.paymentResult =
        await this.paymentManager.processPaymentCallbackResult(
          this.paymentCallbackParams,
        );
    } catch (err) {
      if (err instanceof PaymentGateError) {
        this.paymentResult = err.serializeError();
        //**errorLog
      } else throw err;
    }
    return this.paymentResult;
  }
}

[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 callbackListingPayment api has got 1 regular client parameter

Parameter Type Required Population
listingId ID true request.body?.[“listingId”]

REST Request

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

  axios({
    method: 'POST',
    url: '/v1/callbacklistingpayment',
    data: {
            listingId:"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 listing 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": "listing",
	"method": "POST",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"listing": {
		"id": "ID",
		"attributes": "Object",
		"categoryId": "ID",
		"condition": "Enum",
		"condition_idx": "Integer",
		"contactEmail": "String",
		"contactPhone": "String",
		"currency": "String",
		"description": "Text",
		"expiresAt": "Date",
		"favoriteCount": "Integer",
		"isPremium": "Boolean",
		"listingType": "Enum",
		"listingType_idx": "Integer",
		"locationId": "ID",
		"_paymentConfirmation": "String",
		"premiumExpiry": "Date",
		"premiumType": "Enum",
		"premiumType_idx": "Integer",
		"price": "Double",
		"status": "Enum",
		"status_idx": "Integer",
		"subcategoryId": "ID",
		"title": "String",
		"userId": "ID",
		"viewsCount": "Integer",
		"paymentConfirmation": "Enum",
		"paymentConfirmation_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	},
	"paymentResult": {
		"paymentTicketId": "ID",
		"orderId": "ID",
		"paymentId": "String",
		"paymentStatus": "Enum",
		"paymentIntentInfo": "Object",
		"statusLiteral": "String",
		"amount": "Double",
		"currency": "String",
		"success": true,
		"description": "String",
		"metadata": "Object",
		"paymentUserParams": "Object"
	}
}

Business API Design Specification - Get Paymentcustomerbyuserid

Business API Design Specification - Get Paymentcustomerbyuserid

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 getPaymentCustomerByUserId 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 getPaymentCustomerByUserId Business API is designed to handle a get operation on the Sys_paymentCustomer 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 get the payment customer information by user id.

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 getPaymentCustomerByUserId Business API includes a REST controller that can be triggered via the following route:

/v1/paymentcustomers/: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 getPaymentCustomerByUserId Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The getPaymentCustomerByUserId 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
sys_paymentCustomerId ID Yes - urlpath sys_paymentCustomerId
Description: This id paremeter is used to query the required data object.
userId ID Yes - urlpath userId
Description: An ID value to represent the user who is created as a stripe customer. The parameter is used to query data.

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 getPaymentCustomerByUserId 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 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.

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.

{$and:[{userId:{"$eq":this.userId}},{isActive:true}]}

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, socketSettings, 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 getPaymentCustomerByUserId api has got 2 regular client parameters

Parameter Type Required Population
sys_paymentCustomerId ID true request.params?.[“sys_paymentCustomerId”]
userId ID true request.params?.[“userId”]

REST Request

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

  axios({
    method: 'GET',
    url: `/v1/paymentcustomers/${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 sys_paymentCustomer 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_paymentCustomer",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"sys_paymentCustomer": {
		"id": "ID",
		"userId": "ID",
		"customerId": "String",
		"platform": "String",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Business API Design Specification - List Paymentcustomers

Business API Design Specification - List Paymentcustomers

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 listPaymentCustomers 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 listPaymentCustomers Business API is designed to handle a list operation on the Sys_paymentCustomer 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 list all payment customers.

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 listPaymentCustomers Business API includes a REST controller that can be triggered via the following route:

/v1/paymentcustomers

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 listPaymentCustomers Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The listPaymentCustomers 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 listPaymentCustomers api supports 3 optional filter parameters for filtering list results using URL query parameters. These parameters are only available for list type APIs.

userId Filter

Type: ID
Description: An ID value to represent the user who is created as a stripe customer
Location: Query Parameter

Usage:

Non-Array Property:

Examples:

// Get records with a specific ID
GET /v1/paymentcustomers?userId=550e8400-e29b-41d4-a716-446655440000

// Get records with multiple IDs (use multiple parameters)
GET /v1/paymentcustomers?userId=550e8400-e29b-41d4-a716-446655440000&userId=660e8400-e29b-41d4-a716-446655440001

// Get records without this field
GET /v1/paymentcustomers?userId=null

customerId Filter

Type: String
Description: A string value to represent the customer id which is generated on the Stripe gateway. This id is used to represent the customer in the Stripe gateway
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/paymentcustomers?customerId=john
// Matches: "John", "Johnny", "johnson", "McJohn", etc.

// Find records with multiple values (use multiple parameters)
GET /v1/paymentcustomers?customerId=laptop&customerId=phone&customerId=tablet
// Matches records containing "laptop", "phone", or "tablet" anywhere in the field

// Find records without this field
GET /v1/paymentcustomers?customerId=null

platform Filter

Type: String
Description: A String value to represent payment platform which is used to make the payment. It is stripe as default. It will be used to distinguesh the payment gateways in the future.
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/paymentcustomers?platform=john
// Matches: "John", "Johnny", "johnson", "McJohn", etc.

// Find records with multiple values (use multiple parameters)
GET /v1/paymentcustomers?platform=laptop&platform=phone&platform=tablet
// Matches records containing "laptop", "phone", or "tablet" anywhere in the field

// Find records without this field
GET /v1/paymentcustomers?platform=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 listPaymentCustomers 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.

{isActive:true}

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, socketSettings, 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 listPaymentCustomers 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
userId ID No An ID value to represent the user who is created as a stripe customer
customerId String No A string value to represent the customer id which is generated on the Stripe gateway. This id is used to represent the customer in the Stripe gateway
platform String No A String value to represent payment platform which is used to make the payment. It is stripe as default. It will be used to distinguesh the payment gateways in the future.

REST Request

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

  axios({
    method: 'GET',
    url: '/v1/paymentcustomers',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section for usage examples)
        // userId: '<value>' // Filter by userId
        // customerId: '<value>' // Filter by customerId
        // platform: '<value>' // Filter by platform
            }
  });

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_paymentCustomers 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_paymentCustomers",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"sys_paymentCustomers": [
		{
			"id": "ID",
			"userId": "ID",
			"customerId": "String",
			"platform": "String",
			"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 - List Paymentcustomermethods

Business API Design Specification - List Paymentcustomermethods

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 listPaymentCustomerMethods 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 listPaymentCustomerMethods Business API is designed to handle a list operation on the Sys_paymentMethod 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 list all payment customer methods.

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 listPaymentCustomerMethods Business API includes a REST controller that can be triggered via the following route:

/v1/paymentcustomermethods/: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 listPaymentCustomerMethods Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The listPaymentCustomerMethods 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
userId ID Yes - session userId
Description: An ID value to represent the user who owns the payment method. The parameter is used to query data.

Filter Parameters

The listPaymentCustomerMethods api supports 6 optional filter parameters for filtering list results using URL query parameters. These parameters are only available for list type APIs.

paymentMethodId Filter

Type: String
Description: A string value to represent the id of the payment method on the payment platform.
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/paymentcustomermethods/:userId?paymentMethodId=john
// Matches: "John", "Johnny", "johnson", "McJohn", etc.

// Find records with multiple values (use multiple parameters)
GET /v1/paymentcustomermethods/:userId?paymentMethodId=laptop&paymentMethodId=phone&paymentMethodId=tablet
// Matches records containing "laptop", "phone", or "tablet" anywhere in the field

// Find records without this field
GET /v1/paymentcustomermethods/:userId?paymentMethodId=null

customerId Filter

Type: String
Description: A string value to represent the customer id which is generated on the payment gateway.
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/paymentcustomermethods/:userId?customerId=john
// Matches: "John", "Johnny", "johnson", "McJohn", etc.

// Find records with multiple values (use multiple parameters)
GET /v1/paymentcustomermethods/:userId?customerId=laptop&customerId=phone&customerId=tablet
// Matches records containing "laptop", "phone", or "tablet" anywhere in the field

// Find records without this field
GET /v1/paymentcustomermethods/:userId?customerId=null

cardHolderName Filter

Type: String
Description: A string value to represent the name of the card holder. It can be different than the registered customer.
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/paymentcustomermethods/:userId?cardHolderName=john
// Matches: "John", "Johnny", "johnson", "McJohn", etc.

// Find records with multiple values (use multiple parameters)
GET /v1/paymentcustomermethods/:userId?cardHolderName=laptop&cardHolderName=phone&cardHolderName=tablet
// Matches records containing "laptop", "phone", or "tablet" anywhere in the field

// Find records without this field
GET /v1/paymentcustomermethods/:userId?cardHolderName=null

cardHolderZip Filter

Type: String
Description: A string value to represent the zip code of the card holder. It is used for address verification in specific countries.
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/paymentcustomermethods/:userId?cardHolderZip=john
// Matches: "John", "Johnny", "johnson", "McJohn", etc.

// Find records with multiple values (use multiple parameters)
GET /v1/paymentcustomermethods/:userId?cardHolderZip=laptop&cardHolderZip=phone&cardHolderZip=tablet
// Matches records containing "laptop", "phone", or "tablet" anywhere in the field

// Find records without this field
GET /v1/paymentcustomermethods/:userId?cardHolderZip=null

platform Filter

Type: String
Description: A String value to represent payment platform which teh paymentMethod belongs. It is stripe as default. It will be used to distinguesh the payment gateways in the future.
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/paymentcustomermethods/:userId?platform=john
// Matches: "John", "Johnny", "johnson", "McJohn", etc.

// Find records with multiple values (use multiple parameters)
GET /v1/paymentcustomermethods/:userId?platform=laptop&platform=phone&platform=tablet
// Matches records containing "laptop", "phone", or "tablet" anywhere in the field

// Find records without this field
GET /v1/paymentcustomermethods/:userId?platform=null

cardInfo Filter

Type: Object
Description: A Json value to store the card details of the payment method.
Location: Query Parameter

Usage:

Examples:

// Get records with specific value
GET /v1/paymentcustomermethods/:userId?cardInfo=<value>

// Get records with multiple values (use multiple parameters)
GET /v1/paymentcustomermethods/:userId?cardInfo=<value1>&cardInfo=<value2>

// Get records without this field
GET /v1/paymentcustomermethods/:userId?cardInfo=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 listPaymentCustomerMethods 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 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.

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.

{$and:[{userId:{"$eq":this.userId}},{isActive:true}]}

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, socketSettings, 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 listPaymentCustomerMethods api has 6 filter parameters available for filtering list results. See the Filter Parameters section above for detailed usage examples.

Filter Parameter Type Array Property Description
paymentMethodId String No A string value to represent the id of the payment method on the payment platform.
customerId String No A string value to represent the customer id which is generated on the payment gateway.
cardHolderName String No A string value to represent the name of the card holder. It can be different than the registered customer.
cardHolderZip String No A string value to represent the zip code of the card holder. It is used for address verification in specific countries.
platform String No A String value to represent payment platform which teh paymentMethod belongs. It is stripe as default. It will be used to distinguesh the payment gateways in the future.
cardInfo Object No A Json value to store the card details of the payment method.

REST Request

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

  axios({
    method: 'GET',
    url: `/v1/paymentcustomermethods/${userId}`,
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section for usage examples)
        // paymentMethodId: '<value>' // Filter by paymentMethodId
        // customerId: '<value>' // Filter by customerId
        // cardHolderName: '<value>' // Filter by cardHolderName
        // cardHolderZip: '<value>' // Filter by cardHolderZip
        // platform: '<value>' // Filter by platform
        // cardInfo: '<value>' // Filter by cardInfo
            }
  });

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_paymentMethods 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_paymentMethods",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"sys_paymentMethods": [
		{
			"id": "ID",
			"paymentMethodId": "String",
			"userId": "ID",
			"customerId": "String",
			"cardHolderName": "String",
			"cardHolderZip": "String",
			"platform": "String",
			"cardInfo": "Object",
			"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 - _fetch Listlisting

Business API Design Specification - _fetch Listlisting

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 _fetchListListing 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 _fetchListListing Business API is designed to handle a list operation on the Listing data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

System API to fetch list of listing records for frontend application. Auto-generated, not visible in design.

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 _fetchListListing Business API includes a REST controller that can be triggered via the following route:

/v1/_fetchlistlisting

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 _fetchListListing Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The _fetchListListing Business API has 14 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 _fetchListListing api supports 14 optional filter parameters for filtering list results using URL query parameters. These parameters are only available for list type APIs.

categoryId Filter

Type: ID
Description: Main category for the listing (categoryLocation:category).
Location: Query Parameter

Usage:

Non-Array Property:

Examples:

// Get records with a specific ID
GET /v1/_fetchlistlisting?categoryId=550e8400-e29b-41d4-a716-446655440000

// Get records with multiple IDs (use multiple parameters)
GET /v1/_fetchlistlisting?categoryId=550e8400-e29b-41d4-a716-446655440000&categoryId=660e8400-e29b-41d4-a716-446655440001

// Get records without this field
GET /v1/_fetchlistlisting?categoryId=null

condition Filter

Type: Enum
Description: Item condition: new, used, other.
Location: Query Parameter

Usage:

Examples:

// Get records with specific enum value
GET /v1/_fetchlistlisting?condition=active

// Get records with multiple enum values (use multiple parameters)
GET /v1/_fetchlistlisting?condition=active&condition=pending

// Get records without this field
GET /v1/_fetchlistlisting?condition=null

expiresAt Filter

Type: Date
Description: UTC expiry for listing; after this, listing is automatically expired.
Location: Query Parameter

Usage:

Non-Array Property (Date filtering matches records where the date falls within the specified day, ignoring time portion):

Special Date Operators:

Date Formats: Dates can be provided in ISO 8601 format (2024-01-15, 2024-01-15T10:30:00Z) or as timestamps (1705324800000).

Examples:

// Get records created on a specific date
GET /v1/_fetchlistlisting?expiresAt=2024-01-15

// Get records created on multiple dates (use multiple parameters)
GET /v1/_fetchlistlisting?expiresAt=2024-01-15&expiresAt=2024-01-20

// Get records created today (server timezone)
GET /v1/_fetchlistlisting?expiresAt=$today

// Get records created today (user's local timezone)
GET /v1/_fetchlistlisting?expiresAt=$ltoday

// Get records created this week (server timezone)
GET /v1/_fetchlistlisting?expiresAt=$week

// Get records created this week (user's local timezone)
GET /v1/_fetchlistlisting?expiresAt=$lweek

// Get records created this month
GET /v1/_fetchlistlisting?expiresAt=$month

// Get records created on a specific date (user's local timezone)
GET /v1/_fetchlistlisting?expiresAt=$leq-2024-01-15

// Get records created on multiple dates (user's local timezone, use multiple parameters)
GET /v1/_fetchlistlisting?expiresAt=$lin-2024-01-15&expiresAt=$lin-2024-01-20

// Get records without this field
GET /v1/_fetchlistlisting?expiresAt=null

isPremium Filter

Type: Boolean
Description: If true, the listing is premium (highlighted/pinned, eligible for special placement).
Location: Query Parameter

Usage:

Examples:

// Get records with true value
GET /v1/_fetchlistlisting?isPremium=true

// Get records with false value (or null)
GET /v1/_fetchlistlisting?isPremium=false

// Get records without this field
GET /v1/_fetchlistlisting?isPremium=null

Note: When filtering by false, the query also includes records where the boolean field is null.

listingType Filter

Type: Enum
Description: Type of listing (sale, rent, service, etc.).
Location: Query Parameter

Usage:

Examples:

// Get records with specific enum value
GET /v1/_fetchlistlisting?listingType=active

// Get records with multiple enum values (use multiple parameters)
GET /v1/_fetchlistlisting?listingType=active&listingType=pending

// Get records without this field
GET /v1/_fetchlistlisting?listingType=null

locationId Filter

Type: ID
Description: Location (categoryLocation:location).
Location: Query Parameter

Usage:

Non-Array Property:

Examples:

// Get records with a specific ID
GET /v1/_fetchlistlisting?locationId=550e8400-e29b-41d4-a716-446655440000

// Get records with multiple IDs (use multiple parameters)
GET /v1/_fetchlistlisting?locationId=550e8400-e29b-41d4-a716-446655440000&locationId=660e8400-e29b-41d4-a716-446655440001

// Get records without this field
GET /v1/_fetchlistlisting?locationId=null

premiumExpiry Filter

Type: Date
Description: UTC date when premium status expires. Null if not premium or not applicable.
Location: Query Parameter

Usage:

Non-Array Property (Date filtering matches records where the date falls within the specified day, ignoring time portion):

Special Date Operators:

Date Formats: Dates can be provided in ISO 8601 format (2024-01-15, 2024-01-15T10:30:00Z) or as timestamps (1705324800000).

Examples:

// Get records created on a specific date
GET /v1/_fetchlistlisting?premiumExpiry=2024-01-15

// Get records created on multiple dates (use multiple parameters)
GET /v1/_fetchlistlisting?premiumExpiry=2024-01-15&premiumExpiry=2024-01-20

// Get records created today (server timezone)
GET /v1/_fetchlistlisting?premiumExpiry=$today

// Get records created today (user's local timezone)
GET /v1/_fetchlistlisting?premiumExpiry=$ltoday

// Get records created this week (server timezone)
GET /v1/_fetchlistlisting?premiumExpiry=$week

// Get records created this week (user's local timezone)
GET /v1/_fetchlistlisting?premiumExpiry=$lweek

// Get records created this month
GET /v1/_fetchlistlisting?premiumExpiry=$month

// Get records created on a specific date (user's local timezone)
GET /v1/_fetchlistlisting?premiumExpiry=$leq-2024-01-15

// Get records created on multiple dates (user's local timezone, use multiple parameters)
GET /v1/_fetchlistlisting?premiumExpiry=$lin-2024-01-15&premiumExpiry=$lin-2024-01-20

// Get records without this field
GET /v1/_fetchlistlisting?premiumExpiry=null

premiumType Filter

Type: Enum
Description: Which premium package (gold, silver, none, etc.).
Location: Query Parameter

Usage:

Examples:

// Get records with specific enum value
GET /v1/_fetchlistlisting?premiumType=active

// Get records with multiple enum values (use multiple parameters)
GET /v1/_fetchlistlisting?premiumType=active&premiumType=pending

// Get records without this field
GET /v1/_fetchlistlisting?premiumType=null

price Filter

Type: Double
Description: Listing price.
Location: Query Parameter

Usage:

Non-Array Property:

Range Operators:

Examples:

// Get records with exact value
GET /v1/_fetchlistlisting?price=25

// Get records with multiple values (use multiple parameters)
GET /v1/_fetchlistlisting?price=25&price=30&price=35

// Get records less than value
GET /v1/_fetchlistlisting?price=$lt-30

// Get records greater than or equal to value
GET /v1/_fetchlistlisting?price=$gte-18

// Get records between two values
GET /v1/_fetchlistlisting?price=$btw-100-500

// Get records without this field
GET /v1/_fetchlistlisting?price=null

status Filter

Type: Enum
Description: Lifecycle status: pending_review, active, denied, sold, expired, deleted.
Location: Query Parameter

Usage:

Examples:

// Get records with specific enum value
GET /v1/_fetchlistlisting?status=active

// Get records with multiple enum values (use multiple parameters)
GET /v1/_fetchlistlisting?status=active&status=pending

// Get records without this field
GET /v1/_fetchlistlisting?status=null

subcategoryId Filter

Type: ID
Description: Subcategory for the listing, can be null for top-level (categoryLocation:category).
Location: Query Parameter

Usage:

Non-Array Property:

Examples:

// Get records with a specific ID
GET /v1/_fetchlistlisting?subcategoryId=550e8400-e29b-41d4-a716-446655440000

// Get records with multiple IDs (use multiple parameters)
GET /v1/_fetchlistlisting?subcategoryId=550e8400-e29b-41d4-a716-446655440000&subcategoryId=660e8400-e29b-41d4-a716-446655440001

// Get records without this field
GET /v1/_fetchlistlisting?subcategoryId=null

title Filter

Type: String
Description: Listing title, short and clear.
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/_fetchlistlisting?title=john
// Matches: "John", "Johnny", "johnson", "McJohn", etc.

// Find records with multiple values (use multiple parameters)
GET /v1/_fetchlistlisting?title=laptop&title=phone&title=tablet
// Matches records containing "laptop", "phone", or "tablet" anywhere in the field

// Find records without this field
GET /v1/_fetchlistlisting?title=null

userId Filter

Type: ID
Description: Owner (poster) of the listing (auth:user).
Location: Query Parameter

Usage:

Non-Array Property:

Examples:

// Get records with a specific ID
GET /v1/_fetchlistlisting?userId=550e8400-e29b-41d4-a716-446655440000

// Get records with multiple IDs (use multiple parameters)
GET /v1/_fetchlistlisting?userId=550e8400-e29b-41d4-a716-446655440000&userId=660e8400-e29b-41d4-a716-446655440001

// Get records without this field
GET /v1/_fetchlistlisting?userId=null

paymentConfirmation Filter

Type: Enum
Description: An automatic property that is used to check the confirmed status of the payment set by webhooks.
Location: Query Parameter

Usage:

Examples:

// Get records with specific enum value
GET /v1/_fetchlistlisting?paymentConfirmation=active

// Get records with multiple enum values (use multiple parameters)
GET /v1/_fetchlistlisting?paymentConfirmation=active&paymentConfirmation=pending

// Get records without this field
GET /v1/_fetchlistlisting?paymentConfirmation=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 _fetchListListing 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.

{isActive:true}

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).

[ createdAt 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, socketSettings, 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 _fetchListListing api has 14 filter parameters available for filtering list results. See the Filter Parameters section above for detailed usage examples.

Filter Parameter Type Array Property Description
categoryId ID No Main category for the listing (categoryLocation:category).
condition Enum No Item condition: new, used, other.
expiresAt Date No UTC expiry for listing; after this, listing is automatically expired.
isPremium Boolean No If true, the listing is premium (highlighted/pinned, eligible for special placement).
listingType Enum No Type of listing (sale, rent, service, etc.).
locationId ID No Location (categoryLocation:location).
premiumExpiry Date No UTC date when premium status expires. Null if not premium or not applicable.
premiumType Enum No Which premium package (gold, silver, none, etc.).
price Double No Listing price.
status Enum No Lifecycle status: pending_review, active, denied, sold, expired, deleted.
subcategoryId ID No Subcategory for the listing, can be null for top-level (categoryLocation:category).
title String No Listing title, short and clear.
userId ID No Owner (poster) of the listing (auth:user).
paymentConfirmation Enum No An automatic property that is used to check the confirmed status of the payment set by webhooks.

REST Request

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

  axios({
    method: 'GET',
    url: '/v1/_fetchlistlisting',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section for usage examples)
        // categoryId: '<value>' // Filter by categoryId
        // condition: '<value>' // Filter by condition
        // expiresAt: '<value>' // Filter by expiresAt
        // isPremium: '<value>' // Filter by isPremium
        // listingType: '<value>' // Filter by listingType
        // locationId: '<value>' // Filter by locationId
        // premiumExpiry: '<value>' // Filter by premiumExpiry
        // premiumType: '<value>' // Filter by premiumType
        // price: '<value>' // Filter by price
        // status: '<value>' // Filter by status
        // subcategoryId: '<value>' // Filter by subcategoryId
        // title: '<value>' // Filter by title
        // userId: '<value>' // Filter by userId
        // paymentConfirmation: '<value>' // Filter by paymentConfirmation
            }
  });

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 listings 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": "listings",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"listings": [
		{
			"id": "ID",
			"attributes": "Object",
			"categoryId": "ID",
			"condition": "Enum",
			"condition_idx": "Integer",
			"contactEmail": "String",
			"contactPhone": "String",
			"currency": "String",
			"description": "Text",
			"expiresAt": "Date",
			"favoriteCount": "Integer",
			"isPremium": "Boolean",
			"listingType": "Enum",
			"listingType_idx": "Integer",
			"locationId": "ID",
			"_paymentConfirmation": "String",
			"premiumExpiry": "Date",
			"premiumType": "Enum",
			"premiumType_idx": "Integer",
			"price": "Double",
			"status": "Enum",
			"status_idx": "Integer",
			"subcategoryId": "ID",
			"title": "String",
			"userId": "ID",
			"viewsCount": "Integer",
			"paymentConfirmation": "Enum",
			"paymentConfirmation_idx": "Integer",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID",
			"mainCategory": [
				{
					"description": "Text",
					"icon": "String",
					"name": "String",
					"parentCategoryId": "ID",
					"slug": "String",
					"sortOrder": "Integer"
				},
				{},
				{}
			],
			"location": [
				{
					"city": "String",
					"country": "String",
					"district": "String",
					"latitude": "Double",
					"longitude": "Double",
					"postalCode": "String"
				},
				{},
				{}
			],
			"subCategory": [
				{
					"description": "Text",
					"icon": "String",
					"name": "String",
					"parentCategoryId": "ID",
					"slug": "String",
					"sortOrder": "Integer"
				},
				{},
				{}
			],
			"user": [
				{
					"fullname": "String"
				},
				{},
				{}
			]
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Business API Design Specification - _fetch Listsys_listingpayment

Business API Design Specification - _fetch Listsys_listingpayment

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 _fetchListSys_listingPayment 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 _fetchListSys_listingPayment Business API is designed to handle a list operation on the Sys_listingPayment data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

System API to fetch list of sys_listingPayment records for frontend application. Auto-generated, not visible in design.

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 _fetchListSys_listingPayment Business API includes a REST controller that can be triggered via the following route:

/v1/_fetchlistsys_listingpayment

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 _fetchListSys_listingPayment Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The _fetchListSys_listingPayment 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:

Filter Parameters

The _fetchListSys_listingPayment api supports 6 optional filter parameters for filtering list results using URL query parameters. These parameters are only available for list type APIs.

ownerId Filter

Type: ID
Description: An ID value to represent owner user who created the order
Location: Query Parameter

Usage:

Non-Array Property:

Examples:

// Get records with a specific ID
GET /v1/_fetchlistsys_listingpayment?ownerId=550e8400-e29b-41d4-a716-446655440000

// Get records with multiple IDs (use multiple parameters)
GET /v1/_fetchlistsys_listingpayment?ownerId=550e8400-e29b-41d4-a716-446655440000&ownerId=660e8400-e29b-41d4-a716-446655440001

// Get records without this field
GET /v1/_fetchlistsys_listingpayment?ownerId=null

orderId Filter

Type: ID
Description: an ID value to represent the orderId which is the ID parameter of the source listing object
Location: Query Parameter

Usage:

Non-Array Property:

Examples:

// Get records with a specific ID
GET /v1/_fetchlistsys_listingpayment?orderId=550e8400-e29b-41d4-a716-446655440000

// Get records with multiple IDs (use multiple parameters)
GET /v1/_fetchlistsys_listingpayment?orderId=550e8400-e29b-41d4-a716-446655440000&orderId=660e8400-e29b-41d4-a716-446655440001

// Get records without this field
GET /v1/_fetchlistsys_listingpayment?orderId=null

paymentId Filter

Type: String
Description: A String value to represent the paymentId which is generated on the Stripe gateway. This id may represent different objects due to the payment gateway and the chosen flow type
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/_fetchlistsys_listingpayment?paymentId=john
// Matches: "John", "Johnny", "johnson", "McJohn", etc.

// Find records with multiple values (use multiple parameters)
GET /v1/_fetchlistsys_listingpayment?paymentId=laptop&paymentId=phone&paymentId=tablet
// Matches records containing "laptop", "phone", or "tablet" anywhere in the field

// Find records without this field
GET /v1/_fetchlistsys_listingpayment?paymentId=null

paymentStatus Filter

Type: String
Description: A string value to represent the payment status which belongs to the lifecyle of a Stripe payment.
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/_fetchlistsys_listingpayment?paymentStatus=john
// Matches: "John", "Johnny", "johnson", "McJohn", etc.

// Find records with multiple values (use multiple parameters)
GET /v1/_fetchlistsys_listingpayment?paymentStatus=laptop&paymentStatus=phone&paymentStatus=tablet
// Matches records containing "laptop", "phone", or "tablet" anywhere in the field

// Find records without this field
GET /v1/_fetchlistsys_listingpayment?paymentStatus=null

statusLiteral Filter

Type: String
Description: A string value to represent the logical payment status which belongs to the application lifecycle itself.
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/_fetchlistsys_listingpayment?statusLiteral=john
// Matches: "John", "Johnny", "johnson", "McJohn", etc.

// Find records with multiple values (use multiple parameters)
GET /v1/_fetchlistsys_listingpayment?statusLiteral=laptop&statusLiteral=phone&statusLiteral=tablet
// Matches records containing "laptop", "phone", or "tablet" anywhere in the field

// Find records without this field
GET /v1/_fetchlistsys_listingpayment?statusLiteral=null

redirectUrl Filter

Type: String
Description: A string value to represent return page of the frontend to show the result of the payment, this is used when the callback is made to server not the client.
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/_fetchlistsys_listingpayment?redirectUrl=john
// Matches: "John", "Johnny", "johnson", "McJohn", etc.

// Find records with multiple values (use multiple parameters)
GET /v1/_fetchlistsys_listingpayment?redirectUrl=laptop&redirectUrl=phone&redirectUrl=tablet
// Matches records containing "laptop", "phone", or "tablet" anywhere in the field

// Find records without this field
GET /v1/_fetchlistsys_listingpayment?redirectUrl=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 _fetchListSys_listingPayment 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.

{isActive:true}

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).

[ createdAt 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, socketSettings, 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 _fetchListSys_listingPayment api has 6 filter parameters available for filtering list results. See the Filter Parameters section above for detailed usage examples.

Filter Parameter Type Array Property Description
ownerId ID No An ID value to represent owner user who created the order
orderId ID No an ID value to represent the orderId which is the ID parameter of the source listing object
paymentId String No A String value to represent the paymentId which is generated on the Stripe gateway. This id may represent different objects due to the payment gateway and the chosen flow type
paymentStatus String No A string value to represent the payment status which belongs to the lifecyle of a Stripe payment.
statusLiteral String No A string value to represent the logical payment status which belongs to the application lifecycle itself.
redirectUrl String No A string value to represent return page of the frontend to show the result of the payment, this is used when the callback is made to server not the client.

REST Request

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

  axios({
    method: 'GET',
    url: '/v1/_fetchlistsys_listingpayment',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section for usage examples)
        // ownerId: '<value>' // Filter by ownerId
        // orderId: '<value>' // Filter by orderId
        // paymentId: '<value>' // Filter by paymentId
        // paymentStatus: '<value>' // Filter by paymentStatus
        // statusLiteral: '<value>' // Filter by statusLiteral
        // redirectUrl: '<value>' // Filter by redirectUrl
            }
  });

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_listingPayments 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_listingPayments",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"sys_listingPayments": [
		{
			"id": "ID",
			"ownerId": "ID",
			"orderId": "ID",
			"paymentId": "String",
			"paymentStatus": "String",
			"statusLiteral": "String",
			"redirectUrl": "String",
			"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 - _fetch Listsys_paymentcustomer

Business API Design Specification - _fetch Listsys_paymentcustomer

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 _fetchListSys_paymentCustomer 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 _fetchListSys_paymentCustomer Business API is designed to handle a list operation on the Sys_paymentCustomer data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

System API to fetch list of sys_paymentCustomer records for frontend application. Auto-generated, not visible in design.

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 _fetchListSys_paymentCustomer Business API includes a REST controller that can be triggered via the following route:

/v1/_fetchlistsys_paymentcustomer

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 _fetchListSys_paymentCustomer Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The _fetchListSys_paymentCustomer 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 _fetchListSys_paymentCustomer api supports 3 optional filter parameters for filtering list results using URL query parameters. These parameters are only available for list type APIs.

userId Filter

Type: ID
Description: An ID value to represent the user who is created as a stripe customer
Location: Query Parameter

Usage:

Non-Array Property:

Examples:

// Get records with a specific ID
GET /v1/_fetchlistsys_paymentcustomer?userId=550e8400-e29b-41d4-a716-446655440000

// Get records with multiple IDs (use multiple parameters)
GET /v1/_fetchlistsys_paymentcustomer?userId=550e8400-e29b-41d4-a716-446655440000&userId=660e8400-e29b-41d4-a716-446655440001

// Get records without this field
GET /v1/_fetchlistsys_paymentcustomer?userId=null

customerId Filter

Type: String
Description: A string value to represent the customer id which is generated on the Stripe gateway. This id is used to represent the customer in the Stripe gateway
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/_fetchlistsys_paymentcustomer?customerId=john
// Matches: "John", "Johnny", "johnson", "McJohn", etc.

// Find records with multiple values (use multiple parameters)
GET /v1/_fetchlistsys_paymentcustomer?customerId=laptop&customerId=phone&customerId=tablet
// Matches records containing "laptop", "phone", or "tablet" anywhere in the field

// Find records without this field
GET /v1/_fetchlistsys_paymentcustomer?customerId=null

platform Filter

Type: String
Description: A String value to represent payment platform which is used to make the payment. It is stripe as default. It will be used to distinguesh the payment gateways in the future.
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/_fetchlistsys_paymentcustomer?platform=john
// Matches: "John", "Johnny", "johnson", "McJohn", etc.

// Find records with multiple values (use multiple parameters)
GET /v1/_fetchlistsys_paymentcustomer?platform=laptop&platform=phone&platform=tablet
// Matches records containing "laptop", "phone", or "tablet" anywhere in the field

// Find records without this field
GET /v1/_fetchlistsys_paymentcustomer?platform=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 _fetchListSys_paymentCustomer 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.

{isActive:true}

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).

[ createdAt 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, socketSettings, 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 _fetchListSys_paymentCustomer 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
userId ID No An ID value to represent the user who is created as a stripe customer
customerId String No A string value to represent the customer id which is generated on the Stripe gateway. This id is used to represent the customer in the Stripe gateway
platform String No A String value to represent payment platform which is used to make the payment. It is stripe as default. It will be used to distinguesh the payment gateways in the future.

REST Request

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

  axios({
    method: 'GET',
    url: '/v1/_fetchlistsys_paymentcustomer',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section for usage examples)
        // userId: '<value>' // Filter by userId
        // customerId: '<value>' // Filter by customerId
        // platform: '<value>' // Filter by platform
            }
  });

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_paymentCustomers 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_paymentCustomers",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"sys_paymentCustomers": [
		{
			"id": "ID",
			"userId": "ID",
			"customerId": "String",
			"platform": "String",
			"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 - _fetch Listsys_paymentmethod

Business API Design Specification - _fetch Listsys_paymentmethod

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 _fetchListSys_paymentMethod 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 _fetchListSys_paymentMethod Business API is designed to handle a list operation on the Sys_paymentMethod data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

System API to fetch list of sys_paymentMethod records for frontend application. Auto-generated, not visible in design.

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 _fetchListSys_paymentMethod Business API includes a REST controller that can be triggered via the following route:

/v1/_fetchlistsys_paymentmethod

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 _fetchListSys_paymentMethod Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The _fetchListSys_paymentMethod 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:

Filter Parameters

The _fetchListSys_paymentMethod api supports 7 optional filter parameters for filtering list results using URL query parameters. These parameters are only available for list type APIs.

paymentMethodId Filter

Type: String
Description: A string value to represent the id of the payment method on the payment platform.
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/_fetchlistsys_paymentmethod?paymentMethodId=john
// Matches: "John", "Johnny", "johnson", "McJohn", etc.

// Find records with multiple values (use multiple parameters)
GET /v1/_fetchlistsys_paymentmethod?paymentMethodId=laptop&paymentMethodId=phone&paymentMethodId=tablet
// Matches records containing "laptop", "phone", or "tablet" anywhere in the field

// Find records without this field
GET /v1/_fetchlistsys_paymentmethod?paymentMethodId=null

userId Filter

Type: ID
Description: An ID value to represent the user who owns the payment method
Location: Query Parameter

Usage:

Non-Array Property:

Examples:

// Get records with a specific ID
GET /v1/_fetchlistsys_paymentmethod?userId=550e8400-e29b-41d4-a716-446655440000

// Get records with multiple IDs (use multiple parameters)
GET /v1/_fetchlistsys_paymentmethod?userId=550e8400-e29b-41d4-a716-446655440000&userId=660e8400-e29b-41d4-a716-446655440001

// Get records without this field
GET /v1/_fetchlistsys_paymentmethod?userId=null

customerId Filter

Type: String
Description: A string value to represent the customer id which is generated on the payment gateway.
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/_fetchlistsys_paymentmethod?customerId=john
// Matches: "John", "Johnny", "johnson", "McJohn", etc.

// Find records with multiple values (use multiple parameters)
GET /v1/_fetchlistsys_paymentmethod?customerId=laptop&customerId=phone&customerId=tablet
// Matches records containing "laptop", "phone", or "tablet" anywhere in the field

// Find records without this field
GET /v1/_fetchlistsys_paymentmethod?customerId=null

cardHolderName Filter

Type: String
Description: A string value to represent the name of the card holder. It can be different than the registered customer.
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/_fetchlistsys_paymentmethod?cardHolderName=john
// Matches: "John", "Johnny", "johnson", "McJohn", etc.

// Find records with multiple values (use multiple parameters)
GET /v1/_fetchlistsys_paymentmethod?cardHolderName=laptop&cardHolderName=phone&cardHolderName=tablet
// Matches records containing "laptop", "phone", or "tablet" anywhere in the field

// Find records without this field
GET /v1/_fetchlistsys_paymentmethod?cardHolderName=null

cardHolderZip Filter

Type: String
Description: A string value to represent the zip code of the card holder. It is used for address verification in specific countries.
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/_fetchlistsys_paymentmethod?cardHolderZip=john
// Matches: "John", "Johnny", "johnson", "McJohn", etc.

// Find records with multiple values (use multiple parameters)
GET /v1/_fetchlistsys_paymentmethod?cardHolderZip=laptop&cardHolderZip=phone&cardHolderZip=tablet
// Matches records containing "laptop", "phone", or "tablet" anywhere in the field

// Find records without this field
GET /v1/_fetchlistsys_paymentmethod?cardHolderZip=null

platform Filter

Type: String
Description: A String value to represent payment platform which teh paymentMethod belongs. It is stripe as default. It will be used to distinguesh the payment gateways in the future.
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/_fetchlistsys_paymentmethod?platform=john
// Matches: "John", "Johnny", "johnson", "McJohn", etc.

// Find records with multiple values (use multiple parameters)
GET /v1/_fetchlistsys_paymentmethod?platform=laptop&platform=phone&platform=tablet
// Matches records containing "laptop", "phone", or "tablet" anywhere in the field

// Find records without this field
GET /v1/_fetchlistsys_paymentmethod?platform=null

cardInfo Filter

Type: Object
Description: A Json value to store the card details of the payment method.
Location: Query Parameter

Usage:

Examples:

// Get records with specific value
GET /v1/_fetchlistsys_paymentmethod?cardInfo=<value>

// Get records with multiple values (use multiple parameters)
GET /v1/_fetchlistsys_paymentmethod?cardInfo=<value1>&cardInfo=<value2>

// Get records without this field
GET /v1/_fetchlistsys_paymentmethod?cardInfo=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 _fetchListSys_paymentMethod 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.

{isActive:true}

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).

[ createdAt 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, socketSettings, 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 _fetchListSys_paymentMethod api has 7 filter parameters available for filtering list results. See the Filter Parameters section above for detailed usage examples.

Filter Parameter Type Array Property Description
paymentMethodId String No A string value to represent the id of the payment method on the payment platform.
userId ID No An ID value to represent the user who owns the payment method
customerId String No A string value to represent the customer id which is generated on the payment gateway.
cardHolderName String No A string value to represent the name of the card holder. It can be different than the registered customer.
cardHolderZip String No A string value to represent the zip code of the card holder. It is used for address verification in specific countries.
platform String No A String value to represent payment platform which teh paymentMethod belongs. It is stripe as default. It will be used to distinguesh the payment gateways in the future.
cardInfo Object No A Json value to store the card details of the payment method.

REST Request

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

  axios({
    method: 'GET',
    url: '/v1/_fetchlistsys_paymentmethod',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section for usage examples)
        // paymentMethodId: '<value>' // Filter by paymentMethodId
        // userId: '<value>' // Filter by userId
        // customerId: '<value>' // Filter by customerId
        // cardHolderName: '<value>' // Filter by cardHolderName
        // cardHolderZip: '<value>' // Filter by cardHolderZip
        // platform: '<value>' // Filter by platform
        // cardInfo: '<value>' // Filter by cardInfo
            }
  });

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_paymentMethods 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_paymentMethods",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"sys_paymentMethods": [
		{
			"id": "ID",
			"paymentMethodId": "String",
			"userId": "ID",
			"customerId": "String",
			"cardHolderName": "String",
			"cardHolderZip": "String",
			"platform": "String",
			"cardInfo": "Object",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID"
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

ListingImage Service

Service Design Specification

Service Design Specification

clonesahibinden-listingimage-service documentation Version: 1.0.1

Scope

This document provides a structured architectural overview of the listingImage 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.

ListingImage Service Settings

Manages uploading, linking, ordering, and storing all images attached to classified listings. Enforces image file format, size, count, and metadata standards; supports multi-resolution handling and per-listing image count limits.

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 clonesahibinden-listingimage-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 clonesahibinden-listingimage-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
listingImage Stores metadata about each image attached to a classified listing, with enforced image count, format, size, and dimension constraints. Four separate URL fields for different resolutions. Tied to listing; managed by listing owner/admin/mod. accessProtected

listingImage Data Object

Object Overview

Description: Stores metadata about each image attached to a classified listing, with enforced image count, format, size, and dimension constraints. Four separate URL fields for different resolutions. Tied to listing; managed by listing owner/admin/mod.

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: doUpdate

The existing record will be updated with the new data.No error will be thrown.

Properties Schema

Property Type Required Description
fileSize Integer Yes Size of the image file in bytes.
fullUrl String Yes URL to a full-res processed but possibly optimized image (e.g. with max side 1600px, for gallery display).
height Float Yes Height of the original image, in pixels.
listingId ID Yes The related listing that this image belongs to.
mediumUrl String Yes URL to the medium-sized processed image version (e.g. 400x300px or similar).
mimeType String Yes MIME type of the image (e.g., image/jpeg, image/png, image/webp, image/gif).
sortOrder Integer Yes Order value for display in UI; the lowest value image is the cover/main image.
thumbnailUrl String Yes URL to the thumbnail image (small size, e.g. 120x90px).
uploadedAt Date Yes UTC timestamp when image was uploaded to platform.
url String Yes URL to the original uploaded image file (full resolution/original).
width Float Yes Width of the original image, in pixels.

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

fileSize fullUrl height listingId mediumUrl mimeType thumbnailUrl uploadedAt url width

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

fileSize fullUrl height listingId mediumUrl mimeType sortOrder thumbnailUrl url width

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

listingId sortOrder uploadedAt url

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

listingId sortOrder

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.

Cache Select Properties

listingId

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.

Relation Properties

listingId

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

Filter Properties

listingId

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

listingImage has got 6 Business APIs to manage its internal and crud logic. For the details of each business API refer to its chapter.

Edge Controllers

m2mCreateListingImage

Configuration:

REST Settings:


m2mBulkCreateListingImage

Configuration:

REST Settings:


m2mUpdateListingImageById

Configuration:

REST Settings:


m2mDeleteListingImageById

Configuration:

REST Settings:


m2mUpdateListingImageByQuery

Configuration:

REST Settings:


m2mDeleteListingImageByQuery

Configuration:

REST Settings:


m2mUpdateListingImageByIdList

Configuration:

REST Settings:



Service Library

Functions

validateImageUpload.js

// Validates image upload constraints (for create/update)
// context = API context; expects fileSize, mimeType, width, height, imageCount (if create), max images per listing = 10
const ALLOWED_MIME = ['image/jpeg','image/png','image/webp','image/gif'];
const MIN_WIDTH = 400, MIN_HEIGHT = 300, MAX_FILE_SIZE = 10 * 1024 * 1024, MAX_IMAGES = 10;
module.exports = function validateImageUpload(context) {
  // Check required file properties present
  const { fileSize, mimeType, width, height, imageCount } = context;
  if (mimeType && !ALLOWED_MIME.includes(mimeType))
    throw new Error('Unsupported image type. Allowed: JPEG, PNG, WEBP, GIF.');
  if (fileSize && fileSize > MAX_FILE_SIZE)
    throw new Error('Image file exceeds 10MB limit.');
  if (width && width < MIN_WIDTH)
    throw new Error('Image width must be at least 400px.');
  if (height && height < MIN_HEIGHT)
    throw new Error('Image height must be at least 300px.');
  // Check image count only on create
  if (typeof imageCount === 'number' && imageCount >= MAX_IMAGES)
    throw new Error('Cannot add more than 10 images per listing.');
  return true;
}

Hook Functions

No hook functions defined.

Edge Functions

m2mCreateListingImage.js

module.exports = async (request) => {
        const { createListingImage } = require("dbLayer");
        const context = { session: request.session, requestId: request.requestId };
        const data = request.body?.data || request.data || request;
        const result = await createListingImage(data, context);
        return { status: 200, content: result };
      }

m2mBulkCreateListingImage.js

module.exports = async (request) => {
        const { createBulkListingImage } = require("dbLayer");
        const context = { session: request.session, requestId: request.requestId };
        const dataList = request.body?.dataList || request.dataList || (Array.isArray(request.body) ? request.body : [request.body]);
        if (!Array.isArray(dataList) || dataList.length === 0) {
          return { status: 400, message: "dataList must be a non-empty array" };
        }
        const result = await createBulkListingImage(dataList, context);
        return { status: 200, content: result };
      }

m2mUpdateListingImageById.js

module.exports = async (request) => {
        const { updateListingImageById } = require("dbLayer");
        const context = { session: request.session, requestId: request.requestId };
        const id = request.body?.id || request.params?.id || request.id;
        const dataClause = request.body?.dataClause || request.dataClause || request.body;
        if (dataClause && dataClause.id) delete dataClause.id;
        if (!id) {
          return { status: 400, message: "ID is required" };
        }
        const result = await updateListingImageById(id, dataClause, context);
        return { status: 200, content: result };
      }

m2mDeleteListingImageById.js

module.exports = async (request) => {
        const { deleteListingImageById } = require("dbLayer");
        const context = { session: request.session, requestId: request.requestId };
        const id = request.body?.id || request.params?.id || request.id;
        if (!id) {
          return { status: 400, message: "ID is required" };
        }
        const result = await deleteListingImageById(id, context);
        return { status: 200, content: result };
      }

m2mUpdateListingImageByQuery.js

module.exports = async (request) => {
        const { updateListingImageByQuery } = require("dbLayer");
        const context = { session: request.session, requestId: request.requestId };
        const dataClause = request.body?.dataClause || request.dataClause || request.body;
        const query = request.body?.query || request.query || {};
        if (!query || typeof query !== "object" || Object.keys(query).length === 0) {
          return { status: 400, message: "Query is required and must be a non-empty object" };
        }
        const result = await updateListingImageByQuery(dataClause, query, context);
        return { status: 200, content: result };
      }

m2mDeleteListingImageByQuery.js

module.exports = async (request) => {
        const { deleteListingImageByQuery } = require("dbLayer");
        const context = { session: request.session, requestId: request.requestId };
        const query = request.body?.query || request.query || {};
        if (!query || typeof query !== "object" || Object.keys(query).length === 0) {
          return { status: 400, message: "Query is required and must be a non-empty object" };
        }
        const result = await deleteListingImageByQuery(query, context);
        return { status: 200, content: result };
      }

m2mUpdateListingImageByIdList.js

module.exports = async (request) => {
        const { updateListingImageByIdList } = require("dbLayer");
        const context = { session: request.session, requestId: request.requestId };
        const idList = request.body?.idList || request.idList || [];
        const dataClause = request.body?.dataClause || request.dataClause || request.body;
        if (dataClause && dataClause.idList) delete dataClause.idList;
        if (!Array.isArray(idList) || idList.length === 0) {
          return { status: 400, message: "idList must be a non-empty array" };
        }
        const result = await updateListingImageByIdList(idList, dataClause, context);
        return { status: 200, content: result };
      }

Templates

No templates defined.

Assets

No assets defined.

Public Assets

No public assets defined.


Event Emission


Integration Patterns

Deployment Considerations

Environment Configuration

Implementation Guidelines

Development Workflow

  1. Data Model Implementation: Generate database schema from data object definitions
  2. CRUD Route Generation: Implement auto-generated routes with custom logic
  3. Custom Logic Integration: Implement hook functions and edge functions
  4. Authentication Integration: Configure with project-level authentication
  5. Testing: Unit and integration testing for all components

Code Generation Expectations

Custom Code Integration Points

Testing Strategy

Unit Testing

Integration Testing

Performance Testing


Appendices

Data Type Reference

Type Description Storage
ID Unique identifier UUID (SQL) / ObjectID (NoSQL)
String Short text (≤255 chars) VARCHAR
Text Long-form text TEXT
Integer 32-bit whole numbers INT
Boolean True/false values BOOLEAN
Double 64-bit floating point DOUBLE
Float 32-bit floating point FLOAT
Short 16-bit integers SMALLINT
Object JSON object JSONB (PostgreSQL) / Object (MongoDB)
Date ISO 8601 timestamp TIMESTAMP
Enum Fixed numeric values SMALLINT with lookup

Enum Value Mappings

Request Locations

HTTP Methods

Edge Function Signature

async function edgeFunction(request) {
  // Custom request processing
  // Return response object or throw error
  return {
    data: {},
    status: 200,
    message: "Success"
  };
}

This document was generated from the service architecture definition and should be kept in sync with implementation changes.


REST API GUIDE

REST API GUIDE

clonesahibinden-listingimage-service

Version: 1.0.1

Manages uploading, linking, ordering, and storing all images attached to classified listings. Enforces image file format, size, count, and metadata standards; supports multi-resolution handling and per-listing image count limits.

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 ListingImage Service’s REST API. This document is designed to provide a comprehensive guide to interfacing with our ListingImage Service exclusively through RESTful API endpoints.

Intended Audience

This documentation is intended for developers and integrators who are looking to interact with the ListingImage Service via HTTP requests for purposes such as creating, updating, deleting and querying ListingImage 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 ListingImage 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 ListingImage 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 clonesahibinden-access-token
Cookie clonesahibinden-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 ListingImage 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 ListingImage 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 ListingImage 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 ListingImage 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 ListingImage 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 ListingImage 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

ListingImage 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.

ListingImage resource

Resource Definition : Stores metadata about each image attached to a classified listing, with enforced image count, format, size, and dimension constraints. Four separate URL fields for different resolutions. Tied to listing; managed by listing owner/admin/mod. ListingImage Resource Properties

Name Type Required Default Definition
fileSize Integer Size of the image file in bytes.
fullUrl String URL to a full-res processed but possibly optimized image (e.g. with max side 1600px, for gallery display).
height Float Height of the original image, in pixels.
listingId ID The related listing that this image belongs to.
mediumUrl String URL to the medium-sized processed image version (e.g. 400x300px or similar).
mimeType String MIME type of the image (e.g., image/jpeg, image/png, image/webp, image/gif).
sortOrder Integer Order value for display in UI; the lowest value image is the cover/main image.
thumbnailUrl String URL to the thumbnail image (small size, e.g. 120x90px).
uploadedAt Date UTC timestamp when image was uploaded to platform.
url String URL to the original uploaded image file (full resolution/original).
width Float Width of the original image, in pixels.

Business Api

Create Listingimage API

Create an image record attached to a listing. Enforces max 10 images per listing, allowed file types (image/jpeg, png, webp, gif), max file size (10MB), and minimum dimensions (400x300px). Only owner of related listing, admin, or moderator can add.

API Frontend Description By The Backend Architect

Show file/image upload UI, allow per-image progress and preview, error on more than 10 images, reject unsupported types/sizes/resolutions. On success, show image in gallery. Only listing owner/moderator/admin may add images.

Rest Route

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

/v1/listingimages

Rest Request Parameters

The createListingImage api has got 11 regular request parameters

Parameter Type Required Population
fileSize Integer true request.body?.[“fileSize”]
fullUrl String true request.body?.[“fullUrl”]
height Float true request.body?.[“height”]
listingId ID true request.body?.[“listingId”]
mediumUrl String true request.body?.[“mediumUrl”]
mimeType String true request.body?.[“mimeType”]
sortOrder Integer true request.body?.[“sortOrder”]
thumbnailUrl String true request.body?.[“thumbnailUrl”]
uploadedAt Date true request.body?.[“uploadedAt”]
url String true request.body?.[“url”]
width Float true request.body?.[“width”]
fileSize : Size of the image file in bytes.
fullUrl : URL to a full-res processed but possibly optimized image (e.g. with max side 1600px, for gallery display).
height : Height of the original image, in pixels.
listingId : The related listing that this image belongs to.
mediumUrl : URL to the medium-sized processed image version (e.g. 400x300px or similar).
mimeType : MIME type of the image (e.g., image/jpeg, image/png, image/webp, image/gif).
sortOrder : Order value for display in UI; the lowest value image is the cover/main image.
thumbnailUrl : URL to the thumbnail image (small size, e.g. 120x90px).
uploadedAt : UTC timestamp when image was uploaded to platform.
url : URL to the original uploaded image file (full resolution/original).
width : Width of the original image, in pixels.

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

  axios({
    method: 'POST',
    url: '/v1/listingimages',
    data: {
            fileSize:"Integer",  
            fullUrl:"String",  
            height:"Float",  
            listingId:"ID",  
            mediumUrl:"String",  
            mimeType:"String",  
            sortOrder:"Integer",  
            thumbnailUrl:"String",  
            uploadedAt:"Date",  
            url:"String",  
            width:"Float",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "listingImage",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"listingImage": {
		"id": "ID",
		"fileSize": "Integer",
		"fullUrl": "String",
		"height": "Float",
		"listingId": "ID",
		"mediumUrl": "String",
		"mimeType": "String",
		"sortOrder": "Integer",
		"thumbnailUrl": "String",
		"uploadedAt": "Date",
		"url": "String",
		"width": "Float",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Delete Listingimage API

Remove (soft delete) this image record. Only admin, moderator, or owner of related listing may take action. Image stays in database; actual asset removal is scheduled or handled in listing/bucket image service.

API Frontend Description By The Backend Architect

Provide a delete/trash icon per image. Show immediate feedback on delete (soft delete). Remove from gallery and reflow grid/order. Deletion disables but does not erase image from DB or storage bucket (handled asynchronously).

Rest Route

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

/v1/listingimages/:listingImageId

Rest Request Parameters

The deleteListingImage api has got 1 regular request parameter

Parameter Type Required Population
listingImageId ID true request.params?.[“listingImageId”]
listingImageId : 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/listingimages/:listingImageId

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

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "listingImage",
	"method": "DELETE",
	"action": "delete",
	"appVersion": "Version",
	"rowCount": 1,
	"listingImage": {
		"id": "ID",
		"fileSize": "Integer",
		"fullUrl": "String",
		"height": "Float",
		"listingId": "ID",
		"mediumUrl": "String",
		"mimeType": "String",
		"sortOrder": "Integer",
		"thumbnailUrl": "String",
		"uploadedAt": "Date",
		"url": "String",
		"width": "Float",
		"isActive": false,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Get Listingimage API

Retrieve details/metadata of one image for a listing. Publicly accessible for gallery/carousel; has no sensitive info.

API Frontend Description By The Backend Architect

Used to fetch image details (URLs for all resolutions and display order) for single-image views. All users can access listing image detail for active listings.

Rest Route

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

/v1/listingimages/:listingImageId

Rest Request Parameters

The getListingImage api has got 1 regular request parameter

Parameter Type Required Population
listingImageId ID true request.params?.[“listingImageId”]
listingImageId : 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/listingimages/:listingImageId

  axios({
    method: 'GET',
    url: `/v1/listingimages/${listingImageId}`,
    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": "listingImage",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"listingImage": {
		"isActive": true
	}
}

List Listingimages API

List all images belonging to a specific listing, sorted by sortOrder ascending. Returns up to 10 images per listing. Publicly accessible for populating image galleries.

API Frontend Description By The Backend Architect

Display all images in a listing as a gallery or carousel, sorted by sortOrder (lowest/1 is main image/cover). Maximum images per listing is 10. Used on public listing detail pages and for listing management.

Rest Route

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

/v1/listlistingimages/:listingId

Rest Request Parameters

The listListingImages api has got 1 regular request parameter

Parameter Type Required Population
listingId ID true request.query?.[“listingId”]
listingId : The related listing that this image belongs to… The parameter is used to query data.

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

  axios({
    method: 'GET',
    url: `/v1/listlistingimages/${listingId}`,
    data: {
    
    },
    params: {
             listingId:'"ID"',  
    
        }
  });

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": "listingImages",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"listingImages": [
		{
			"isActive": true
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Update Listingimage API

Update sort order or image metadata; user is limited to manipulating images of their own listings (or admins/mods). Cannot move image to another listing. Can revalidate constraints on request.

API Frontend Description By The Backend Architect

Allow user to reorder images of a listing (changing sortOrder), set another main image (sortOrder=1), or update image metadata. Show error if trying to move image between listings or violate constraints.

Rest Route

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

/v1/listingimages/:listingImageId

Rest Request Parameters

The updateListingImage api has got 2 regular request parameters

Parameter Type Required Population
listingImageId ID true request.params?.[“listingImageId”]
sortOrder Integer false request.body?.[“sortOrder”]
listingImageId : This id paremeter is used to select the required data object that will be updated
sortOrder : Order value for display in UI; the lowest value image is the cover/main image.

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

  axios({
    method: 'PATCH',
    url: `/v1/listingimages/${listingImageId}`,
    data: {
            sortOrder:"Integer",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "listingImage",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"listingImage": {
		"id": "ID",
		"fileSize": "Integer",
		"fullUrl": "String",
		"height": "Float",
		"listingId": "ID",
		"mediumUrl": "String",
		"mimeType": "String",
		"sortOrder": "Integer",
		"thumbnailUrl": "String",
		"uploadedAt": "Date",
		"url": "String",
		"width": "Float",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

_fetch Listlistingimage API

System API to fetch list of listingImage records for frontend application. Auto-generated, not visible in design.

Rest Route

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

/v1/_fetchlistlistingimage

Rest Request Parameters

Filter Parameters

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

listingId (ID): The related listing that this image belongs to.

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

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

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "listingImages",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"listingImages": [
		{
			"id": "ID",
			"fileSize": "Integer",
			"fullUrl": "String",
			"height": "Float",
			"listingId": "ID",
			"mediumUrl": "String",
			"mimeType": "String",
			"sortOrder": "Integer",
			"thumbnailUrl": "String",
			"uploadedAt": "Date",
			"url": "String",
			"width": "Float",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID",
			"listing": [
				{
					"attributes": "Object",
					"categoryId": "ID",
					"condition": "Enum",
					"condition_idx": "Integer",
					"contactEmail": "String",
					"contactPhone": "String",
					"currency": "String",
					"description": "Text",
					"expiresAt": "Date",
					"favoriteCount": "Integer",
					"isPremium": "Boolean",
					"listingType": "Enum",
					"listingType_idx": "Integer",
					"locationId": "ID",
					"_paymentConfirmation": "String",
					"premiumExpiry": "Date",
					"premiumType": "Enum",
					"premiumType_idx": "Integer",
					"price": "Double",
					"status": "Enum",
					"status_idx": "Integer",
					"subcategoryId": "ID",
					"title": "String",
					"userId": "ID",
					"viewsCount": "Integer",
					"paymentConfirmation": "Enum",
					"paymentConfirmation_idx": "Integer"
				},
				{},
				{}
			]
		},
		{},
		{}
	],
	"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

clonesahibinden-listingimage-service

Manages uploading, linking, ordering, and storing all images attached to classified listings. Enforces image file format, size, count, and metadata standards; supports multi-resolution handling and per-listing image count limits.

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 ListingImage Service Event descriptions. This guide is dedicated to detailing how to subscribe to and listen for state changes within the ListingImage Service, offering an exclusive focus on event subscription mechanisms.

Intended Audience

This documentation is aimed at developers and integrators looking to monitor ListingImage Service state changes. It is especially relevant for those wishing to implement or enhance business logic based on interactions with ListingImage 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 ListingImage 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 listingImage-created

Event topic: clonesahibinden-listingimage-service-dbevent-listingimage-created

This event is triggered upon the creation of a listingImage data object in the database. The event payload encompasses the newly created data, encapsulated within the root of the paylod.

Event payload:

{"id":"ID","fileSize":"Integer","fullUrl":"String","height":"Float","listingId":"ID","mediumUrl":"String","mimeType":"String","sortOrder":"Integer","thumbnailUrl":"String","uploadedAt":"Date","url":"String","width":"Float","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

DbEvent listingImage-updated

Event topic: clonesahibinden-listingimage-service-dbevent-listingimage-updated

Activation of this event follows the update of a listingImage data object. The payload contains the updated information under the listingImage attribute, along with the original data prior to update, labeled as old_listingImage and also you can find the old and new versions of updated-only portion of the data…

Event payload:

{
old_listingImage:{"id":"ID","fileSize":"Integer","fullUrl":"String","height":"Float","listingId":"ID","mediumUrl":"String","mimeType":"String","sortOrder":"Integer","thumbnailUrl":"String","uploadedAt":"Date","url":"String","width":"Float","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},
listingImage:{"id":"ID","fileSize":"Integer","fullUrl":"String","height":"Float","listingId":"ID","mediumUrl":"String","mimeType":"String","sortOrder":"Integer","thumbnailUrl":"String","uploadedAt":"Date","url":"String","width":"Float","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},
oldDataValues,
newDataValues
}

DbEvent listingImage-deleted

Event topic: clonesahibinden-listingimage-service-dbevent-listingimage-deleted

This event announces the deletion of a listingImage 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","fileSize":"Integer","fullUrl":"String","height":"Float","listingId":"ID","mediumUrl":"String","mimeType":"String","sortOrder":"Integer","thumbnailUrl":"String","uploadedAt":"Date","url":"String","width":"Float","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

ElasticSearch Index Events

Within the ListingImage 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 listingimage-created

Event topic: elastic-index-clonesahibinden_listingimage-created

Event payload:

{"id":"ID","fileSize":"Integer","fullUrl":"String","height":"Float","listingId":"ID","mediumUrl":"String","mimeType":"String","sortOrder":"Integer","thumbnailUrl":"String","uploadedAt":"Date","url":"String","width":"Float","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event listingimage-updated

Event topic: elastic-index-clonesahibinden_listingimage-created

Event payload:

{"id":"ID","fileSize":"Integer","fullUrl":"String","height":"Float","listingId":"ID","mediumUrl":"String","mimeType":"String","sortOrder":"Integer","thumbnailUrl":"String","uploadedAt":"Date","url":"String","width":"Float","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event listingimage-deleted

Event topic: elastic-index-clonesahibinden_listingimage-deleted

Event payload:

{"id":"ID","fileSize":"Integer","fullUrl":"String","height":"Float","listingId":"ID","mediumUrl":"String","mimeType":"String","sortOrder":"Integer","thumbnailUrl":"String","uploadedAt":"Date","url":"String","width":"Float","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event listingimage-extended

Event topic: elastic-index-clonesahibinden_listingimage-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 listingimage-created

Event topic : clonesahibinden-listingimage-service-listingimage-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 listingImage data object itself.

The following JSON included in the payload illustrates the fullest representation of the listingImage 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":"listingImage","method":"POST","action":"create","appVersion":"Version","rowCount":1,"listingImage":{"id":"ID","fileSize":"Integer","fullUrl":"String","height":"Float","listingId":"ID","mediumUrl":"String","mimeType":"String","sortOrder":"Integer","thumbnailUrl":"String","uploadedAt":"Date","url":"String","width":"Float","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event listingimage-deleted

Event topic : clonesahibinden-listingimage-service-listingimage-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 listingImage data object itself.

The following JSON included in the payload illustrates the fullest representation of the listingImage 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":"listingImage","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"listingImage":{"id":"ID","fileSize":"Integer","fullUrl":"String","height":"Float","listingId":"ID","mediumUrl":"String","mimeType":"String","sortOrder":"Integer","thumbnailUrl":"String","uploadedAt":"Date","url":"String","width":"Float","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event listingimage-updated

Event topic : clonesahibinden-listingimage-service-listingimage-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 listingImage data object itself.

The following JSON included in the payload illustrates the fullest representation of the listingImage 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":"listingImage","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"listingImage":{"id":"ID","fileSize":"Integer","fullUrl":"String","height":"Float","listingId":"ID","mediumUrl":"String","mimeType":"String","sortOrder":"Integer","thumbnailUrl":"String","uploadedAt":"Date","url":"String","width":"Float","isActive":true,"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 listingImage

Service Design Specification - Object Design for listingImage

clonesahibinden-listingimage-service documentation

Document Overview

This document outlines the object design for the listingImage model in our application. It includes details about the model’s attributes, relationships, and any specific validation or business logic that applies.

listingImage Data Object

Object Overview

Description: Stores metadata about each image attached to a classified listing, with enforced image count, format, size, and dimension constraints. Four separate URL fields for different resolutions. Tied to listing; managed by listing owner/admin/mod.

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: doUpdate

The existing record will be updated with the new data.No error will be thrown.

Properties Schema

Property Type Required Description
fileSize Integer Yes Size of the image file in bytes.
fullUrl String Yes URL to a full-res processed but possibly optimized image (e.g. with max side 1600px, for gallery display).
height Float Yes Height of the original image, in pixels.
listingId ID Yes The related listing that this image belongs to.
mediumUrl String Yes URL to the medium-sized processed image version (e.g. 400x300px or similar).
mimeType String Yes MIME type of the image (e.g., image/jpeg, image/png, image/webp, image/gif).
sortOrder Integer Yes Order value for display in UI; the lowest value image is the cover/main image.
thumbnailUrl String Yes URL to the thumbnail image (small size, e.g. 120x90px).
uploadedAt Date Yes UTC timestamp when image was uploaded to platform.
url String Yes URL to the original uploaded image file (full resolution/original).
width Float Yes Width of the original image, in pixels.

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

fileSize fullUrl height listingId mediumUrl mimeType thumbnailUrl uploadedAt url width

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

fileSize fullUrl height listingId mediumUrl mimeType sortOrder thumbnailUrl url width

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

listingId sortOrder uploadedAt url

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

listingId sortOrder

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.

Cache Select Properties

listingId

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.

Relation Properties

listingId

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

Filter Properties

listingId

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 Listingimage

Business API Design Specification - Create Listingimage

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 createListingImage 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 createListingImage Business API is designed to handle a create operation on the ListingImage data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

Create an image record attached to a listing. Enforces max 10 images per listing, allowed file types (image/jpeg, png, webp, gif), max file size (10MB), and minimum dimensions (400x300px). Only owner of related listing, admin, or moderator can add.

API Frontend Description By The Backend Architect

Show file/image upload UI, allow per-image progress and preview, error on more than 10 images, reject unsupported types/sizes/resolutions. On success, show image in gallery. Only listing owner/moderator/admin may add images.

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 createListingImage Business API includes a REST controller that can be triggered via the following route:

/v1/listingimages

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 createListingImage Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The createListingImage Business API has 12 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
listingImageId ID No - body listingImageId
Description: This id paremeter is used to create the data object with a given specific id. Leave null for automatic id.
fileSize Integer Yes - body fileSize
Description: Size of the image file in bytes.
fullUrl String Yes - body fullUrl
Description: URL to a full-res processed but possibly optimized image (e.g. with max side 1600px, for gallery display).
height Float Yes - body height
Description: Height of the original image, in pixels.
listingId ID Yes - body listingId
Description: The related listing that this image belongs to.
mediumUrl String Yes - body mediumUrl
Description: URL to the medium-sized processed image version (e.g. 400x300px or similar).
mimeType String Yes - body mimeType
Description: MIME type of the image (e.g., image/jpeg, image/png, image/webp, image/gif).
sortOrder Integer Yes - body sortOrder
Description: Order value for display in UI; the lowest value image is the cover/main image.
thumbnailUrl String Yes - body thumbnailUrl
Description: URL to the thumbnail image (small size, e.g. 120x90px).
uploadedAt Date Yes - body uploadedAt
Description: UTC timestamp when image was uploaded to platform.
url String Yes - body url
Description: URL to the original uploaded image file (full resolution/original).
width Float Yes - body width
Description: Width of the original image, in pixels.

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 createListingImage 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.listingImageId,
  fileSize: this.fileSize,
  fullUrl: this.fullUrl,
  height: this.height,
  listingId: this.listingId,
  mediumUrl: this.mediumUrl,
  mimeType: this.mimeType,
  sortOrder: this.sortOrder,
  thumbnailUrl: this.thumbnailUrl,
  uploadedAt: this.uploadedAt,
  url: this.url,
  width: this.width,
  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, socketSettings, cronSettings

[2] Action : fetchListing

Action Type: FetchObjectAction

Fetch listing to perform ownership check and enforce image constraints

class Api {
  async fetchListing() {
    // Fetch Object on childObject listing

    const userQuery = {
      $and: [{ id: this.listingId }, { isActive: true }],
    };
    const { convertUserQueryToElasticQuery } = require("common");
    const scriptQuery = convertUserQueryToElasticQuery(userQuery);

    const elasticIndex = new ElasticIndexer("listing");
    const data = await elasticIndex.getOne(scriptQuery);

    if (!data) {
      throw new NotFoundError("errMsg_FethcedObjectNotFound:listing");
    }

    return data
      ? {
          id: data["id"],
          userId: data["userId"],
        }
      : null;
  }
}

[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] 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 : countImages

Action Type: FetchStatsAction

Count current images in this listing for max image constraint

class Api {
  // Code for Fetch Stats Action
  async countImages() {
    // Fetch stats from listingImage
    const userQuery = {
      $and: [{ listingId: this.listingId }, { isActive: true }],
    };
    const statsList = ["count"];

    const { convertUserQueryToElasticQuery } = require("common");
    const scriptQuery = convertUserQueryToElasticQuery(userQuery);

    // Using Elastic Index stats
    const elasticIndex = new ElasticIndexer("listingImage");

    const aggs = {};
    const aggQuery = { query: scriptQuery, aggs: aggs };
    const aggResult = await elasticIndex.getAggregations(aggQuery);

    if (!aggResult) return null;

    return aggResult.count.value_as_string ?? aggResult.count.value;
  }
}

[7] Action : checkImageConstraints

Action Type: FunctionCallAction

Validates image file constraints (mime type, size, width/height, allowed count)

class Api {
  async checkImageConstraints() {
    try {
      return LIB.validateImageUpload(this);
    } catch (err) {
      console.error("Error in FunctionCallAction checkImageConstraints:", err);
      throw err;
    }
  }
}

[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] 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 createListingImage api has got 11 regular client parameters

Parameter Type Required Population
fileSize Integer true request.body?.[“fileSize”]
fullUrl String true request.body?.[“fullUrl”]
height Float true request.body?.[“height”]
listingId ID true request.body?.[“listingId”]
mediumUrl String true request.body?.[“mediumUrl”]
mimeType String true request.body?.[“mimeType”]
sortOrder Integer true request.body?.[“sortOrder”]
thumbnailUrl String true request.body?.[“thumbnailUrl”]
uploadedAt Date true request.body?.[“uploadedAt”]
url String true request.body?.[“url”]
width Float true request.body?.[“width”]

REST Request

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

  axios({
    method: 'POST',
    url: '/v1/listingimages',
    data: {
            fileSize:"Integer",  
            fullUrl:"String",  
            height:"Float",  
            listingId:"ID",  
            mediumUrl:"String",  
            mimeType:"String",  
            sortOrder:"Integer",  
            thumbnailUrl:"String",  
            uploadedAt:"Date",  
            url:"String",  
            width:"Float",  
    
    },
    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 listingImage 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": "listingImage",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"listingImage": {
		"id": "ID",
		"fileSize": "Integer",
		"fullUrl": "String",
		"height": "Float",
		"listingId": "ID",
		"mediumUrl": "String",
		"mimeType": "String",
		"sortOrder": "Integer",
		"thumbnailUrl": "String",
		"uploadedAt": "Date",
		"url": "String",
		"width": "Float",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Business API Design Specification - Delete Listingimage

Business API Design Specification - Delete Listingimage

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 deleteListingImage 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 deleteListingImage Business API is designed to handle a delete operation on the ListingImage data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

Remove (soft delete) this image record. Only admin, moderator, or owner of related listing may take action. Image stays in database; actual asset removal is scheduled or handled in listing/bucket image service.

API Frontend Description By The Backend Architect

Provide a delete/trash icon per image. Show immediate feedback on delete (soft delete). Remove from gallery and reflow grid/order. Deletion disables but does not erase image from DB or storage bucket (handled asynchronously).

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 deleteListingImage Business API includes a REST controller that can be triggered via the following route:

/v1/listingimages/:listingImageId

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 deleteListingImage Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The deleteListingImage 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
listingImageId ID Yes - urlpath listingImageId
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 deleteListingImage 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.

{$and:[{id:this.listingImageId},{isActive:true}]}

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, socketSettings, cronSettings

[2] Action : fetchListingForDelete

Action Type: FetchObjectAction

Fetch listing to check owner permission for image delete.

class Api {
  async fetchListingForDelete() {
    // Fetch Object on childObject listing

    const userQuery = {
      $and: [{ id: this.listingImage.listingId }, { isActive: true }],
    };
    const { convertUserQueryToElasticQuery } = require("common");
    const scriptQuery = convertUserQueryToElasticQuery(userQuery);

    const elasticIndex = new ElasticIndexer("listing");
    const data = await elasticIndex.getOne(scriptQuery);

    if (!data) {
      throw new NotFoundError("errMsg_FethcedObjectNotFound:listing");
    }

    return data
      ? {
          id: data["id"],
          userId: data["userId"],
        }
      : null;
  }
}

[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] Step : transposeParameters

Manager executes parameter transform scripts, computes derived values, and remaps objects or arrays as needed for later processing.


[5] Step : checkParameters

Manager runs built-in validations including required field checks, type enforcement, and deletion preconditions. Stops execution if validation fails.


[6] 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

[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] Step : buildOutput

Manager shapes the response payload, masks sensitive fields, and formats related cleanup results for output.


[12] Step : sendResponse

Manager delivers the response to the client and finalizes any temporary internal structures.


[13] 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 deleteListingImage api has got 1 regular client parameter

Parameter Type Required Population
listingImageId ID true request.params?.[“listingImageId”]

REST Request

To access the api you can use the REST controller with the path DELETE /v1/listingimages/:listingImageId

  axios({
    method: 'DELETE',
    url: `/v1/listingimages/${listingImageId}`,
    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 listingImage 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": "listingImage",
	"method": "DELETE",
	"action": "delete",
	"appVersion": "Version",
	"rowCount": 1,
	"listingImage": {
		"id": "ID",
		"fileSize": "Integer",
		"fullUrl": "String",
		"height": "Float",
		"listingId": "ID",
		"mediumUrl": "String",
		"mimeType": "String",
		"sortOrder": "Integer",
		"thumbnailUrl": "String",
		"uploadedAt": "Date",
		"url": "String",
		"width": "Float",
		"isActive": false,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Business API Design Specification - Get Listingimage

Business API Design Specification - Get Listingimage

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 getListingImage 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 getListingImage Business API is designed to handle a get operation on the ListingImage data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

Retrieve details/metadata of one image for a listing. Publicly accessible for gallery/carousel; has no sensitive info.

API Frontend Description By The Backend Architect

Used to fetch image details (URLs for all resolutions and display order) for single-image views. All users can access listing image detail for active listings.

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 getListingImage Business API includes a REST controller that can be triggered via the following route:

/v1/listingimages/:listingImageId

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 getListingImage Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The getListingImage 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
listingImageId ID Yes - urlpath listingImageId
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 getListingImage 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,listingId,url,thumbnailUrl,mediumUrl,fullUrl,sortOrder,fileSize,mimeType,width,height,uploadedAt

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.

{$and:[{id:this.listingImageId},{isActive:true}]}

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, socketSettings, 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 getListingImage api has got 1 regular client parameter

Parameter Type Required Population
listingImageId ID true request.params?.[“listingImageId”]

REST Request

To access the api you can use the REST controller with the path GET /v1/listingimages/:listingImageId

  axios({
    method: 'GET',
    url: `/v1/listingimages/${listingImageId}`,
    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 listingImage 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": "listingImage",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"listingImage": {
		"isActive": true
	}
}

Business API Design Specification - List Listingimages

Business API Design Specification - List Listingimages

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 listListingImages 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 listListingImages Business API is designed to handle a list operation on the ListingImage 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 images belonging to a specific listing, sorted by sortOrder ascending. Returns up to 10 images per listing. Publicly accessible for populating image galleries.

API Frontend Description By The Backend Architect

Display all images in a listing as a gallery or carousel, sorted by sortOrder (lowest/1 is main image/cover). Maximum images per listing is 10. Used on public listing detail pages and for listing management.

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 listListingImages Business API includes a REST controller that can be triggered via the following route:

/v1/listlistingimages/:listingId

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 listListingImages Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The listListingImages 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
listingId ID Yes - query listingId
Description: The related listing that this image belongs to… The parameter is used to query data.

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 listListingImages 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,listingId,url,thumbnailUrl,mediumUrl,fullUrl,sortOrder,fileSize,mimeType,width,height,uploadedAt

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.

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.

{$and:[{listingId:{"$eq":this.listingId}},{isActive:true}]}

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).

[ sortOrder 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, socketSettings, 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 listListingImages api has got 1 regular client parameter

Parameter Type Required Population
listingId ID true request.query?.[“listingId”]

REST Request

To access the api you can use the REST controller with the path GET /v1/listlistingimages/:listingId

  axios({
    method: 'GET',
    url: `/v1/listlistingimages/${listingId}`,
    data: {
    
    },
    params: {
             listingId:'"ID"',  
    
        }
  });

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 listingImages 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": "listingImages",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"listingImages": [
		{
			"isActive": true
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Business API Design Specification - Update Listingimage

Business API Design Specification - Update Listingimage

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 updateListingImage 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 updateListingImage Business API is designed to handle a update operation on the ListingImage data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

Update sort order or image metadata; user is limited to manipulating images of their own listings (or admins/mods). Cannot move image to another listing. Can revalidate constraints on request.

API Frontend Description By The Backend Architect

Allow user to reorder images of a listing (changing sortOrder), set another main image (sortOrder=1), or update image metadata. Show error if trying to move image between listings or violate constraints.

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 updateListingImage Business API includes a REST controller that can be triggered via the following route:

/v1/listingimages/:listingImageId

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 updateListingImage Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The updateListingImage 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
listingImageId ID Yes - urlpath listingImageId
Description: This id paremeter is used to select the required data object that will be updated
sortOrder Integer No - body sortOrder
Description: Order value for display in UI; the lowest value image is the cover/main image.

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 updateListingImage 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.

{$and:[{id:this.listingImageId},{isActive:true}]}

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.

{
  sortOrder: this.sortOrder,
}

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, socketSettings, cronSettings

[2] Action : fetchListingForUpdate

Action Type: FetchObjectAction

Ensure only owner/admin/mod may update order/metadata.

class Api {
  async fetchListingForUpdate() {
    // Fetch Object on childObject listing

    const userQuery = {
      $and: [{ id: this.listingImage.listingId }, { isActive: true }],
    };
    const { convertUserQueryToElasticQuery } = require("common");
    const scriptQuery = convertUserQueryToElasticQuery(userQuery);

    const elasticIndex = new ElasticIndexer("listing");
    const data = await elasticIndex.getOne(scriptQuery);

    if (!data) {
      throw new NotFoundError("errMsg_FethcedObjectNotFound:listing");
    }

    return data
      ? {
          id: data["id"],
          userId: data["userId"],
        }
      : null;
  }
}

[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 : checkImageConstraintsUpdate

Action Type: FunctionCallAction

Validates any updated image field constraints (if image file is swapped or metadata changed).

class Api {
  async checkImageConstraintsUpdate() {
    try {
      return LIB.validateImageUpload(this);
    } catch (err) {
      console.error(
        "Error in FunctionCallAction checkImageConstraintsUpdate:",
        err,
      );
      throw err;
    }
  }
}

[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 updateListingImage api has got 2 regular client parameters

Parameter Type Required Population
listingImageId ID true request.params?.[“listingImageId”]
sortOrder Integer false request.body?.[“sortOrder”]

REST Request

To access the api you can use the REST controller with the path PATCH /v1/listingimages/:listingImageId

  axios({
    method: 'PATCH',
    url: `/v1/listingimages/${listingImageId}`,
    data: {
            sortOrder:"Integer",  
    
    },
    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 listingImage 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": "listingImage",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"listingImage": {
		"id": "ID",
		"fileSize": "Integer",
		"fullUrl": "String",
		"height": "Float",
		"listingId": "ID",
		"mediumUrl": "String",
		"mimeType": "String",
		"sortOrder": "Integer",
		"thumbnailUrl": "String",
		"uploadedAt": "Date",
		"url": "String",
		"width": "Float",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Business API Design Specification - _fetch Listlistingimage

Business API Design Specification - _fetch Listlistingimage

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 _fetchListListingImage 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 _fetchListListingImage Business API is designed to handle a list operation on the ListingImage data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

System API to fetch list of listingImage records for frontend application. Auto-generated, not visible in design.

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 _fetchListListingImage Business API includes a REST controller that can be triggered via the following route:

/v1/_fetchlistlistingimage

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 _fetchListListingImage Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The _fetchListListingImage 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 _fetchListListingImage api supports 1 optional filter parameter for filtering list results using URL query parameters. These parameters are only available for list type APIs.

listingId Filter

Type: ID
Description: The related listing that this image belongs to.
Location: Query Parameter

Usage:

Non-Array Property:

Examples:

// Get records with a specific ID
GET /v1/_fetchlistlistingimage?listingId=550e8400-e29b-41d4-a716-446655440000

// Get records with multiple IDs (use multiple parameters)
GET /v1/_fetchlistlistingimage?listingId=550e8400-e29b-41d4-a716-446655440000&listingId=660e8400-e29b-41d4-a716-446655440001

// Get records without this field
GET /v1/_fetchlistlistingimage?listingId=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 _fetchListListingImage 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.

{isActive:true}

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).

[ createdAt 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, socketSettings, 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 _fetchListListingImage 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
listingId ID No The related listing that this image belongs to.

REST Request

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

  axios({
    method: 'GET',
    url: '/v1/_fetchlistlistingimage',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section for usage examples)
        // listingId: '<value>' // Filter by listingId
            }
  });

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 listingImages 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": "listingImages",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"listingImages": [
		{
			"id": "ID",
			"fileSize": "Integer",
			"fullUrl": "String",
			"height": "Float",
			"listingId": "ID",
			"mediumUrl": "String",
			"mimeType": "String",
			"sortOrder": "Integer",
			"thumbnailUrl": "String",
			"uploadedAt": "Date",
			"url": "String",
			"width": "Float",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID",
			"listing": [
				{
					"attributes": "Object",
					"categoryId": "ID",
					"condition": "Enum",
					"condition_idx": "Integer",
					"contactEmail": "String",
					"contactPhone": "String",
					"currency": "String",
					"description": "Text",
					"expiresAt": "Date",
					"favoriteCount": "Integer",
					"isPremium": "Boolean",
					"listingType": "Enum",
					"listingType_idx": "Integer",
					"locationId": "ID",
					"_paymentConfirmation": "String",
					"premiumExpiry": "Date",
					"premiumType": "Enum",
					"premiumType_idx": "Integer",
					"price": "Double",
					"status": "Enum",
					"status_idx": "Integer",
					"subcategoryId": "ID",
					"title": "String",
					"userId": "ID",
					"viewsCount": "Integer",
					"paymentConfirmation": "Enum",
					"paymentConfirmation_idx": "Integer"
				},
				{},
				{}
			]
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Payment Service

Service Design Specification

Service Design Specification

clonesahibinden-payment-service documentation Version: 1.0.2

Scope

This document provides a structured architectural overview of the payment 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.

Payment Service Settings

Handles Stripe payment flow for one-time premium upgrades on classified listings. Creates and tracks payment transactions, manages Stripe Checkout session and webhooks, and notifies the listing service to update premium status. Exposes payment history endpoints for users and reconciliation for admin.

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 clonesahibinden-payment-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 clonesahibinden-payment-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
paymentTransaction Represents a Stripe-based payment for a one-time premium listing upgrade. Linked to user and listing, with payment metadata, premium details, status, and Stripe reconciliation fields. Immutable except for webhook-driven status updates. accessPrivate

paymentTransaction Data Object

Object Overview

Description: Represents a Stripe-based payment for a one-time premium listing upgrade. Linked to user and listing, with payment metadata, premium details, status, and Stripe reconciliation fields. Immutable except for webhook-driven status updates.

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
amount Double Yes Payment amount for selected premiumType, in target currency.
currency String Yes Currency in ISO-4217 format (e.g., 'TRY','USD') used for Stripe checkout.
listingId ID Yes Target classified listing being upgraded to premium.
paymentConfirmedAt Date No Date/time when payment was confirmed and premium was granted. Null if never successful/aborted.
premiumType Enum Yes Premium upgrade package: bronze, silver, gold (matches frontend/listing options).
status Enum Yes Status of payment: pending, awaiting_confirmation (stripe checkout created, awaiting webhook), success (confirmed), failed (declined or errored), canceled (user canceled).
stripeEventId String No Last Stripe event webhook ID processed for this payment (used for double-spend/deduplication of webhook).
stripeSessionId String No Stripe Checkout Session ID associated with this payment (used for reconciling gateway callbacks).
userId ID Yes User (buyer) who made the payment (auth:user)

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

amount currency listingId premiumType 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

amount currency listingId paymentConfirmedAt premiumType status stripeEventId stripeSessionId 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.

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

listingId paymentConfirmedAt premiumType status 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

listingId premiumType status stripeEventId stripeSessionId 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.

Relation Properties

listingId 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.

Filter Properties

listingId paymentConfirmedAt premiumType status 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 Logic

payment has got 5 Business APIs to manage its internal and crud logic. For the details of each business API refer to its chapter.

Edge Controllers

m2mCreatePaymentTransaction

Configuration:

REST Settings:


m2mBulkCreatePaymentTransaction

Configuration:

REST Settings:


m2mUpdatePaymentTransactionById

Configuration:

REST Settings:


m2mDeletePaymentTransactionById

Configuration:

REST Settings:


m2mUpdatePaymentTransactionByQuery

Configuration:

REST Settings:


m2mDeletePaymentTransactionByQuery

Configuration:

REST Settings:


m2mUpdatePaymentTransactionByIdList

Configuration:

REST Settings:



Service Library

Functions

getPremiumPrice.js

// Returns an object with .amount (Double) and .currency (String) for a given premiumType
// You can swap out the switch below for config/db lookup for real apps
module.exports = function getPremiumPrice(premiumType) {
  switch (premiumType) {
    case 'bronze': return { amount: 59.0, currency: 'TRY' };
    case 'silver': return { amount: 129.0, currency: 'TRY' };
    case 'gold': return { amount: 249.0, currency: 'TRY' };
    default: throw new Error('Unknown premiumType: '+premiumType);
  }
};

getPremiumDuration.js

// Returns duration in days (integer) for each premium type (example: bronze - 7 days, silver - 15, gold - 30)
module.exports = function getPremiumDuration(premiumType) {
  switch (premiumType) {
    case 'bronze': return 7;
    case 'silver': return 15;
    case 'gold': return 30;
    default: return 7;
  }
};

verifyStripeSignature.js

// Use Stripe SDK to validate webhook signature
// You must set process.env.STRIPE_WEBHOOK_SECRET in your environment
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);
module.exports = function verifyStripeSignature(rawBody, stripeSignature) {
  try {
    stripe.webhooks.constructEvent(rawBody, stripeSignature, process.env.STRIPE_WEBHOOK_SECRET);
    return true;
  } catch (err) {
    return false;
  }
};

getStripeEventType.js

// Extract event type from Stripe webhook payload (raw JSON string)
module.exports = function getStripeEventType(rawBody) {
  const obj = typeof rawBody === 'string' ? JSON.parse(rawBody) : rawBody;
  return obj.type;
};

getStripeSessionId.js

// Extract session ID from webhook payload (for 'checkout.session.completed' event)
module.exports = function getStripeSessionId(rawBody) {
  const obj = typeof rawBody === 'string' ? JSON.parse(rawBody) : rawBody;
  return obj.data && obj.data.object && obj.data.object.id ? obj.data.object.id : null;
};

getStripeEventId.js

module.exports = function getStripeEventId(rawBody) { const obj = typeof rawBody === 'string' ? JSON.parse(rawBody) : rawBody; return obj.id; };

findPaymentByStripeSessionId.js

const { getPaymentTransactionByQuery } = require('dbLayer');
module.exports = async function findPaymentByStripeSessionId(sessionId) {
  // status checks left to workflow
  return await getPaymentTransactionByQuery({ stripeSessionId: sessionId });
};

Hook Functions

No hook functions defined.

Edge Functions

m2mCreatePaymentTransaction.js

module.exports = async (request) => {
        const { createPaymentTransaction } = require("dbLayer");
        const context = { session: request.session, requestId: request.requestId };
        const data = request.body?.data || request.data || request;
        const result = await createPaymentTransaction(data, context);
        return { status: 200, content: result };
      }

m2mBulkCreatePaymentTransaction.js

module.exports = async (request) => {
        const { createBulkPaymentTransaction } = require("dbLayer");
        const context = { session: request.session, requestId: request.requestId };
        const dataList = request.body?.dataList || request.dataList || (Array.isArray(request.body) ? request.body : [request.body]);
        if (!Array.isArray(dataList) || dataList.length === 0) {
          return { status: 400, message: "dataList must be a non-empty array" };
        }
        const result = await createBulkPaymentTransaction(dataList, context);
        return { status: 200, content: result };
      }

m2mUpdatePaymentTransactionById.js

module.exports = async (request) => {
        const { updatePaymentTransactionById } = require("dbLayer");
        const context = { session: request.session, requestId: request.requestId };
        const id = request.body?.id || request.params?.id || request.id;
        const dataClause = request.body?.dataClause || request.dataClause || request.body;
        if (dataClause && dataClause.id) delete dataClause.id;
        if (!id) {
          return { status: 400, message: "ID is required" };
        }
        const result = await updatePaymentTransactionById(id, dataClause, context);
        return { status: 200, content: result };
      }

m2mDeletePaymentTransactionById.js

module.exports = async (request) => {
        const { deletePaymentTransactionById } = require("dbLayer");
        const context = { session: request.session, requestId: request.requestId };
        const id = request.body?.id || request.params?.id || request.id;
        if (!id) {
          return { status: 400, message: "ID is required" };
        }
        const result = await deletePaymentTransactionById(id, context);
        return { status: 200, content: result };
      }

m2mUpdatePaymentTransactionByQuery.js

module.exports = async (request) => {
        const { updatePaymentTransactionByQuery } = require("dbLayer");
        const context = { session: request.session, requestId: request.requestId };
        const dataClause = request.body?.dataClause || request.dataClause || request.body;
        const query = request.body?.query || request.query || {};
        if (!query || typeof query !== "object" || Object.keys(query).length === 0) {
          return { status: 400, message: "Query is required and must be a non-empty object" };
        }
        const result = await updatePaymentTransactionByQuery(dataClause, query, context);
        return { status: 200, content: result };
      }

m2mDeletePaymentTransactionByQuery.js

module.exports = async (request) => {
        const { deletePaymentTransactionByQuery } = require("dbLayer");
        const context = { session: request.session, requestId: request.requestId };
        const query = request.body?.query || request.query || {};
        if (!query || typeof query !== "object" || Object.keys(query).length === 0) {
          return { status: 400, message: "Query is required and must be a non-empty object" };
        }
        const result = await deletePaymentTransactionByQuery(query, context);
        return { status: 200, content: result };
      }

m2mUpdatePaymentTransactionByIdList.js

module.exports = async (request) => {
        const { updatePaymentTransactionByIdList } = require("dbLayer");
        const context = { session: request.session, requestId: request.requestId };
        const idList = request.body?.idList || request.idList || [];
        const dataClause = request.body?.dataClause || request.dataClause || request.body;
        if (dataClause && dataClause.idList) delete dataClause.idList;
        if (!Array.isArray(idList) || idList.length === 0) {
          return { status: 400, message: "idList must be a non-empty array" };
        }
        const result = await updatePaymentTransactionByIdList(idList, dataClause, context);
        return { status: 200, content: result };
      }

Templates

No templates defined.

Assets

No assets defined.

Public Assets

No public assets defined.


Event Emission


Integration Patterns

Deployment Considerations

Environment Configuration

Implementation Guidelines

Development Workflow

  1. Data Model Implementation: Generate database schema from data object definitions
  2. CRUD Route Generation: Implement auto-generated routes with custom logic
  3. Custom Logic Integration: Implement hook functions and edge functions
  4. Authentication Integration: Configure with project-level authentication
  5. Testing: Unit and integration testing for all components

Code Generation Expectations

Custom Code Integration Points

Testing Strategy

Unit Testing

Integration Testing

Performance Testing


Appendices

Data Type Reference

Type Description Storage
ID Unique identifier UUID (SQL) / ObjectID (NoSQL)
String Short text (≤255 chars) VARCHAR
Text Long-form text TEXT
Integer 32-bit whole numbers INT
Boolean True/false values BOOLEAN
Double 64-bit floating point DOUBLE
Float 32-bit floating point FLOAT
Short 16-bit integers SMALLINT
Object JSON object JSONB (PostgreSQL) / Object (MongoDB)
Date ISO 8601 timestamp TIMESTAMP
Enum Fixed numeric values SMALLINT with lookup

Enum Value Mappings

Request Locations

HTTP Methods

Edge Function Signature

async function edgeFunction(request) {
  // Custom request processing
  // Return response object or throw error
  return {
    data: {},
    status: 200,
    message: "Success"
  };
}

This document was generated from the service architecture definition and should be kept in sync with implementation changes.


REST API GUIDE

REST API GUIDE

clonesahibinden-payment-service

Version: 1.0.2

Handles Stripe payment flow for one-time premium upgrades on classified listings. Creates and tracks payment transactions, manages Stripe Checkout session and webhooks, and notifies the listing service to update premium status. Exposes payment history endpoints for users and reconciliation for admin.

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 Payment Service’s REST API. This document is designed to provide a comprehensive guide to interfacing with our Payment Service exclusively through RESTful API endpoints.

Intended Audience

This documentation is intended for developers and integrators who are looking to interact with the Payment Service via HTTP requests for purposes such as creating, updating, deleting and querying Payment 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 Payment 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 Payment 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 clonesahibinden-access-token
Cookie clonesahibinden-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 Payment 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 Payment 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 Payment 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 Payment 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 Payment 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 Payment 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

Payment 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.

PaymentTransaction resource

Resource Definition : Represents a Stripe-based payment for a one-time premium listing upgrade. Linked to user and listing, with payment metadata, premium details, status, and Stripe reconciliation fields. Immutable except for webhook-driven status updates. PaymentTransaction Resource Properties

Name Type Required Default Definition
amount Double Payment amount for selected premiumType, in target currency.
currency String Currency in ISO-4217 format (e.g., 'TRY','USD') used for Stripe checkout.
listingId ID Target classified listing being upgraded to premium.
paymentConfirmedAt Date Date/time when payment was confirmed and premium was granted. Null if never successful/aborted.
premiumType Enum Premium upgrade package: bronze, silver, gold (matches frontend/listing options).
status Enum Status of payment: pending, awaiting_confirmation (stripe checkout created, awaiting webhook), success (confirmed), failed (declined or errored), canceled (user canceled).
stripeEventId String Last Stripe event webhook ID processed for this payment (used for double-spend/deduplication of webhook).
stripeSessionId String Stripe Checkout Session ID associated with this payment (used for reconciling gateway callbacks).
userId ID User (buyer) who made the payment (auth:user)

Enum Properties

Enum properties are represented as strings in the database. The values are mapped to their corresponding names in the application layer.

premiumType Enum Property

Property Definition : Premium upgrade package: bronze, silver, gold (matches frontend/listing options).Enum Options

Name Value Index
bronze "bronze"" 0
silver "silver"" 1
gold "gold"" 2
status Enum Property

Property Definition : Status of payment: pending, awaiting_confirmation (stripe checkout created, awaiting webhook), success (confirmed), failed (declined or errored), canceled (user canceled).Enum Options

Name Value Index
pending "pending"" 0
awaiting_confirmation "awaiting_confirmation"" 1
success "success"" 2
failed "failed"" 3
canceled "canceled"" 4

Business Api

Create Paymenttransaction API

Create a paymentTransaction to initiate a Stripe Checkout for premium upgrade on a listing. Checks listing and user, prevents duplicate active payments, creates transaction with status=‘pending’, triggers Stripe checkout, and returns checkout session URL/info.

API Frontend Description By The Backend Architect

Initiate Premium Payment

Rest Route

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

/v1/payments/create

Rest Request Parameters

The createPaymentTransaction api has got 2 regular request parameters

Parameter Type Required Population
listingId ID true request.body?.[“listingId”]
premiumType String true request.body?.[“premiumType”]
listingId : ID of the listing to upgrade to premium
premiumType : PremiumType to purchase (‘bronze’, ‘silver’, ‘gold’)

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

  axios({
    method: 'POST',
    url: '/v1/payments/create',
    data: {
            listingId:"ID",  
            premiumType:"String",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "paymentTransaction",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"paymentTransaction": {
		"id": "ID",
		"amount": "Double",
		"currency": "String",
		"listingId": "ID",
		"paymentConfirmedAt": "Date",
		"premiumType": "Enum",
		"premiumType_idx": "Integer",
		"status": "Enum",
		"status_idx": "Integer",
		"stripeEventId": "String",
		"stripeSessionId": "String",
		"userId": "ID",
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"isActive": true
	},
	"paymentResult": {
		"paymentTicketId": "ID",
		"orderId": "ID",
		"paymentId": "String",
		"paymentStatus": "Enum",
		"paymentIntentInfo": "Object",
		"statusLiteral": "String",
		"amount": "Double",
		"currency": "String",
		"success": true,
		"description": "String",
		"metadata": "Object",
		"paymentUserParams": "Object"
	}
}

Get Paymenttransaction API

Retrieve a paymentTransaction by ID. Only owner or admin may access. Used for order confirmation display, receipt, etc.

API Frontend Description By The Backend Architect

Rest Route

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

/v1/payments/:id

Rest Request Parameters

The getPaymentTransaction api has got 2 regular request parameters

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

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

  axios({
    method: 'GET',
    url: `/v1/payments/${id}`,
    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": "paymentTransaction",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"paymentTransaction": {
		"listingInfo": {
			"categoryId": "ID",
			"isPremium": "Boolean",
			"premiumExpiry": "Date",
			"premiumType": "Enum",
			"premiumType_idx": "Integer",
			"subcategoryId": "ID",
			"title": "String"
		},
		"isActive": true
	}
}

List Paymenttransactions API

List all paymentTransactions for current user, paginated. Admin can query all users. Used for user payment history and admin reconciliation.

API Frontend Description By The Backend Architect

Rest Route

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

/v1/payments

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

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

  axios({
    method: 'GET',
    url: '/v1/payments',
    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": "paymentTransactions",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"paymentTransactions": [
		{
			"listingInfo": [
				{
					"categoryId": "ID",
					"isPremium": "Boolean",
					"premiumExpiry": "Date",
					"premiumType": "Enum",
					"premiumType_idx": "Integer",
					"subcategoryId": "ID",
					"title": "String"
				},
				{},
				{}
			],
			"isActive": true
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Stripe Webhookcallback API

Receives Stripe webhook events, updates corresponding paymentTransaction (status, confirmation), triggers listing premium upgrade via interservice call. Only accepts trusted Stripe event payloads. No login required.

API Frontend Description By The Backend Architect

Rest Route

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

/v1/payments/webhook

Rest Request Parameters

The stripeWebhookCallback api has got 1 regular request parameter

Parameter Type Required Population
paymentTransactionId ID true request.params?.[“paymentTransactionId”]
paymentTransactionId : 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 POST /v1/payments/webhook

  axios({
    method: 'POST',
    url: '/v1/payments/webhook',
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "paymentTransaction",
	"method": "POST",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"paymentTransaction": {
		"id": "ID",
		"amount": "Double",
		"currency": "String",
		"listingId": "ID",
		"paymentConfirmedAt": "Date",
		"premiumType": "Enum",
		"premiumType_idx": "Integer",
		"status": "Enum",
		"status_idx": "Integer",
		"stripeEventId": "String",
		"stripeSessionId": "String",
		"userId": "ID",
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"isActive": true
	}
}

_fetch Listpaymenttransaction API

System API to fetch list of paymentTransaction records for frontend application. Auto-generated, not visible in design.

Rest Route

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

/v1/_fetchlistpaymenttransaction

Rest Request Parameters

Filter Parameters

The _fetchListPaymentTransaction api supports 5 optional filter parameters for filtering list results:

listingId (ID): Target classified listing being upgraded to premium.

paymentConfirmedAt (Date): Date/time when payment was confirmed and premium was granted. Null if never successful/aborted.

premiumType (Enum): Premium upgrade package: bronze, silver, gold (matches frontend/listing options).

status (Enum): Status of payment: pending, awaiting_confirmation (stripe checkout created, awaiting webhook), success (confirmed), failed (declined or errored), canceled (user canceled).

userId (ID): User (buyer) who made the payment (auth:user)

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

  axios({
    method: 'GET',
    url: '/v1/_fetchlistpaymenttransaction',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section above)
        // listingId: '<value>' // Filter by listingId
        // paymentConfirmedAt: '<value>' // Filter by paymentConfirmedAt
        // premiumType: '<value>' // Filter by premiumType
        // status: '<value>' // Filter by status
        // 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": "paymentTransactions",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"paymentTransactions": [
		{
			"id": "ID",
			"amount": "Double",
			"currency": "String",
			"listingId": "ID",
			"paymentConfirmedAt": "Date",
			"premiumType": "Enum",
			"premiumType_idx": "Integer",
			"status": "Enum",
			"status_idx": "Integer",
			"stripeEventId": "String",
			"stripeSessionId": "String",
			"userId": "ID",
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID",
			"listing": [
				{
					"attributes": "Object",
					"categoryId": "ID",
					"condition": "Enum",
					"condition_idx": "Integer",
					"contactEmail": "String",
					"contactPhone": "String",
					"currency": "String",
					"description": "Text",
					"expiresAt": "Date",
					"favoriteCount": "Integer",
					"isPremium": "Boolean",
					"listingType": "Enum",
					"listingType_idx": "Integer",
					"locationId": "ID",
					"_paymentConfirmation": "String",
					"premiumExpiry": "Date",
					"premiumType": "Enum",
					"premiumType_idx": "Integer",
					"price": "Double",
					"status": "Enum",
					"status_idx": "Integer",
					"subcategoryId": "ID",
					"title": "String",
					"userId": "ID",
					"viewsCount": "Integer",
					"paymentConfirmation": "Enum",
					"paymentConfirmation_idx": "Integer"
				},
				{},
				{}
			],
			"buyer": [
				{
					"fullname": "String"
				},
				{},
				{}
			],
			"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

clonesahibinden-payment-service

Handles Stripe payment flow for one-time premium upgrades on classified listings. Creates and tracks payment transactions, manages Stripe Checkout session and webhooks, and notifies the listing service to update premium status. Exposes payment history endpoints for users and reconciliation for admin.

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 Payment Service Event descriptions. This guide is dedicated to detailing how to subscribe to and listen for state changes within the Payment Service, offering an exclusive focus on event subscription mechanisms.

Intended Audience

This documentation is aimed at developers and integrators looking to monitor Payment Service state changes. It is especially relevant for those wishing to implement or enhance business logic based on interactions with Payment 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 Payment 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 paymentTransaction-created

Event topic: clonesahibinden-payment-service-dbevent-paymenttransaction-created

This event is triggered upon the creation of a paymentTransaction data object in the database. The event payload encompasses the newly created data, encapsulated within the root of the paylod.

Event payload:

{"id":"ID","amount":"Double","currency":"String","listingId":"ID","paymentConfirmedAt":"Date","premiumType":"Enum","premiumType_idx":"Integer","status":"Enum","status_idx":"Integer","stripeEventId":"String","stripeSessionId":"String","userId":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

DbEvent paymentTransaction-updated

Event topic: clonesahibinden-payment-service-dbevent-paymenttransaction-updated

Activation of this event follows the update of a paymentTransaction data object. The payload contains the updated information under the paymentTransaction attribute, along with the original data prior to update, labeled as old_paymentTransaction and also you can find the old and new versions of updated-only portion of the data…

Event payload:

{
old_paymentTransaction:{"id":"ID","amount":"Double","currency":"String","listingId":"ID","paymentConfirmedAt":"Date","premiumType":"Enum","premiumType_idx":"Integer","status":"Enum","status_idx":"Integer","stripeEventId":"String","stripeSessionId":"String","userId":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},
paymentTransaction:{"id":"ID","amount":"Double","currency":"String","listingId":"ID","paymentConfirmedAt":"Date","premiumType":"Enum","premiumType_idx":"Integer","status":"Enum","status_idx":"Integer","stripeEventId":"String","stripeSessionId":"String","userId":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},
oldDataValues,
newDataValues
}

DbEvent paymentTransaction-deleted

Event topic: clonesahibinden-payment-service-dbevent-paymenttransaction-deleted

This event announces the deletion of a paymentTransaction 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","amount":"Double","currency":"String","listingId":"ID","paymentConfirmedAt":"Date","premiumType":"Enum","premiumType_idx":"Integer","status":"Enum","status_idx":"Integer","stripeEventId":"String","stripeSessionId":"String","userId":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":false}

ElasticSearch Index Events

Within the Payment 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 paymenttransaction-created

Event topic: elastic-index-clonesahibinden_paymenttransaction-created

Event payload:

{"id":"ID","amount":"Double","currency":"String","listingId":"ID","paymentConfirmedAt":"Date","premiumType":"Enum","premiumType_idx":"Integer","status":"Enum","status_idx":"Integer","stripeEventId":"String","stripeSessionId":"String","userId":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event paymenttransaction-updated

Event topic: elastic-index-clonesahibinden_paymenttransaction-created

Event payload:

{"id":"ID","amount":"Double","currency":"String","listingId":"ID","paymentConfirmedAt":"Date","premiumType":"Enum","premiumType_idx":"Integer","status":"Enum","status_idx":"Integer","stripeEventId":"String","stripeSessionId":"String","userId":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event paymenttransaction-deleted

Event topic: elastic-index-clonesahibinden_paymenttransaction-deleted

Event payload:

{"id":"ID","amount":"Double","currency":"String","listingId":"ID","paymentConfirmedAt":"Date","premiumType":"Enum","premiumType_idx":"Integer","status":"Enum","status_idx":"Integer","stripeEventId":"String","stripeSessionId":"String","userId":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event paymenttransaction-extended

Event topic: elastic-index-clonesahibinden_paymenttransaction-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 paymenttransaction-created

Event topic : clonesahibinden-payment-service-paymenttransaction-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 paymentTransaction data object itself.

The following JSON included in the payload illustrates the fullest representation of the paymentTransaction 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":"paymentTransaction","method":"POST","action":"create","appVersion":"Version","rowCount":1,"paymentTransaction":{"id":"ID","amount":"Double","currency":"String","listingId":"ID","paymentConfirmedAt":"Date","premiumType":"Enum","premiumType_idx":"Integer","status":"Enum","status_idx":"Integer","stripeEventId":"String","stripeSessionId":"String","userId":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true},"paymentResult":{"paymentTicketId":"ID","orderId":"ID","paymentId":"String","paymentStatus":"Enum","paymentIntentInfo":"Object","statusLiteral":"String","amount":"Double","currency":"String","success":true,"description":"String","metadata":"Object","paymentUserParams":"Object"}}

Route Event webhookcallback-striped

Event topic : clonesahibinden-payment-service-webhookcallback-striped

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 paymentTransaction data object itself.

The following JSON included in the payload illustrates the fullest representation of the paymentTransaction 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":"paymentTransaction","method":"POST","action":"update","appVersion":"Version","rowCount":1,"paymentTransaction":{"id":"ID","amount":"Double","currency":"String","listingId":"ID","paymentConfirmedAt":"Date","premiumType":"Enum","premiumType_idx":"Integer","status":"Enum","status_idx":"Integer","stripeEventId":"String","stripeSessionId":"String","userId":"ID","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 paymentTransaction

Service Design Specification - Object Design for paymentTransaction

clonesahibinden-payment-service documentation

Document Overview

This document outlines the object design for the paymentTransaction model in our application. It includes details about the model’s attributes, relationships, and any specific validation or business logic that applies.

paymentTransaction Data Object

Object Overview

Description: Represents a Stripe-based payment for a one-time premium listing upgrade. Linked to user and listing, with payment metadata, premium details, status, and Stripe reconciliation fields. Immutable except for webhook-driven status updates.

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
amount Double Yes Payment amount for selected premiumType, in target currency.
currency String Yes Currency in ISO-4217 format (e.g., 'TRY','USD') used for Stripe checkout.
listingId ID Yes Target classified listing being upgraded to premium.
paymentConfirmedAt Date No Date/time when payment was confirmed and premium was granted. Null if never successful/aborted.
premiumType Enum Yes Premium upgrade package: bronze, silver, gold (matches frontend/listing options).
status Enum Yes Status of payment: pending, awaiting_confirmation (stripe checkout created, awaiting webhook), success (confirmed), failed (declined or errored), canceled (user canceled).
stripeEventId String No Last Stripe event webhook ID processed for this payment (used for double-spend/deduplication of webhook).
stripeSessionId String No Stripe Checkout Session ID associated with this payment (used for reconciling gateway callbacks).
userId ID Yes User (buyer) who made the payment (auth:user)

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

amount currency listingId premiumType 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

amount currency listingId paymentConfirmedAt premiumType status stripeEventId stripeSessionId 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.

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

listingId paymentConfirmedAt premiumType status 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

listingId premiumType status stripeEventId stripeSessionId 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.

Relation Properties

listingId 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.

Filter Properties

listingId paymentConfirmedAt premiumType status 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 - Create Paymenttransaction

Business API Design Specification - Create Paymenttransaction

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 createPaymentTransaction 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 createPaymentTransaction Business API is designed to handle a create operation on the PaymentTransaction 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 paymentTransaction to initiate a Stripe Checkout for premium upgrade on a listing. Checks listing and user, prevents duplicate active payments, creates transaction with status=‘pending’, triggers Stripe checkout, and returns checkout session URL/info.

API Frontend Description By The Backend Architect

Initiate Premium Payment

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 createPaymentTransaction Business API includes a REST controller that can be triggered via the following route:

/v1/payments/create

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 createPaymentTransaction Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The createPaymentTransaction 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
paymentTransactionId ID No - body paymentTransactionId
Description: This id paremeter is used to create the data object with a given specific id. Leave null for automatic id.
listingId ID Yes `` body listingId
Description: ID of the listing to upgrade to premium
premiumType String Yes `` body premiumType
Description: PremiumType to purchase (‘bronze’, ‘silver’, ‘gold’)

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 createPaymentTransaction 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

{
    userId: this.session.userId,
    listingId: this.listingId,
    premiumType: this.premiumType,
    status: 'pending',
   
}

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.paymentTransactionId,
  amount: this.amount,
  currency: this.currency,
  listingId: this.listingId,
  paymentConfirmedAt: this.paymentConfirmedAt,
  premiumType: this.premiumType,
  status: 'pending',
  stripeEventId: this.stripeEventId,
  stripeSessionId: this.stripeSessionId,
  userId: this.session.userId,
}

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, socketSettings, 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 : fetchListing

Action Type: FetchObjectAction

Fetch the target listing to confirm it exists and is valid for payment

class Api {
  async fetchListing() {
    // Fetch Object on childObject listing

    const userQuery = {
      $and: [{ id: this.listingId }, { isActive: true }],
    };
    const { convertUserQueryToElasticQuery } = require("common");
    const scriptQuery = convertUserQueryToElasticQuery(userQuery);

    const elasticIndex = new ElasticIndexer("listing");
    const data = await elasticIndex.getOne(scriptQuery);

    if (!data) {
      throw new NotFoundError("errMsg_FethcedObjectNotFound:listing");
    }

    return data
      ? {
          id: data["id"],
          userId: data["userId"],
          status: data["status"],
          isPremium: data["isPremium"],
          premiumType: data["premiumType"],
          premiumExpiry: data["premiumExpiry"],
        }
      : null;
  }
}

[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 : validateListingOwnership

Action Type: ValidationAction

User must be owner of the listing to upgrade premium

class Api {
  async validateListingOwnership() {
    if (this.checkAbsolute()) return true;

    const isValid = this.listing.userId === this.session.userId;

    if (!isValid) {
      throw new ForbiddenError("You do not own this listing.");
    }
    return isValid;
  }
}

[7] Action : validateListingStatus

Action Type: ValidationAction

Listing must be active or pending_review for upgrade.

class Api {
  async validateListingStatus() {
    const isValid = ["active", "pending_review"].includes(this.listing.status);

    if (!isValid) {
      throw new BadRequestError("Listing not eligible for upgrade.");
    }
    return isValid;
  }
}

[8] Action : validateNoDuplicatePayment

Action Type: ValidationAction

No existing pending/awaiting/success payment for this listing/premiumType by this user.

class Api {
  async validateNoDuplicatePayment() {
    const isValid = !(
      this.existingPayments && this.existingPayments.length > 0
    );

    if (!isValid) {
      throw new BadRequestError(
        "Duplicate or unconfirmed payment detected for this upgrade. Please wait or contact support.",
      );
    }
    return isValid;
  }
}

[9] 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

[10] 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

[11] Action : calculateAmountForPremium

Action Type: FunctionCallAction

Determine the amount to be charged for the selected premiumType. (Replace with dynamic lookup as needed.)

class Api {
  async calculateAmountForPremium() {
    try {
      return LIB.getPremiumPrice(this.premiumType);
    } catch (err) {
      console.error(
        "Error in FunctionCallAction calculateAmountForPremium:",
        err,
      );
      throw err;
    }
  }
}

[12] Action : setAmountContext

Action Type: AddToContextAction

Sets the calculated amount and currency for paymentTransaction creation.

class Api {
  async setAmountContext() {
    try {
      this["amount"] = this.amountInfo.amount;

      this["currency"] = this.amountInfo.currency;

      return true;
    } catch (error) {
      console.error("AddToContextAction error:", error);
      throw error;
    }
  }
}

[13] Step : mainCreateOperation

Manager executes the database insert operation, updates indexes/caches, and triggers internal post-processing like linked default records.


[14] Action : stripeCheckoutAction

Action Type: PaymentAction

Initiates Stripe Checkout session after DB paymentTransaction created. Stores returned sessionId in DB.

class Api {
  throwstripeCheckoutActionConfigError() {
    throw new HttpServerError(
      "errMsg_ActionConfigError:Stripe Configuration For The Object Is Not Activated",
    );
  }

  getOrderId() {
    this.throwstripeCheckoutActionConfigError();
  }

  paymentUpdated() {
    this.throwstripeCheckoutActionConfigError();
  }

  paymentStarted() {
    this.throwstripeCheckoutActionConfigError();
  }

  paymentCanceled() {
    this.throwstripeCheckoutActionConfigError();
  }
  paymentFailed() {
    this.throwstripeCheckoutActionConfigError();
  }
  paymentDone() {
    this.throwstripeCheckoutActionConfigError();
  }

  getPaymentParameters(userParams) {
    this.throwstripeCheckoutActionConfigError();
  }
  async stripeCheckoutAction() {
    this.throwstripeCheckoutActionConfigError();
  }
}

[15] Step : buildOutput

Manager shapes the response: masks sensitive fields, resolves linked references, and formats output according to API contract.


[16] Action : addCheckoutSessionUrl

Action Type: AddToResponseAction

Returns the Stripe checkout session URL to frontend after DB insert and Stripe call.

class Api {
  async addCheckoutSessionUrl() {
    try {
      this.output["checkoutSessionUrl"] = this.checkoutSession.url;

      this.output["transactionId"] = this.paymentTransaction.id;

      return true;
    } catch (error) {
      console.error("AddToResponseAction error:", error);
      throw error;
    }
  }
}

[17] Step : sendResponse

Manager sends the response to the client and finalizes internal tasks like flushing logs or updating session state.


[18] 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 createPaymentTransaction api has got 2 regular client parameters

Parameter Type Required Population
listingId ID true request.body?.[“listingId”]
premiumType String true request.body?.[“premiumType”]

REST Request

To access the api you can use the REST controller with the path POST /v1/payments/create

  axios({
    method: 'POST',
    url: '/v1/payments/create',
    data: {
            listingId:"ID",  
            premiumType:"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 paymentTransaction 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": "paymentTransaction",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"paymentTransaction": {
		"id": "ID",
		"amount": "Double",
		"currency": "String",
		"listingId": "ID",
		"paymentConfirmedAt": "Date",
		"premiumType": "Enum",
		"premiumType_idx": "Integer",
		"status": "Enum",
		"status_idx": "Integer",
		"stripeEventId": "String",
		"stripeSessionId": "String",
		"userId": "ID",
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"isActive": true
	},
	"paymentResult": {
		"paymentTicketId": "ID",
		"orderId": "ID",
		"paymentId": "String",
		"paymentStatus": "Enum",
		"paymentIntentInfo": "Object",
		"statusLiteral": "String",
		"amount": "Double",
		"currency": "String",
		"success": true,
		"description": "String",
		"metadata": "Object",
		"paymentUserParams": "Object"
	}
}

Business API Design Specification - Get Paymenttransaction

Business API Design Specification - Get Paymenttransaction

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 getPaymentTransaction 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 getPaymentTransaction Business API is designed to handle a get operation on the PaymentTransaction data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

Retrieve a paymentTransaction by ID. Only owner or admin may access. Used for order confirmation display, receipt, etc.

API Frontend Description By The Backend Architect

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 getPaymentTransaction Business API includes a REST controller that can be triggered via the following route:

/v1/payments/:id

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 getPaymentTransaction Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The getPaymentTransaction 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
paymentTransactionId ID Yes - urlpath paymentTransactionId
Description: This id paremeter is used to query the required data object.
id String Yes - urlpath id
Description: This parameter will be used to select the data object that is queried

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 getPaymentTransaction 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.",

userId,listingId,amount,currency,premiumType,status,stripeSessionId,stripeEventId,paymentConfirmedAt

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.

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.

{id:this.paymentTransactionId}

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, socketSettings, 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 getPaymentTransaction api has got 2 regular client parameters

Parameter Type Required Population
paymentTransactionId ID true request.params?.[“paymentTransactionId”]
id String true request.params?.[“id”]

REST Request

To access the api you can use the REST controller with the path GET /v1/payments/:id

  axios({
    method: 'GET',
    url: `/v1/payments/${id}`,
    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 paymentTransaction 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": "paymentTransaction",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"paymentTransaction": {
		"listingInfo": {
			"categoryId": "ID",
			"isPremium": "Boolean",
			"premiumExpiry": "Date",
			"premiumType": "Enum",
			"premiumType_idx": "Integer",
			"subcategoryId": "ID",
			"title": "String"
		},
		"isActive": true
	}
}

Business API Design Specification - List Paymenttransactions

Business API Design Specification - List Paymenttransactions

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 listPaymentTransactions 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 listPaymentTransactions Business API is designed to handle a list operation on the PaymentTransaction 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 paymentTransactions for current user, paginated. Admin can query all users. Used for user payment history and admin reconciliation.

API Frontend Description By The Backend Architect

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 listPaymentTransactions Business API includes a REST controller that can be triggered via the following route:

/v1/payments

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 listPaymentTransactions Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The listPaymentTransactions 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 listPaymentTransactions 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,userId,listingId,amount,currency,premiumType,status,paymentConfirmedAt

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 === 'admin' ? {} : {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.

{$and:[this.session.roleId === 'admin' ? {} : {userId: this.session.userId},{userId:this.session?.userId}]}

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).

[ createdAt 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, socketSettings, 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 listPaymentTransactions api has got no visible parameters.

REST Request

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

  axios({
    method: 'GET',
    url: '/v1/payments',
    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 paymentTransactions 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": "paymentTransactions",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"paymentTransactions": [
		{
			"listingInfo": [
				{
					"categoryId": "ID",
					"isPremium": "Boolean",
					"premiumExpiry": "Date",
					"premiumType": "Enum",
					"premiumType_idx": "Integer",
					"subcategoryId": "ID",
					"title": "String"
				},
				{},
				{}
			],
			"isActive": true
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Business API Design Specification - Stripe Webhookcallback

Business API Design Specification - Stripe Webhookcallback

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 stripeWebhookCallback 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 stripeWebhookCallback Business API is designed to handle a update operation on the PaymentTransaction data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

Receives Stripe webhook events, updates corresponding paymentTransaction (status, confirmation), triggers listing premium upgrade via interservice call. Only accepts trusted Stripe event payloads. No login required.

API Frontend Description By The Backend Architect

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 stripeWebhookCallback Business API includes a REST controller that can be triggered via the following route:

/v1/payments/webhook

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 stripeWebhookCallback Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The stripeWebhookCallback 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
paymentTransactionId ID Yes - urlpath paymentTransactionId
Description: This id paremeter is used to select the required data object that will be updated
rawBody String Yes `` body .
Description: Raw request body from Stripe webhook

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 stripeWebhookCallback 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


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.

{id:this.paymentTransactionId}

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.

{}

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, socketSettings, 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] Action : parseStripeEvent

Action Type: AddToContextAction

Parses raw Stripe event body, extracts relevant fields.

class Api {
  async parseStripeEvent() {
    try {
      this["stripeEventType"] = LIB.getStripeEventType(this.rawBody);

      this["stripeSessionId"] = LIB.getStripeSessionId(this.rawBody);

      this["stripeEventId"] = LIB.getStripeEventId(this.rawBody);

      return true;
    } catch (error) {
      console.error("AddToContextAction error:", error);
      throw error;
    }
  }
}

[11] Action : loadPaymentBySessionId

Action Type: AddToContextAction

Load paymentTransaction matching Stripe sessionId.

class Api {
  async loadPaymentBySessionId() {
    try {
      this["payment"] = LIB.findPaymentByStripeSessionId(this.stripeSessionId);

      return true;
    } catch (error) {
      console.error("AddToContextAction error:", error);
      throw error;
    }
  }
}

[12] Step : mainUpdateOperation

Manager executes the update operation with the WHERE and data clauses. Database-level events are raised if configured.


[13] Action : setPaymentStatusSuccess

Action Type: UpdateCrudAction

Updates paymentTransaction status and sets confirmation date if event is completed.

class Api {
  async setPaymentStatusSuccess() {
    // Aggregated Update Operation on childObject paymentTransaction

    const params = {
      status: "success",
      paymentConfirmedAt: new Date().toISOString(),
      stripeEventId: this.stripeEventId,
    };
    const userQuery = { id: this.payment.id };

    const { convertUserQueryToSequelizeQuery } = require("common");
    const query = convertUserQueryToSequelizeQuery(userQuery);

    const result = await updatePaymentTransactionByQuery(params, query, this);
    if (!result) return null;

    // if updated record is in main data update main data
    if (this.dbResult) {
      for (const item of result) {
        if (item.id == this.dbResult.id) {
          Object.assign(this.dbResult, item);
          this.paymentTransaction = this.dbResult;
        }
      }
    }
    if (result.length == 0) return null;
    if (result.length == 1) return result[0];
    return result;
  }
}

[14] Action : upgradeListingPremium

Action Type: InterserviceCallAction

After confirmed payment, calls listing service to set isPremium=true, update premiumType/expiry.

class Api {
  async upgradeListingPremium() {
    const params = {};

    params["listingId"] = this.payment.listingId;

    params["premiumType"] = this.payment.premiumType;

    params["premiumDuration"] = LIB.getPremiumDuration(
      this.payment.premiumType,
    );

    params["paymentTransactionId"] = this.payment.id;

    const resp = await serviceModel.callBusinessApi(
      "listing",
      "upgradeListingPremium",
      params,
    );

    return resp;
  }
}

[15] Step : buildOutput

Manager assembles the response object from the update result, masking fields or injecting additional metadata.


[16] Step : sendResponse

Manager sends the response back to the controller for delivery to the client.


[17] 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 stripeWebhookCallback api has got 1 regular client parameter

Parameter Type Required Population
paymentTransactionId ID true request.params?.[“paymentTransactionId”]

REST Request

To access the api you can use the REST controller with the path POST /v1/payments/webhook

  axios({
    method: 'POST',
    url: '/v1/payments/webhook',
    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 paymentTransaction 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": "paymentTransaction",
	"method": "POST",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"paymentTransaction": {
		"id": "ID",
		"amount": "Double",
		"currency": "String",
		"listingId": "ID",
		"paymentConfirmedAt": "Date",
		"premiumType": "Enum",
		"premiumType_idx": "Integer",
		"status": "Enum",
		"status_idx": "Integer",
		"stripeEventId": "String",
		"stripeSessionId": "String",
		"userId": "ID",
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"isActive": true
	}
}

Business API Design Specification - _fetch Listpaymenttransaction

Business API Design Specification - _fetch Listpaymenttransaction

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 _fetchListPaymentTransaction 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 _fetchListPaymentTransaction Business API is designed to handle a list operation on the PaymentTransaction data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

System API to fetch list of paymentTransaction records for frontend application. Auto-generated, not visible in design.

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 _fetchListPaymentTransaction Business API includes a REST controller that can be triggered via the following route:

/v1/_fetchlistpaymenttransaction

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 _fetchListPaymentTransaction Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The _fetchListPaymentTransaction 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 _fetchListPaymentTransaction api supports 5 optional filter parameters for filtering list results using URL query parameters. These parameters are only available for list type APIs.

listingId Filter

Type: ID
Description: Target classified listing being upgraded to premium.
Location: Query Parameter

Usage:

Non-Array Property:

Examples:

// Get records with a specific ID
GET /v1/_fetchlistpaymenttransaction?listingId=550e8400-e29b-41d4-a716-446655440000

// Get records with multiple IDs (use multiple parameters)
GET /v1/_fetchlistpaymenttransaction?listingId=550e8400-e29b-41d4-a716-446655440000&listingId=660e8400-e29b-41d4-a716-446655440001

// Get records without this field
GET /v1/_fetchlistpaymenttransaction?listingId=null

paymentConfirmedAt Filter

Type: Date
Description: Date/time when payment was confirmed and premium was granted. Null if never successful/aborted.
Location: Query Parameter

Usage:

Non-Array Property (Date filtering matches records where the date falls within the specified day, ignoring time portion):

Special Date Operators:

Date Formats: Dates can be provided in ISO 8601 format (2024-01-15, 2024-01-15T10:30:00Z) or as timestamps (1705324800000).

Examples:

// Get records created on a specific date
GET /v1/_fetchlistpaymenttransaction?paymentConfirmedAt=2024-01-15

// Get records created on multiple dates (use multiple parameters)
GET /v1/_fetchlistpaymenttransaction?paymentConfirmedAt=2024-01-15&paymentConfirmedAt=2024-01-20

// Get records created today (server timezone)
GET /v1/_fetchlistpaymenttransaction?paymentConfirmedAt=$today

// Get records created today (user's local timezone)
GET /v1/_fetchlistpaymenttransaction?paymentConfirmedAt=$ltoday

// Get records created this week (server timezone)
GET /v1/_fetchlistpaymenttransaction?paymentConfirmedAt=$week

// Get records created this week (user's local timezone)
GET /v1/_fetchlistpaymenttransaction?paymentConfirmedAt=$lweek

// Get records created this month
GET /v1/_fetchlistpaymenttransaction?paymentConfirmedAt=$month

// Get records created on a specific date (user's local timezone)
GET /v1/_fetchlistpaymenttransaction?paymentConfirmedAt=$leq-2024-01-15

// Get records created on multiple dates (user's local timezone, use multiple parameters)
GET /v1/_fetchlistpaymenttransaction?paymentConfirmedAt=$lin-2024-01-15&paymentConfirmedAt=$lin-2024-01-20

// Get records without this field
GET /v1/_fetchlistpaymenttransaction?paymentConfirmedAt=null

premiumType Filter

Type: Enum
Description: Premium upgrade package: bronze, silver, gold (matches frontend/listing options).
Location: Query Parameter

Usage:

Examples:

// Get records with specific enum value
GET /v1/_fetchlistpaymenttransaction?premiumType=active

// Get records with multiple enum values (use multiple parameters)
GET /v1/_fetchlistpaymenttransaction?premiumType=active&premiumType=pending

// Get records without this field
GET /v1/_fetchlistpaymenttransaction?premiumType=null

status Filter

Type: Enum
Description: Status of payment: pending, awaiting_confirmation (stripe checkout created, awaiting webhook), success (confirmed), failed (declined or errored), canceled (user canceled).
Location: Query Parameter

Usage:

Examples:

// Get records with specific enum value
GET /v1/_fetchlistpaymenttransaction?status=active

// Get records with multiple enum values (use multiple parameters)
GET /v1/_fetchlistpaymenttransaction?status=active&status=pending

// Get records without this field
GET /v1/_fetchlistpaymenttransaction?status=null

userId Filter

Type: ID
Description: User (buyer) who made the payment (auth:user)
Location: Query Parameter

Usage:

Non-Array Property:

Examples:

// Get records with a specific ID
GET /v1/_fetchlistpaymenttransaction?userId=550e8400-e29b-41d4-a716-446655440000

// Get records with multiple IDs (use multiple parameters)
GET /v1/_fetchlistpaymenttransaction?userId=550e8400-e29b-41d4-a716-446655440000&userId=660e8400-e29b-41d4-a716-446655440001

// Get records without this field
GET /v1/_fetchlistpaymenttransaction?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 _fetchListPaymentTransaction 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).

[ createdAt 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, socketSettings, 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 _fetchListPaymentTransaction 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
listingId ID No Target classified listing being upgraded to premium.
paymentConfirmedAt Date No Date/time when payment was confirmed and premium was granted. Null if never successful/aborted.
premiumType Enum No Premium upgrade package: bronze, silver, gold (matches frontend/listing options).
status Enum No Status of payment: pending, awaiting_confirmation (stripe checkout created, awaiting webhook), success (confirmed), failed (declined or errored), canceled (user canceled).
userId ID No User (buyer) who made the payment (auth:user)

REST Request

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

  axios({
    method: 'GET',
    url: '/v1/_fetchlistpaymenttransaction',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section for usage examples)
        // listingId: '<value>' // Filter by listingId
        // paymentConfirmedAt: '<value>' // Filter by paymentConfirmedAt
        // premiumType: '<value>' // Filter by premiumType
        // status: '<value>' // Filter by status
        // 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 paymentTransactions 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": "paymentTransactions",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"paymentTransactions": [
		{
			"id": "ID",
			"amount": "Double",
			"currency": "String",
			"listingId": "ID",
			"paymentConfirmedAt": "Date",
			"premiumType": "Enum",
			"premiumType_idx": "Integer",
			"status": "Enum",
			"status_idx": "Integer",
			"stripeEventId": "String",
			"stripeSessionId": "String",
			"userId": "ID",
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID",
			"listing": [
				{
					"attributes": "Object",
					"categoryId": "ID",
					"condition": "Enum",
					"condition_idx": "Integer",
					"contactEmail": "String",
					"contactPhone": "String",
					"currency": "String",
					"description": "Text",
					"expiresAt": "Date",
					"favoriteCount": "Integer",
					"isPremium": "Boolean",
					"listingType": "Enum",
					"listingType_idx": "Integer",
					"locationId": "ID",
					"_paymentConfirmation": "String",
					"premiumExpiry": "Date",
					"premiumType": "Enum",
					"premiumType_idx": "Integer",
					"price": "Double",
					"status": "Enum",
					"status_idx": "Integer",
					"subcategoryId": "ID",
					"title": "String",
					"userId": "ID",
					"viewsCount": "Integer",
					"paymentConfirmation": "Enum",
					"paymentConfirmation_idx": "Integer"
				},
				{},
				{}
			],
			"buyer": [
				{
					"fullname": "String"
				},
				{},
				{}
			],
			"isActive": true
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Auth Service

Service Design Specification

Service Design Specification

Athentication documentation -Version:1.0.5

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 ‘clonesahibinden-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 User Email: admin@admin.com** The login email of the super admin user. This user has full permissions across the project and is not tenant-scoped. If not defined, the project owner’s email is used. This email must be unique and valid to support email-based features like verification and password reset.

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.

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 Required For Login: The project requires email verification for user login, meaning that users must verify their email address before they can log in. This is useful for projects that require email verification to ensure that users have provided a valid email address, 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 email to the user’s email address after they register or change their email address. 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 Active: The authetication module is configured to support mobile numbers for users. This means that the user data object will contain a mobile property that will be used to store the user’s mobile number. This is useful for projects that require mobile numbers for users, such as two-factor authentication, SMS notifications, or any application where mobile numbers are required. The mobile number is required to be given by the user during registration, and it will be used to send SMS notifications or for two-factor authentication.

Mobile Verification Is Not Required For Login: The project does not require mobile number verification for user login, meaning that users can log in without verifying their mobile number. This is useful for projects that do not require mobile number verification, such as enterprise applications, internal tools, or any application where mobile number verification is not required. The mobile verification process is not handled by the auth service, and users can log in without verifying their mobile number. While the mobile verification is not required, the auth service will still support mobile verification if it is configured in the verification services. You can prefer mobile verification at any time before any action or make it optional which means that users can verify their mobile number if they want to, but it is not required for login. You can check the mobile verification details in the REST API documentation of the auth service.

Mobile 2FA Is Not Required For Login: The project does not require mobile-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 mobile-based 2FA is not required. While the mobile 2FA is not required, the auth service will still support mobile 2FA if it is configured in the verification services. You can prefer mobile 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 mobile 2FA details in the REST API documentation of the auth service.

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: moderator

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

{
  "superAdmin": "'superAdmin'",
  "admin": "'admin'",
  "user": "'user'",
  "moderator": "'moderator'"
}

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

userType

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 clonesahibinden-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

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.
mobile String No A string value to represent the user's mobile number.
mobileVerified Boolean Yes A boolean value to represent the mobile verification status of the user.
emailVerified Boolean Yes A boolean value to represent the email verification status of the user.
userType Enum No Indicates whether the user is an individual or a corporate account.

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 mobile userType

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 mobile mobileVerified emailVerified userType

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 mobile

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

clonesahibinden-auth-service

Version: 1.0.5

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 clonesahibinden-access-token
Cookie clonesahibinden-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.
mobile String A string value to represent the user's mobile number.
mobileVerified Boolean A boolean value to represent the mobile verification status of the user.
emailVerified Boolean A boolean value to represent the email verification status of the user.
userType Enum Indicates whether the user is an individual or a corporate account.

Enum Properties

Enum properties are represented as strings in the database. The values are mapped to their corresponding names in the application layer.

userType Enum Property

Property Definition : Indicates whether the user is an individual or a corporate account.Enum Options

Name Value Index
individual "individual"" 0
corporate "corporate"" 1

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",
		"mobile": "String",
		"mobileVerified": "Boolean",
		"emailVerified": "Boolean",
		"userType": "Enum",
		"userType_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 5 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”]
mobile String false request.body?.[“mobile”]
userType Enum false request.body?.[“userType”]
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
mobile : A string value to represent the user’s mobile number.
userType : Indicates whether the user is an individual or a corporate account.

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",  
            mobile:"String",  
            userType:"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",
		"mobile": "String",
		"mobileVerified": "Boolean",
		"emailVerified": "Boolean",
		"userType": "Enum",
		"userType_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 5 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”]
mobile String false request.body?.[“mobile”]
userType Enum false request.body?.[“userType”]
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
mobile : A string value to represent the user’s mobile number.
userType : Indicates whether the user is an individual or a corporate account.

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",  
            mobile:"String",  
            userType:"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",
		"mobile": "String",
		"mobileVerified": "Boolean",
		"emailVerified": "Boolean",
		"userType": "Enum",
		"userType_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 6 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”]
mobile String false request.body?.[“mobile”]
userType Enum false request.body?.[“userType”]
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
mobile : A string value to represent the user’s mobile number.
userType : Indicates whether the user is an individual or a corporate account.

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",  
            mobile:"String",  
            userType:"Enum",  
    
    },
    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",
		"mobile": "String",
		"mobileVerified": "Boolean",
		"emailVerified": "Boolean",
		"userType": "Enum",
		"userType_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",
		"mobile": "String",
		"mobileVerified": "Boolean",
		"emailVerified": "Boolean",
		"userType": "Enum",
		"userType_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",
		"mobile": "String",
		"mobileVerified": "Boolean",
		"emailVerified": "Boolean",
		"userType": "Enum",
		"userType_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 4 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.

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

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
        // mobile: '<value>' // Filter by mobile
            }
  });

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",
			"mobile": "String",
			"mobileVerified": "Boolean",
			"emailVerified": "Boolean",
			"userType": "Enum",
			"userType_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 2 optional filter parameters for filtering list results:

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

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

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
        // mobile: '<value>' // Filter by mobile
            }
  });

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",
			"mobile": "String",
			"mobileVerified": "Boolean",
			"emailVerified": "Boolean",
			"userType": "Enum",
			"userType_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",
		"mobile": "String",
		"mobileVerified": "Boolean",
		"emailVerified": "Boolean",
		"userType": "Enum",
		"userType_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",
		"mobile": "String",
		"mobileVerified": "Boolean",
		"emailVerified": "Boolean",
		"userType": "Enum",
		"userType_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",
		"mobile": "String",
		"mobileVerified": "Boolean",
		"emailVerified": "Boolean",
		"userType": "Enum",
		"userType_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
	}
}

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 6 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”]
mobile String false request.body?.[“mobile”]
userType Enum false request.body?.[“userType”]
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.
mobile : The mobile number defined by the the user that is being registered.
userType : Indicates whether the user is an individual or a corporate account.

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",  
            mobile:"String",  
            userType:"Enum",  
    
    },
    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",
		"mobile": "String",
		"mobileVerified": "Boolean",
		"emailVerified": "Boolean",
		"userType": "Enum",
		"userType_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

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

clonesahibinden-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: clonesahibinden-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","mobile":"String","mobileVerified":"Boolean","emailVerified":"Boolean","userType":"Enum","userType_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

DbEvent user-updated

Event topic: clonesahibinden-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","mobile":"String","mobileVerified":"Boolean","emailVerified":"Boolean","userType":"Enum","userType_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","mobile":"String","mobileVerified":"Boolean","emailVerified":"Boolean","userType":"Enum","userType_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},
oldDataValues,
newDataValues
}

DbEvent user-deleted

Event topic: clonesahibinden-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","mobile":"String","mobileVerified":"Boolean","emailVerified":"Boolean","userType":"Enum","userType_idx":"Integer","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

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-clonesahibinden_user-created

Event payload:

{"id":"ID","email":"String","password":"String","fullname":"String","avatar":"String","roleId":"String","mobile":"String","mobileVerified":"Boolean","emailVerified":"Boolean","userType":"Enum","userType_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event user-updated

Event topic: elastic-index-clonesahibinden_user-created

Event payload:

{"id":"ID","email":"String","password":"String","fullname":"String","avatar":"String","roleId":"String","mobile":"String","mobileVerified":"Boolean","emailVerified":"Boolean","userType":"Enum","userType_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event user-deleted

Event topic: elastic-index-clonesahibinden_user-deleted

Event payload:

{"id":"ID","email":"String","password":"String","fullname":"String","avatar":"String","roleId":"String","mobile":"String","mobileVerified":"Boolean","emailVerified":"Boolean","userType":"Enum","userType_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event user-extended

Event topic: elastic-index-clonesahibinden_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 : clonesahibinden-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","mobile":"String","mobileVerified":"Boolean","emailVerified":"Boolean","userType":"Enum","userType_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event user-updated

Event topic : clonesahibinden-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","mobile":"String","mobileVerified":"Boolean","emailVerified":"Boolean","userType":"Enum","userType_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event profile-updated

Event topic : clonesahibinden-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","mobile":"String","mobileVerified":"Boolean","emailVerified":"Boolean","userType":"Enum","userType_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event user-created

Event topic : clonesahibinden-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","mobile":"String","mobileVerified":"Boolean","emailVerified":"Boolean","userType":"Enum","userType_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event user-deleted

Event topic : clonesahibinden-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","mobile":"String","mobileVerified":"Boolean","emailVerified":"Boolean","userType":"Enum","userType_idx":"Integer","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event profile-archived

Event topic : clonesahibinden-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","mobile":"String","mobileVerified":"Boolean","emailVerified":"Boolean","userType":"Enum","userType_idx":"Integer","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event users-listed

Event topic : clonesahibinden-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","mobile":"String","mobileVerified":"Boolean","emailVerified":"Boolean","userType":"Enum","userType_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 : clonesahibinden-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","mobile":"String","mobileVerified":"Boolean","emailVerified":"Boolean","userType":"Enum","userType_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 : clonesahibinden-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","mobile":"String","mobileVerified":"Boolean","emailVerified":"Boolean","userType":"Enum","userType_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event userpassword-updated

Event topic : clonesahibinden-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","mobile":"String","mobileVerified":"Boolean","emailVerified":"Boolean","userType":"Enum","userType_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event userpasswordbyadmin-updated

Event topic : clonesahibinden-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","mobile":"String","mobileVerified":"Boolean","emailVerified":"Boolean","userType":"Enum","userType_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event briefuser-retrived

Event topic : clonesahibinden-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 : clonesahibinden-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","mobile":"String","mobileVerified":"Boolean","emailVerified":"Boolean","userType":"Enum","userType_idx":"Integer","isActive":true,"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 user

Service Design Specification - Object Design for user

clonesahibinden-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.
mobile String No A string value to represent the user's mobile number.
mobileVerified Boolean Yes A boolean value to represent the mobile verification status of the user.
emailVerified Boolean Yes A boolean value to represent the email verification status of the user.
userType Enum No Indicates whether the user is an individual or a corporate account.

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 mobile userType

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 mobile mobileVerified emailVerified userType

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 mobile

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.

{$and:[{id:this.userId},{isActive:true}]}

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, socketSettings, 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 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",
		"mobile": "String",
		"mobileVerified": "Boolean",
		"emailVerified": "Boolean",
		"userType": "Enum",
		"userType_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 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 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
mobile String No - body mobile
Description: A string value to represent the user’s mobile number.
userType Enum No - body userType
Description: Indicates whether the user is an individual or a corporate account.

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.

{$and:[{id:this.userId},{isActive:true}]}

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,
  mobile: this.mobile,
  userType: this.userType,
}

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, socketSettings, 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, {
      superAdmin: 20,
      saasAdmin: 19,
      admin: 18,
      tenantOwner: 17,
      tenantAdmin: 16,
      saasUser: 15,
      tenantUser: 14,
      user: 13,
    });

    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 =
      (this._r[this.session.roleId] ?? 0) > (this._r[this.user.roleId] ?? 0);

    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 5 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”]
mobile String false request.body?.[“mobile”]
userType Enum false request.body?.[“userType”]

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",  
            mobile:"String",  
            userType:"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",
		"mobile": "String",
		"mobileVerified": "Boolean",
		"emailVerified": "Boolean",
		"userType": "Enum",
		"userType_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 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 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
mobile String No - body mobile
Description: A string value to represent the user’s mobile number.
userType Enum No - body userType
Description: Indicates whether the user is an individual or a corporate account.

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.

{$and:[{id:this.userId},{isActive:true}]}

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,
  mobile: this.mobile,
  userType: this.userType,
}

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, socketSettings, 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 5 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”]
mobile String false request.body?.[“mobile”]
userType Enum false request.body?.[“userType”]

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",  
            mobile:"String",  
            userType:"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",
		"mobile": "String",
		"mobileVerified": "Boolean",
		"emailVerified": "Boolean",
		"userType": "Enum",
		"userType_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 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
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
mobile String No - body mobile
Description: A string value to represent the user’s mobile number.
userType Enum No - body userType
Description: Indicates whether the user is an individual or a corporate account.

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 = 
  this.avatar ? `https://gravatar.com/avatar/${LIB.common.md5(this.email ?? 'nullValue')}?s=200&d=identicon` : null

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,
  mobile: this.mobile,
  userType: this.userType,
  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, socketSettings, 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 : fetchArchivedUser

Action Type: FetchObjectAction

Check and get if any deleted user exists with the same email

class Api {
  async fetchArchivedUser() {
    // Fetch Object on childObject user

    const userQuery = {
      $and: [
        { email: this.email, isActive: false },
        {
          _archivedAt: {
            $gte: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000),
          },
        },
      ],
    };

    const { convertUserQueryToSequelizeQuery } = require("common");
    const scriptQuery = convertUserQueryToSequelizeQuery(userQuery);

    // get object from db
    const data = await getUserByQuery(scriptQuery);

    return data
      ? {
          id: data["id"],
        }
      : null;
  }
}

[6] Action : checkArchivedUser

Action Type: ValidationAction

Prevents re-register of a user when their profile is sitll in 30days archive

class Api {
  async checkArchivedUser() {
    const isError = this.archivedUser?.email != null;

    if (isError) {
      throw new BadRequestError("ThisProfileIsArchivedPleaseLoginToRestore");
    }
    return isError;
  }
}

[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] Step : mainCreateOperation

Manager executes the database insert operation, updates indexes/caches, and triggers internal post-processing like linked default records.


[10] Step : buildOutput

Manager shapes the response: masks sensitive fields, resolves linked references, and formats output according to API contract.


[11] Action : writeVerificationNeedsToResponse

Action Type: AddToResponseAction

Set if email or mobile verification needed

class Api {
  async writeVerificationNeedsToResponse() {
    try {
      this.output["emailVerificationNeeded"] = !this.user?.emailVerified;

      this.output["mobileVerificationNeeded"] = false;

      return true;
    } catch (error) {
      console.error("AddToResponseAction error:", error);
      throw error;
    }
  }
}

[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 createUser api has got 6 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”]
mobile String false request.body?.[“mobile”]
userType Enum false request.body?.[“userType”]

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",  
            mobile:"String",  
            userType:"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": "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",
		"mobile": "String",
		"mobileVerified": "Boolean",
		"emailVerified": "Boolean",
		"userType": "Enum",
		"userType_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.

{$and:[{id:this.userId},{isActive:true}]}

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, socketSettings, 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, {
      superAdmin: 20,
      saasAdmin: 19,
      admin: 18,
      tenantOwner: 17,
      tenantAdmin: 16,
      saasUser: 15,
      tenantUser: 0,
      user: 0,
    });

    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 = this.userId == this.auth?.superAdminId;

    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 =
      (this._r[this.session?.roleId] ?? 0) > (this._r[this.user?.roleId] ?? 0);

    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 (async (userId) => {
        await this.auth.deleteUserSessions(userId);
      })(this.userId);
    } 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",
		"mobile": "String",
		"mobileVerified": "Boolean",
		"emailVerified": "Boolean",
		"userType": "Enum",
		"userType_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.

{$and:[{id:this.userId},{isActive:true}]}

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, socketSettings, 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 = this.userId == this.auth?.superAdminId;

    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 (async (userId) => {
        await this.auth.deleteUserSessions(userId);
      })(this.userId);
    } 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",
		"mobile": "String",
		"mobileVerified": "Boolean",
		"emailVerified": "Boolean",
		"userType": "Enum",
		"userType_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 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 listUsers api supports 4 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

mobile Filter

Type: String
Description: A string value to represent the user’s mobile number.
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?mobile=john
// Matches: "John", "Johnny", "johnson", "McJohn", etc.

// Find records with multiple values (use multiple parameters)
GET /v1/users?mobile=laptop&mobile=phone&mobile=tablet
// Matches records containing "laptop", "phone", or "tablet" anywhere in the field

// Find records without this field
GET /v1/users?mobile=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.

{isActive:true}

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, socketSettings, 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 4 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.
mobile String No A string value to represent the user’s mobile number.

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
        // mobile: '<value>' // Filter by mobile
            }
  });

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",
			"mobile": "String",
			"mobileVerified": "Boolean",
			"emailVerified": "Boolean",
			"userType": "Enum",
			"userType_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 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
keyword String Yes - query keyword
Description: -

Filter Parameters

The searchUsers api supports 2 optional filter parameters 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

mobile Filter

Type: String
Description: A string value to represent the user’s mobile number.
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?mobile=john
// Matches: "John", "Johnny", "johnson", "McJohn", etc.

// Find records with multiple values (use multiple parameters)
GET /v1/searchusers?mobile=laptop&mobile=phone&mobile=tablet
// Matches records containing "laptop", "phone", or "tablet" anywhere in the field

// Find records without this field
GET /v1/searchusers?mobile=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.

{isActive:true}

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, socketSettings, 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 2 filter parameters 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.
mobile String No A string value to represent the user’s mobile number.

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
        // mobile: '<value>' // Filter by mobile
            }
  });

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",
			"mobile": "String",
			"mobileVerified": "Boolean",
			"emailVerified": "Boolean",
			"userType": "Enum",
			"userType_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.

{$and:[{id:this.userId},{isActive:true}]}

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: this.roleId,
   
}

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: this.roleId,
}

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, socketSettings, 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, {
      superAdmin: 20,
      saasAdmin: 19,
      admin: 18,
      tenantOwner: 17,
      tenantAdmin: 16,
      saasUser: 15,
      tenantUser: 0,
      user: 0,
    });

    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 =
      (this._r[this.session.roleId] ?? 0) > (this._r[this.roleId] ?? 0);

    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 =
      (this._r[this.session.roleId] ?? 0) > (this._r[this.user.roleId] ?? 0);

    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",
		"mobile": "String",
		"mobileVerified": "Boolean",
		"emailVerified": "Boolean",
		"userType": "Enum",
		"userType_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 = 
  this.newPassword ? this.hashString(this.newPassword) : null

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.

{$and:[{id:this.userId},{isActive:true}]}

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: this.newPassword,
   
}

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: this.newPassword,
}

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, socketSettings, 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 = this.hashCompare(this.oldPassword, this.user.password);

    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",
		"mobile": "String",
		"mobileVerified": "Boolean",
		"emailVerified": "Boolean",
		"userType": "Enum",
		"userType_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 = 
  this.password ? this.hashString(this.password) : null

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.

{$and:[{id:this.userId},{isActive:true}]}

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: this.password,
   
}

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: this.password,
}

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, socketSettings, 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, {
      superAdmin: 20,
      saasAdmin: 19,
      admin: 18,
      tenantOwner: 17,
      tenantAdmin: 16,
      saasUser: 15,
      tenantUser: 14,
      user: 13,
    });

    return obj;
  }
}

[10] Action : protectHigherRole

Action Type: ValidationAction

Prevents the update of a higher or equal user role

class Api {
  async protectHigherRole() {
    const isValid =
      (this._r[this.session.roleId] ?? 0) > (this._r[this.user.roleId] ?? 0);

    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",
		"mobile": "String",
		"mobileVerified": "Boolean",
		"emailVerified": "Boolean",
		"userType": "Enum",
		"userType_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.

{$and:[{id:this.userId},{isActive:true}]}

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, socketSettings, 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 - 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 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
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.
mobile String No - body mobile
Description: The mobile number defined by the the user that is being registered.
userType Enum No - body userType
Description: Indicates whether the user is an individual or a corporate account.

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 = 
  this.socialProfile?.avatar ?? (this.avatar ? this.avatar : `https://gravatar.com/avatar/${LIB.common.md5(this.email ?? 'nullValue')}?s=200&d=identicon`)
this.password = 
  this.socialProfile ? this.password ?? LIB.common.randomCode() : this.password
this.fullname = 
  this.socialProfile?.fullname ?? this.fullname
this.email = 
  this.socialProfile?.email ?? this.email
this.mobile = 
  this.socialProfile?.mobile ?? this.mobile

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: this.socialProfile?.emailVerified ?? false,
    roleId: this.socialProfile?.roleId ?? 'user',
    : null,
   
}

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,
  mobile: this.mobile,
  userType: this.userType,
  emailVerified: this.socialProfile?.emailVerified ?? false,
  roleId: this.socialProfile?.roleId ?? 'user',
  undefined: null,
  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, socketSettings, 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 : fetchArchivedUser

Action Type: FetchObjectAction

Check and get if any deleted user(in 30 days) exists with the same email

class Api {
  async fetchArchivedUser() {
    // Fetch Object on childObject user

    const userQuery = {
      $and: [
        { email: this.email, isActive: false },
        {
          _archivedAt: {
            $gte: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000),
          },
        },
      ],
    };

    const { convertUserQueryToSequelizeQuery } = require("common");
    const scriptQuery = convertUserQueryToSequelizeQuery(userQuery);

    // get object from db
    const data = await getUserByQuery(scriptQuery);

    return data
      ? {
          id: data["id"],
        }
      : null;
  }
}

[6] Action : checkArchivedUser

Action Type: ValidationAction

Prevents re-register of a user when their profile is sitll in 30days archive

class Api {
  async checkArchivedUser() {
    const isError = this.archivedUser?.email != null;

    if (isError) {
      throw new BadRequestError("YourProfileIsArchivedPleaseLoginToRestore");
    }
    return isError;
  }
}

[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] Step : mainCreateOperation

Manager executes the database insert operation, updates indexes/caches, and triggers internal post-processing like linked default records.


[10] Step : buildOutput

Manager shapes the response: masks sensitive fields, resolves linked references, and formats output according to API contract.


[11] Action : writeVerificationNeedsToResponse

Action Type: AddToResponseAction

Set if email or mobile verification needed

class Api {
  async writeVerificationNeedsToResponse() {
    try {
      this.output["emailVerificationNeeded"] = !this.user?.emailVerified;

      this.output["mobileVerificationNeeded"] = false;

      return true;
    } catch (error) {
      console.error("AddToResponseAction error:", error);
      throw error;
    }
  }
}

[12] 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 (async () => {
        try {
          if (
            this.output.emailVerificationNeeded ||
            this.output.mobileVerificationNeeded
          )
            return;
          const email = this.output[this.dataName]?.email;
          if (!email) return;
          const { createSessionManager } = require("sessionLayer");
          const sm = createSessionManager();
          await sm.setLoginToRequest(this.request, null, {
            userField: "email",
            subjectClaim: email,
          });
          this.output.accessToken = sm.accessToken;
          this.output.autoLoginSession = sm.session;
          this.request.autoLoginToken = sm.accessToken;
          console.log("Auto-login after registration successful for:", email);
        } catch (autoLoginErr) {
          console.log(
            "Auto-login after registration failed:",
            autoLoginErr.message,
          );
        }
      })();
    } catch (err) {
      console.error("Error in FunctionCallAction autoLoginAfterRegister:", err);
      throw err;
    }
  }
}

[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 registerUser api has got 6 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”]
mobile String false request.body?.[“mobile”]
userType Enum false request.body?.[“userType”]

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",  
            mobile:"String",  
            userType:"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": "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",
		"mobile": "String",
		"mobileVerified": "Boolean",
		"emailVerified": "Boolean",
		"userType": "Enum",
		"userType_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Bff Service

Service Design Specification

Service Design Specification

BFF Service Documentation Version: 1.0.3


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.3

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 /AccountBannedNotificationView

Example:

axios({
  method: "GET",
  url: `/AccountBannedNotificationView`,
  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 /AccountBannedNotificationView/:id

Parameters

Parameter Type Required Population
id ID Yes path.param
axios({
  method: "GET",
  url: `/AccountBannedNotificationView/${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 /ConversationThreadView

Example:

axios({
  method: "GET",
  url: `/ConversationThreadView`,
  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 /ConversationThreadView/:id

Parameters

Parameter Type Required Population
id ID Yes path.param
axios({
  method: "GET",
  url: `/ConversationThreadView/${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 /FavoritesView

Example:

axios({
  method: "GET",
  url: `/FavoritesView`,
  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 /FavoritesView/:id

Parameters

Parameter Type Required Population
id ID Yes path.param
axios({
  method: "GET",
  url: `/FavoritesView/${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 /ListingDetailView

Example:

axios({
  method: "GET",
  url: `/ListingDetailView`,
  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 /ListingDetailView/:id

Parameters

Parameter Type Required Population
id ID Yes path.param
axios({
  method: "GET",
  url: `/ListingDetailView/${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 /ListingStatusNotificationView

Example:

axios({
  method: "GET",
  url: `/ListingStatusNotificationView`,
  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 /ListingStatusNotificationView/:id

Parameters

Parameter Type Required Population
id ID Yes path.param
axios({
  method: "GET",
  url: `/ListingStatusNotificationView/${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 /MessageReceivedNotificationView

Example:

axios({
  method: "GET",
  url: `/MessageReceivedNotificationView`,
  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 /MessageReceivedNotificationView/:id

Parameters

Parameter Type Required Population
id ID Yes path.param
axios({
  method: "GET",
  url: `/MessageReceivedNotificationView/${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 /PremiumPaymentSuccessNotificationView

Example:

axios({
  method: "GET",
  url: `/PremiumPaymentSuccessNotificationView`,
  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 /PremiumPaymentSuccessNotificationView/:id

Parameters

Parameter Type Required Population
id ID Yes path.param
axios({
  method: "GET",
  url: `/PremiumPaymentSuccessNotificationView/${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: List Records

Route Definition: Returns a paginated list from the elastic index. Route Type: list
Default access route: POST /AdminDashboardView/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: `/AdminDashboardView/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 /AdminDashboardView/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: `/AdminDashboardView/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 /AdminDashboardView/count

Parameters

Parameter Type Required Population
q String No query.q
filters Object Yes body
axios({
  method: "POST",
  url: `/AdminDashboardView/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 /AdminDashboardView/count

Parameters

Parameter Type Required Population
q String No query.q
axios({
  method: "GET",
  url: `/AdminDashboardView/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 /AdminDashboardView/schema

axios({
  method: "GET",
  url: `/AdminDashboardView/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 /AdminDashboardView/filters

Route Type: get

Parameters

Parameter Type Required Population
page Number No query.page
limit Number No query.limit
axios({
  method: "GET",
  url: `/AdminDashboardView/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 /AdminDashboardView/filters

Route Type: create

Parameters

Parameter Type Required Population
filters Object Yes body
axios({
  method: "POST",
  url: `/AdminDashboardView/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 /AdminDashboardView/filters/:filterId

Route Type: delete

Parameters

Parameter Type Required Population
filterId ID Yes path.param
axios({
  method: "DELETE",
  url: `/AdminDashboardView/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 /AdminDashboardView/:id

Parameters

Parameter Type Required Population
id ID Yes path.param
axios({
  method: "GET",
  url: `/AdminDashboardView/${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 /ListingListView/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: `/ListingListView/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 /ListingListView/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: `/ListingListView/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 /ListingListView/count

Parameters

Parameter Type Required Population
q String No query.q
filters Object Yes body
axios({
  method: "POST",
  url: `/ListingListView/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 /ListingListView/count

Parameters

Parameter Type Required Population
q String No query.q
axios({
  method: "GET",
  url: `/ListingListView/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 /ListingListView/schema

axios({
  method: "GET",
  url: `/ListingListView/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 /ListingListView/filters

Route Type: get

Parameters

Parameter Type Required Population
page Number No query.page
limit Number No query.limit
axios({
  method: "GET",
  url: `/ListingListView/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 /ListingListView/filters

Route Type: create

Parameters

Parameter Type Required Population
filters Object Yes body
axios({
  method: "POST",
  url: `/ListingListView/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 /ListingListView/filters/:filterId

Route Type: delete

Parameters

Parameter Type Required Population
filterId ID Yes path.param
axios({
  method: "DELETE",
  url: `/ListingListView/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 /ListingListView/:id

Parameters

Parameter Type Required Population
id ID Yes path.param
axios({
  method: "GET",
  url: `/ListingListView/${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: user-created

Event Topic: elastic-index-clonesahibinden_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 AdminDashboardViewAggregateData function to enrich and store the final document in the related index.

Expected Payload:

{
  "id": "String"
}

Kafka Event Listener: user-updated

Event Topic: elastic-index-clonesahibinden_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 AdminDashboardViewAggregateData function to update the enriched document in the related index.

Expected Payload:

{
  "id": "String"
}

Kafka Event Listener: user-deleted

Event Topic: elastic-index-clonesahibinden>_user-deleted

When a user is deleted in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the AdminDashboardViewAggregateData function to handle removal or cleanup in the related index.

Expected Payload:

{
  "id": "String"
}

Kafka Event Listener: listing-created

Event Topic: elastic-index-clonesahibinden_listing-created

When a listing is created in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the ListingListViewAggregateData function to enrich and store the final document in the related index.

Expected Payload:

{
  "id": "String"
}

Kafka Event Listener: listing-updated

Event Topic: elastic-index-clonesahibinden_listing-updated

When a listing is updated in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the ListingListViewAggregateData function to update the enriched document in the related index.

Expected Payload:

{
  "id": "String"
}

Kafka Event Listener: listing-deleted

Event Topic: elastic-index-clonesahibinden>_listing-deleted

When a listing is deleted in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the ListingListViewAggregateData 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 ownerUserReListingListView function to update dependent documents in the related index.

Expected Payload:

{
  "id": "String"
}

Kafka Event Listener: user-updated

Event Topic: elastic-index-clonesahibinden>_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 ownerUserReListingListView function to re-enrich dependent data in the related index.

Expected Payload:

{
  "id": "String"
}

Kafka Event Listener: user-deleted

Event Topic: elastic-index-clonesahibinden>_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 ownerUserReListingListView function to handle dependent data cleanup or updates.

Expected Payload:

{
  "id": "String"
}

Kafka Event Listener: category-created

Event Topic: elastic-index-category-created

When a category is created in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the categoryReListingListView function to update dependent documents in the related index.

Expected Payload:

{
  "id": "String"
}

Kafka Event Listener: category-updated

Event Topic: elastic-index-clonesahibinden>_category-updated

When a category is updated in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the categoryReListingListView function to re-enrich dependent data in the related index.

Expected Payload:

{
  "id": "String"
}

Kafka Event Listener: category-deleted

Event Topic: elastic-index-clonesahibinden>_category-deleted

When a category is deleted from the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the categoryReListingListView function to handle dependent data cleanup or updates.

Expected Payload:

{
  "id": "String"
}

Kafka Event Listener: category-created

Event Topic: elastic-index-category-created

When a category is created in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the subcategoryReListingListView function to update dependent documents in the related index.

Expected Payload:

{
  "id": "String"
}

Kafka Event Listener: category-updated

Event Topic: elastic-index-clonesahibinden>_category-updated

When a category is updated in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the subcategoryReListingListView function to re-enrich dependent data in the related index.

Expected Payload:

{
  "id": "String"
}

Kafka Event Listener: category-deleted

Event Topic: elastic-index-clonesahibinden>_category-deleted

When a category is deleted from the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the subcategoryReListingListView function to handle dependent data cleanup or updates.

Expected Payload:

{
  "id": "String"
}

Kafka Event Listener: location-created

Event Topic: elastic-index-location-created

When a location is created in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the locationReListingListView function to update dependent documents in the related index.

Expected Payload:

{
  "id": "String"
}

Kafka Event Listener: location-updated

Event Topic: elastic-index-clonesahibinden>_location-updated

When a location is updated in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the locationReListingListView function to re-enrich dependent data in the related index.

Expected Payload:

{
  "id": "String"
}

Kafka Event Listener: location-deleted

Event Topic: elastic-index-clonesahibinden>_location-deleted

When a location is deleted from the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the locationReListingListView function to handle dependent data cleanup or updates.

Expected Payload:

{
  "id": "String"
}

Kafka Event Listener: listingimage-created

Event Topic: elastic-index-listingimage-created

When a listingimage is created in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the coverImageReListingListView function to update dependent documents in the related index.

Expected Payload:

{
  "id": "String"
}

Kafka Event Listener: listingimage-updated

Event Topic: elastic-index-clonesahibinden>_listingimage-updated

When a listingimage is updated in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the coverImageReListingListView function to re-enrich dependent data in the related index.

Expected Payload:

{
  "id": "String"
}

Kafka Event Listener: listingimage-deleted

Event Topic: elastic-index-clonesahibinden>_listingimage-deleted

When a listingimage is deleted from the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the coverImageReListingListView 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.3


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.3

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: clonesahibinden-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 clonesahibinden-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: clonesahibinden-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 clonesahibinden-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: clonesahibinden-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 clonesahibinden-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: clonesahibinden-notification-service-notification-email

When a notification is sent through the Email channel, this listener is triggered. It consumes messages from the clonesahibinden-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: clonesahibinden-notification-service-notification-push

When a notification is sent through the Push channel, this listener is triggered. It consumes messages from the clonesahibinden-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: clonesahibinden-notification-service-notification-sms

When a notification is sent through the SMS channel, this listener is triggered. It consumes messages from the clonesahibinden-notification-service-notification-sms topic, parses the payload, and uses the dynamically configured SMS provider to send the notification.

Kafka Event Listener: runaccountActivationListener

Event Topic: clonesahibinden-auth-service-dbevent-user-created

When a notification is sent through the clonesahibinden-auth-service-dbevent-user-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 (UserProfileView).

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: runaccountBannedListener

Event Topic: clonesahibinden-adminmoderation-service-dbevent-adminactionlog-created

When a notification is sent through the clonesahibinden-adminmoderation-service-dbevent-adminactionlog-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 (AccountBannedNotificationView).

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: runlistingApprovedListener

Event Topic: clonesahibinden-listing-service-listing-statusupdated

When a notification is sent through the clonesahibinden-listing-service-listing-statusupdated 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 (ListingStatusNotificationView).

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: runlistingDeniedListener

Event Topic: clonesahibinden-listing-service-listing-statusupdated

When a notification is sent through the clonesahibinden-listing-service-listing-statusupdated 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 (ListingStatusNotificationView).

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: runmessageReceivedListener

Event Topic: clonesahibinden-conversation-service-dbevent-conversationmessage-created

When a notification is sent through the clonesahibinden-conversation-service-dbevent-conversationmessage-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 (MessageReceivedNotificationView).

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: runpasswordResetListener

Event Topic: clonesahibinden-auth-service-resetpassword-requested

When a notification is sent through the clonesahibinden-auth-service-resetpassword-requested 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 (UserProfileView).

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: runpremiumPaymentSuccessListener

Event Topic: clonesahibinden-payment-service-dbevent-paymenttransaction-updated

When a notification is sent through the clonesahibinden-payment-service-dbevent-paymenttransaction-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 (PremiumPaymentSuccessNotificationView).

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: clonesahibinden-user-service-email-verification-start

When a notification is sent through the clonesahibinden-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: clonesahibinden-user-service-mobile-verification-start

When a notification is sent through the clonesahibinden-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: clonesahibinden-user-service-password-reset-by-email-start

When a notification is sent through the clonesahibinden-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: clonesahibinden-user-service-password-reset-by-mobile-start

When a notification is sent through the clonesahibinden-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: clonesahibinden-user-service-email-2FA-start

When a notification is sent through the clonesahibinden-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: clonesahibinden-user-service-mobile-2FA-start

When a notification is sent through the clonesahibinden-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