weChess Multiplayer Chess Platform - Complete Documentation

weChess is a real-time multiplayer chess platform featuring lobby and in-game chat, leaderboards, and support for both guest and registered players. The system provides chat moderation, matchmaking (public and private games), ongoing/resumable matches, and administrative tools for game and user management.

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


Table of Contents

Getting Started

Frontend Prompts

Auth Service

Gameplay Service

LobbyChat Service

Leaderboard Service

AgentHub Service

Bff Service

Notification Service

LLM Documents


Getting Started

weChess Multiplayer Chess Platform

weChess Multiplayer Chess Platform

Version : 1.0.174

weChess is a real-time multiplayer chess platform featuring lobby and in-game chat, leaderboards, and support for both guest and registered players. The system provides chat moderation, matchmaking (public and private games), ongoing/resumable matches, and administrative tools for game and user management.

How to Use Project Documents

The Wechess 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://wechess.prw.mindbricks.com/auth-api
Staging https://wechess-stage.mindbricks.co/auth-api
Production https://wechess.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 Wechess 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 weChess Multiplayer Chess 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

gameplay Service

Description: Service for managing real-time chess games, matchmaking, move history, and private invitations, including lifecycle management (mutual game-save/resume, admin termination), supporting both guest and registered users. Enables API access for reviewing games, enforcing moderation actions, and tracking game results.

Documentation:

Base URL Examples:

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

lobbyChat Service

Description: Public lobby chat microservice. Manages create, list, reporting, moderation, and 24-hour message expiry for guest/registered users.

Documentation:

Base URL Examples:

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

leaderboard Service

Description: Handles ELO/stat computation and leaderboard management for registered players only. Excludes guest users entirely.

Documentation:

Base URL Examples:

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

agentHub Service

Description: AI Agent Hub

Documentation:

Base URL Examples:

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

Connect via MCP (Model Context Protocol)

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

Unified MCP Endpoint

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

Authentication

MCP connections require authentication via the Authorization header:

OAuth is not supported for MCP connections at this time.

Connecting from Cursor

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

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

Connecting from Claude Desktop

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

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

What’s Available

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


Conclusion

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

To summarize:

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

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

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


Frontend Prompts

Project Introduction & Setup

WECHESS

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

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

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

Project Introduction

weChess is a real-time multiplayer chess platform featuring lobby and in-game chat, leaderboards, and support for both guest and registered players. The system provides chat moderation, matchmaking (public and private games), ongoing/resumable matches, and administrative tools for game and user management.

Project Services Overview

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

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

# Service Description API Prefix
1 auth Authentication and user management /auth-api
2 gameplay Service for managing real-time chess games, matchmaking, move history, and private invitations, including lifecycle management (mutual game-save/resume, admin termination), supporting both guest and registered users. Enables API access for reviewing games, enforcing moderation actions, and tracking game results. /gameplay-api
3 lobbyChat Public lobby chat microservice. Manages create, list, reporting, moderation, and 24-hour message expiry for guest/registered users. /lobbyChat-api
4 leaderboard Handles ELO/stat computation and leaderboard management for registered players only. Excludes guest users entirely. /leaderboard-api
5 agentHub AI Agent Hub /agentHub-api

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

API Structure

Object Structure of a Successful Response

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

HTTP Status Codes:

Success Response Format:

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

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

Additional Data

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

Error Response

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

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

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

Accessing the Backend

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

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

For the auth service, the base URLs are:

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

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

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

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

Home Page

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

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

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

Initial Navigation Structure

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

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

What To Build Now

With this prompt, build:

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

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

Common Reminders

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

Authentication Management

WECHESS

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

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

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

FRONTEND_URL

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

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

This variable is used by the auth service for:

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

Registration Management

User Registration

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

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

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

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

Register User API

This api is used by public users to register themselves

Rest Route

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

/v1/registeruser

Rest Request Parameters

The registerUser api has got 4 regular request parameters

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

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

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

REST Response

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

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

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

Login Management

Login Identifier Model

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

Login Flow

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

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

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

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

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

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

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

POST /login — User Login

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

Access Routes:

Request Parameters

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

Behavior

Example

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

Success Response

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

}

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

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

Error Responses


POST /logout — User Logout

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

Behavior

Example

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

Notes

Success Response

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

GET /currentuser — Current Session

Purpose Returns the currently authenticated user’s session.

Route Type sessionInfo

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

Request

No parameters.

Example

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

Success (200)

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

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

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

Errors

Notes

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

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

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


Verification Management

WECHESS

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

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

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

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

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

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

Accessing the backend

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

For the auth service, the base URLs are:

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

After User Registration

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

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

Email Verification

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

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

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

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

POST /verification-services/email-verification/start

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

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

Example Request

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

Success Response

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

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

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

Error Responses


POST /verification-services/email-verification/complete

Purpose: Completes verification using the received code.

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

Success Response

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

Error Responses


Mobile Verification

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

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

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

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

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

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

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

Request Body

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

Success Response

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

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

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

Error Responses


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

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

Request Body

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

Success Response

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

Two-Factor Authentication (2FA)

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

How 2FA Works After Login

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

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

2FA Frontend Flow

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

2FA Type Selection

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

Email 2FA Endpoints

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

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

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

Example Request

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

Success Response

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

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

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

Error Responses


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

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

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

Success Response

Returns the updated session with sessionNeedsEmail2FA: false:

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

Error Responses


Mobile 2FA Endpoints

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

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

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

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

Example Request

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

Success Response

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

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

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

Error Responses


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

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

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

Success Response

Returns the updated session with sessionNeedsMobile2FA: false:

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

Error Responses


Important 2FA Notes

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

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


Profile Management

WECHESS

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

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

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

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

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

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

Accessing the backend

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

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

For the auth service, service urls are as follows:

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

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

Avatar Storage (Database Buckets)

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

The auth service provides these avatar buckets:

User Avatar Bucket

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

Upload example (multipart/form-data):

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

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

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

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

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

await updateProfile({ avatar: avatarUrl });

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

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

Listing and Deleting Avatars

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

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

Profile Page

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

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

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

Avatar upload workflow:

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

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

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

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

Get User API

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

Rest Route

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

/v1/users/:userId

Rest Request Parameters

The getUser api has got 1 regular request parameter

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

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

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

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "user",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"user": {
		"id": "ID",
		"email": "String",
		"password": "String",
		"fullname": "String",
		"avatar": "String",
		"roleId": "String",
		"emailVerified": "Boolean",
		"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 3 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”]
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

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",  
    
    },
    params: {
    
        }
  });

REST Response

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

Update Userpassword API

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

Rest Route

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

/v1/userpassword/:userId

Rest Request Parameters

The updateUserPassword api has got 3 regular request parameters

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

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

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

REST Response

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

Archiving A Profile

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

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

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

Archive Profile API

This api is used by users to archive their profiles.

Rest Route

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

/v1/archiveprofile/:userId

Rest Request Parameters

The archiveProfile api has got 1 regular request parameter

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

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

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

REST Response

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

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

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

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


User Management

WECHESS

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

This document is the 2nd part of a REST API guide for the wechess 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 wechess 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: guest registeredPlayer administrator

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

{
  "superAdmin": "'superAdmin'",
  "admin": "'admin'",
  "user": "'user'",
  "guest": "'guest'",
  "registeredPlayer": "'registeredPlayer'",
  "administrator": "'administrator'"
}

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

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

Listing Users

You can list users using the listUsers api.

List Users API

The list of users is filtered by the tenantId.

Rest Route

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

/v1/users

Rest Request Parameters

Filter Parameters

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

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

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

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

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

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

REST Response

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

Searching Users

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

eg: GET /v1/searchusers?keyword=Joe

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

Search Users API

The list of users is filtered by the tenantId.

Rest Route

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

/v1/searchusers

Rest Request Parameters

The searchUsers api has got 1 regular request parameter

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

Filter Parameters

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

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

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

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

REST Response

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

Pagination

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

GET /users?pageNumber=1&pageRowCount=50

Creating Users

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

Create User API

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

Rest Route

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

/v1/users

Rest Request Parameters

The createUser api has got 4 regular request parameters

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

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

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

REST Response

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

Avatar Upload

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

POST {authBaseUrl}/bucket/userAvatars/upload

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

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

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

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

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

Updating Users

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

Update User API

This route is used by admins to update user profiles.

Rest Route

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

/v1/users/:userId

Rest Request Parameters

The updateUser api has got 3 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”]
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

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",  
    
    },
    params: {
    
        }
  });

REST Response

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

For role updates there are some rules.

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

For password updates there are some rules.

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

Update Userrole API

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

Rest Route

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

/v1/userrole/:userId

Rest Request Parameters

The updateUserRole api has got 2 regular request parameters

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

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

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

REST Response

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

Update Userpasswordbyadmin API

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

Rest Route

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

/v1/userpasswordbyadmin/:userId

Rest Request Parameters

The updateUserPasswordByAdmin api has got 2 regular request parameters

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

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

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

REST Response

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

Deleting Users

Deleting users is possible in certain conditions.

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

Delete User API

This api is used by admins to delete user profiles.

Rest Route

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

/v1/users/:userId

Rest Request Parameters

The deleteUser api has got 1 regular request parameter

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

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

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

REST Response

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

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

Avatar Storage (Database Buckets)

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

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

User Avatar Bucket:

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

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


MCP BFF Integration

WECHESS

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

This document is a part of a REST API guide for the wechess 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 Wechess application uses an MCP BFF service that aggregates multiple backend MCP servers into a single frontend-facing API. Instead of the frontend connecting to each service’s MCP endpoint directly, it communicates exclusively through the MCP BFF.

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

Key Responsibilities

MCP BFF Service URLs

For the MCP BFF service, the base URLs are:

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


Authentication

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

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

Chat API (AI Interaction)

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

POST /api/chat — Regular Chat

Send a message and receive the complete AI response.

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

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

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

Request:

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

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

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

SSE Event Types

The streaming endpoint emits the following event types in order:

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

SSE Event Data Reference

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

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

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

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

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

{ "tool": "currentuser" }

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

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

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

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

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

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

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

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

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

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

SSE Event Lifecycle

A typical conversation stream follows this lifecycle:

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

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

Inline Segment Rendering (Critical UX Pattern)

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

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

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

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

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

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

Parsing SSE Events (Frontend Implementation)

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

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

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

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

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

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

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

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

Building the Segments Array (React Example)

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

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

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

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

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

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

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

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

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

Rendering the Message Bubble

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

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

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

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

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

Handling __frontendAction in Tool Results

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

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

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

Frontend Action Types

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

QR Code Action (type: "qrcode")

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

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

Data View Action (type: "dataView")

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

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

Payment Action (type: "payment")

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

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

Conversation Management

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

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

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

MCP Tool Discovery & Direct Invocation

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

GET /api/tools — List All Tools

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

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

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

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

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

GET /api/tools/status — Connection Status

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

POST /api/tools/refresh — Reconnect Services

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

Elasticsearch API

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

All Elasticsearch endpoints are under /api/elastic.

GET /api/elastic/allIndices — List Project Indices

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

const indices = await fetch(`${mcpBffUrl}/api/elastic/allIndices`, { headers });
// ["wechess_products", "wechess_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 wechess_ 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
gameplay Service for managing real-time chess games, matchmaking, move history, and private invitations, including lifecycle management (mutual game-save/resume, admin termination), supporting both guest and registered users. Enables API access for reviewing games, enforcing moderation actions, and tracking game results.
lobbyChat Public lobby chat microservice. Manages create, list, reporting, moderation, and 24-hour message expiry for guest/registered users.
leaderboard Handles ELO/stat computation and leaderboard management for registered players only. Excludes guest users entirely.
agentHub AI Agent Hub

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


MCP as Internal API Gateway

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

Direct Tool Calls (REST)

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

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

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

AI-Orchestrated Calls (Chat API)

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

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


MCP Connection Info for Profile Page

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

What to Display

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

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

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

Profile Page UI Requirements

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

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

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

    Cursor (.cursor/mcp.json):

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

    Claude Desktop (claude_desktop_config.json):

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

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

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


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


Gameplay Service

WECHESS

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

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

Service Access

Gameplay service management is handled through service specific base urls.

Gameplay 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 gameplay service, the base URLs are:

Scope

Gameplay Service Description

Service for managing real-time chess games, matchmaking, move history, and private invitations, including lifecycle management (mutual game-save/resume, admin termination), supporting both guest and registered users. Enables API access for reviewing games, enforcing moderation actions, and tracking game results.

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

chessGame Data Object:

chessGameMove Data Object: Represents a single move in a chess game (FIDE-compliant SAN/LAN representation, timestamp, player, time, move number).

chessGameInvitation Data Object: An invitation for a private chess game between two players; status tracked; expires at set time or when accepted/declined.

customBoard Data Object:

boardTheme Data Object:

userPreference Data Object:

gameHubMessage Data Object: Auto-generated message DataObject for the gameHub RealtimeHub. Stores all messages with typed content payloads.

gameHubModeration Data Object: Auto-generated moderation DataObject for the gameHub RealtimeHub. Stores block and silence actions for room-level user moderation.

Gameplay Service Frontend Description By The Backend Architect

Focuses on all server-side logic for chess sessions, matchmaking flows, move recording, lifecycle events, and admin moderation features. Games may be public (matched) or private (via invitation code); history and result calculations are managed herein. Guests are supported in games but leaderboards/stats are maintained only for registered players (handled by leaderboard service). Admin UIs use advanced query/list/review APIs for game and event history. Special actions are available for mutual save/resume agreements and forced admin interrupts.

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

ChessGame Data Object

ChessGame Data Object Properties

ChessGame 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
playerWhiteId ID false Yes No User ID of the player assigned White (guest or registered); references auth:user.id.
playerBlackId ID No No -
createdById ID false Yes No ID of the user who created the game (can be a guest or registered user).
status Enum false Yes No Lifecycle status: pending, active, paused, completed, terminated
mode Enum false Yes No Game mode: public (matchmaking), private (invitation-based)
invitationCode String No No -
currentFEN String false Yes No Current board state in FEN notation for restoration/resume.
gameType Enum false Yes No Game type: timed, untimed, blitz, rapid
saveStatus Enum false Yes No Game mutual-saving: notSaveable, requested, paused (both agreed)
saveRequestWhite Boolean false No No Whether white has requested save/resume; mutual save when both true.
saveRequestBlack Boolean false No No Whether black has requested save/resume; mutual save when both true.
movedAt Date false No No Timestamp of last move (heartbeat/game activity).
result Enum false No No Game result/outcome: whiteWin, blackWin, draw, aborted
terminatedById ID false No No ID of administrator who forced terminated the game (if applicable).
reportStatus Enum false No No Moderation/review status: none, reported, underReview
guestPlayerWhite Boolean false No No True if white is a guest (not a registered user); needed to distinguish guest/registered in history.
guestPlayerBlack Boolean false No No True if black is a guest (not a registered user); needed to distinguish guest/registered in history.
initialFEN String false No No The starting FEN position when the game was created. Used to identify custom games.

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

playerWhiteId playerBlackId createdById terminatedById

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

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

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

status invitationCode

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.

ChessGameMove Data Object

Represents a single move in a chess game (FIDE-compliant SAN/LAN representation, timestamp, player, time, move number).

ChessGameMove Data Object Frontend Description By The Backend Architect

Every legal move in a chess game is stored as its own chessGameMove. Only admins or participants can create (add) moves. Used for reconstructing history and post-game analysis. Move time is stored for potential time control.

ChessGameMove Data Object Properties

ChessGameMove 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
gameId ID false Yes No Reference to the chessGame this move belongs to.
moveNumber Integer false Yes No Move number (starting from 1 in each game).
moveNotation String false Yes No Chess move in either Standard Algebraic or Long Algebraic Notation (SAN/LAN).
moveTime Integer false No No Time in milliseconds since the previous move (for time control, etc.).
movedById ID false Yes No User ID of the player who made the move (guest/registered); references auth:user.id.
moveTimestamp Date false Yes No Timestamp when move was made.

Relation Properties

gameId movedById

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

In frontend, please ensure that,

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

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

Required: Yes

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

Required: No

Filter Properties

gameId

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.

ChessGameInvitation Data Object

An invitation for a private chess game between two players; status tracked; expires at set time or when accepted/declined.

ChessGameInvitation Data Object Frontend Description By The Backend Architect

Create chessGameInvitation for private games. Used to notify recipient, with acceptance establishing game session. Expiration is enforced. Sender/recipient are references to user (guest or registered). Invalidation logic on decline/cancel/expiry. Invitation code is managed with target game.

ChessGameInvitation Data Object Properties

ChessGameInvitation 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
gameId ID false Yes No Game this invitation is linked to.
senderId ID Yes No -
recipientId ID Yes No -
status Enum Yes No -
expiresAt Date false Yes No Expiration date/time for the invitation.

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

gameId senderId recipientId

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

In frontend, please ensure that,

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

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

Required: Yes

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

Required: No

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

Required: No

Filter Properties

senderId recipientId status

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

CustomBoard Data Object

CustomBoard Data Object Properties

CustomBoard 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
name String false Yes No Name of the custom board position
fen String false Yes No FEN string representing the board position
description Text false No No Optional description of the custom board
isPublished Boolean Yes No -
category Enum Yes No -
createdById ID Yes No -

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

createdById

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

isPublished category createdById

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.

BoardTheme Data Object

BoardTheme Data Object Properties

BoardTheme 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
name String false Yes No Theme display name
lightSquare String false Yes No Hex color for light squares
darkSquare String false Yes No Hex color for dark squares
isPublished Boolean false No No Whether the theme is publicly visible
createdById ID false Yes No User who created this theme

Relation Properties

createdById

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

isPublished

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.

UserPreference Data Object

UserPreference Data Object Properties

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

Property Type IsArray Required Secret Description
userId ID false Yes No The user this preferences record belongs to
activeThemeId String false No No ID of the currently selected board theme (preset ID or custom theme ID)
soundEnabled Boolean false No No Whether game sounds are enabled
showAnimations Boolean false No No Whether board animations are shown
boardOrientation Enum false No No Default board orientation preference
premoveEnabled Boolean false No No Whether premove feature is enabled

Enum Properties

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

Relation Properties

userId

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

GameHubMessage Data Object

Auto-generated message DataObject for the gameHub RealtimeHub. Stores all messages with typed content payloads.

GameHubMessage Data Object Properties

GameHubMessage 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
roomId ID false Yes No Reference to the room this message belongs to
senderId ID false No No Reference to the user who sent this message
senderName String false No No Display name of the sender (denormalized from user profile at send time)
senderAvatar String false No No Avatar URL of the sender (denormalized from user profile at send time)
messageType Enum false Yes No Content type discriminator for this message
content Object false Yes No Type-specific content payload (structure depends on messageType)
timestamp false No No Message creation time
status Enum false No No Message moderation status

Enum Properties

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

Filter Properties

roomId senderId senderName senderAvatar messageType content timestamp status

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

GameHubModeration Data Object

Auto-generated moderation DataObject for the gameHub RealtimeHub. Stores block and silence actions for room-level user moderation.

GameHubModeration Data Object Properties

GameHubModeration 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
roomId ID false Yes No Reference to the room where the moderation action applies
userId ID false Yes No The user who is blocked or silenced
action Enum false Yes No Moderation action type
reason Text false No No Optional reason for the moderation action
duration Integer false No No Duration in seconds. 0 means permanent
expiresAt false No No Expiry timestamp. Null means permanent
issuedBy ID false No No The moderator who issued the action

Enum Properties

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

Relation Properties

roomId

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

roomId userId action reason duration expiresAt issuedBy

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.

ChessGame Default APIs

Operation API Name Route Explicitly Set
Create createGame /v1/game Yes
Update updateGame /v1/game/:chessGameId Yes
Delete deleteGame /v1/game/:chessGameId Yes
Get getGame /v1/game/:chessGameId Yes
List listGames /v1/games Yes

ChessGameMove Default APIs

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

Operation API Name Route Explicitly Set
Create createGameMove /v1/gamemove Yes
Update none - Auto
Delete none - Auto
Get none - Auto
List listGameMoves /v1/gamemoves Yes

ChessGameInvitation Default APIs

Operation API Name Route Explicitly Set
Create createGameInvitation /v1/gameinvitation Yes
Update updateGameInvitation /v1/gameinvitation/:chessGameInvitationId Yes
Delete deleteGameInvitation /v1/gameinvitation/:chessGameInvitationId Auto
Get none - Auto
List listGameInvitations /v1/gameinvitations Yes

CustomBoard Default APIs

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

Operation API Name Route Explicitly Set
Create createCustomBoard /v1/customboards Yes
Update updateCustomBoard /v1/customboards/:customBoardId Yes
Delete deleteCustomBoard /v1/customboards/:customBoardId Yes
Get getCustomBoard /v1/customboards/:customBoardId Yes
List listCustomBoards /v1/customboards Yes

BoardTheme Default APIs

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

Operation API Name Route Explicitly Set
Create createBoardTheme /v1/boardthemes Yes
Update updateBoardTheme /v1/boardthemes/:boardThemeId Yes
Delete deleteBoardTheme /v1/boardthemes/:boardThemeId Yes
Get none - Auto
List listBoardThemes /v1/boardthemes Yes

UserPreference Default APIs

Operation API Name Route Explicitly Set
Create createUserPreference /v1/userpreferences Yes
Update updateUserPreference /v1/userpreferences/:userPreferenceId Yes
Delete none - Auto
Get getUserPreference /v1/userpreferences/:userPreferenceId Yes
List listUserPreferences /v1/userpreferences Yes

GameHubMessage Default APIs

Operation API Name Route Explicitly Set
Create none - Auto
Update updateGameHubMessage /v1/v1/gameHub-messages/:id Yes
Delete deleteGameHubMessage /v1/v1/gameHub-messages/:id Yes
Get getGameHubMessage /v1/v1/gameHub-messages/:id Yes
List listGameHubMessages /v1/v1/gameHub-messages Yes

GameHubModeration Default APIs

Operation API Name Route Explicitly Set
Create none - Auto
Update none - Auto
Delete none - Auto
Get none - Auto
List none - Auto

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

[Default create API] — This is the designated default create API for the chessGame data object. Frontend generators and AI agents should use this API for standard CRUD operations. Starts a new chess game session (public or private). Sets up all initial state, assigns player roles, and sets mode.

API Frontend Description By The Backend Architect

Called when matchmaking or private game is created. Invited/private games have invitationCode. Only logged-in users (guest or registered) can create games. Raise event for gameCreated for notification/bff.

Rest Route

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

/v1/game

Rest Request Parameters

The createGame api has got 18 regular request parameters

Parameter Type Required Population
playerWhiteId ID true request.body?.[“playerWhiteId”]
playerBlackId ID false request.body?.[“playerBlackId”]
createdById ID true request.body?.[“createdById”]
status Enum true request.body?.[“status”]
mode Enum true request.body?.[“mode”]
invitationCode String false request.body?.[“invitationCode”]
currentFEN String true request.body?.[“currentFEN”]
gameType Enum true request.body?.[“gameType”]
saveStatus Enum true request.body?.[“saveStatus”]
saveRequestWhite Boolean false request.body?.[“saveRequestWhite”]
saveRequestBlack Boolean false request.body?.[“saveRequestBlack”]
movedAt Date false request.body?.[“movedAt”]
result Enum false request.body?.[“result”]
terminatedById ID false request.body?.[“terminatedById”]
reportStatus Enum false request.body?.[“reportStatus”]
guestPlayerWhite Boolean false request.body?.[“guestPlayerWhite”]
guestPlayerBlack Boolean false request.body?.[“guestPlayerBlack”]
initialFEN String false request.body?.[“initialFEN”]
playerWhiteId : User ID of the player assigned White (guest or registered); references auth:user.id.
playerBlackId :
createdById : ID of the user who created the game (can be a guest or registered user).
status : Lifecycle status: pending, active, paused, completed, terminated
mode : Game mode: public (matchmaking), private (invitation-based)
invitationCode :
currentFEN : Current board state in FEN notation for restoration/resume.
gameType : Game type: timed, untimed, blitz, rapid
saveStatus : Game mutual-saving: notSaveable, requested, paused (both agreed)
saveRequestWhite : Whether white has requested save/resume; mutual save when both true.
saveRequestBlack : Whether black has requested save/resume; mutual save when both true.
movedAt : Timestamp of last move (heartbeat/game activity).
result : Game result/outcome: whiteWin, blackWin, draw, aborted
terminatedById : ID of administrator who forced terminated the game (if applicable).
reportStatus : Moderation/review status: none, reported, underReview
guestPlayerWhite : True if white is a guest (not a registered user); needed to distinguish guest/registered in history.
guestPlayerBlack : True if black is a guest (not a registered user); needed to distinguish guest/registered in history.
initialFEN : The starting FEN position when the game was created. Used to identify custom games.

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

  axios({
    method: 'POST',
    url: '/v1/game',
    data: {
            playerWhiteId:"ID",  
            playerBlackId:"ID",  
            createdById:"ID",  
            status:"Enum",  
            mode:"Enum",  
            invitationCode:"String",  
            currentFEN:"String",  
            gameType:"Enum",  
            saveStatus:"Enum",  
            saveRequestWhite:"Boolean",  
            saveRequestBlack:"Boolean",  
            movedAt:"Date",  
            result:"Enum",  
            terminatedById:"ID",  
            reportStatus:"Enum",  
            guestPlayerWhite:"Boolean",  
            guestPlayerBlack:"Boolean",  
            initialFEN:"String",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "chessGame",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"chessGame": {
		"id": "ID",
		"playerWhiteId": "ID",
		"playerBlackId": "ID",
		"createdById": "ID",
		"status": "Enum",
		"status_idx": "Integer",
		"mode": "Enum",
		"mode_idx": "Integer",
		"invitationCode": "String",
		"currentFEN": "String",
		"gameType": "Enum",
		"gameType_idx": "Integer",
		"saveStatus": "Enum",
		"saveStatus_idx": "Integer",
		"saveRequestWhite": "Boolean",
		"saveRequestBlack": "Boolean",
		"movedAt": "Date",
		"result": "Enum",
		"result_idx": "Integer",
		"terminatedById": "ID",
		"reportStatus": "Enum",
		"reportStatus_idx": "Integer",
		"guestPlayerWhite": "Boolean",
		"guestPlayerBlack": "Boolean",
		"initialFEN": "String",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Update Game API

[Default update API] — This is the designated default update API for the chessGame data object. Frontend generators and AI agents should use this API for standard CRUD operations. Updates chess game state including board position, status, save flags etc. Auth: only participants or admin.

API Frontend Description By The Backend Architect

Used for updating board state, status, mutual saving, etc. Most fields are read-only after game completion/termination except by admin. Raise event for gameUpdated for notification/bff.

Rest Route

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

/v1/game/:chessGameId

Rest Request Parameters

The updateGame api has got 13 regular request parameters

Parameter Type Required Population
chessGameId ID true request.params?.[“chessGameId”]
playerBlackId ID request.body?.[“playerBlackId”]
status Enum false request.body?.[“status”]
currentFEN String false request.body?.[“currentFEN”]
saveStatus Enum false request.body?.[“saveStatus”]
saveRequestWhite Boolean false request.body?.[“saveRequestWhite”]
saveRequestBlack Boolean false request.body?.[“saveRequestBlack”]
movedAt Date false request.body?.[“movedAt”]
result Enum false request.body?.[“result”]
terminatedById ID false request.body?.[“terminatedById”]
reportStatus Enum false request.body?.[“reportStatus”]
guestPlayerWhite Boolean false request.body?.[“guestPlayerWhite”]
guestPlayerBlack Boolean false request.body?.[“guestPlayerBlack”]
chessGameId : This id paremeter is used to select the required data object that will be updated
playerBlackId :
status : Lifecycle status: pending, active, paused, completed, terminated
currentFEN : Current board state in FEN notation for restoration/resume.
saveStatus : Game mutual-saving: notSaveable, requested, paused (both agreed)
saveRequestWhite : Whether white has requested save/resume; mutual save when both true.
saveRequestBlack : Whether black has requested save/resume; mutual save when both true.
movedAt : Timestamp of last move (heartbeat/game activity).
result : Game result/outcome: whiteWin, blackWin, draw, aborted
terminatedById : ID of administrator who forced terminated the game (if applicable).
reportStatus : Moderation/review status: none, reported, underReview
guestPlayerWhite : True if white is a guest (not a registered user); needed to distinguish guest/registered in history.
guestPlayerBlack : True if black is a guest (not a registered user); needed to distinguish guest/registered in history.

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

  axios({
    method: 'PATCH',
    url: `/v1/game/${chessGameId}`,
    data: {
            playerBlackId:"ID",  
            status:"Enum",  
            currentFEN:"String",  
            saveStatus:"Enum",  
            saveRequestWhite:"Boolean",  
            saveRequestBlack:"Boolean",  
            movedAt:"Date",  
            result:"Enum",  
            terminatedById:"ID",  
            reportStatus:"Enum",  
            guestPlayerWhite:"Boolean",  
            guestPlayerBlack:"Boolean",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "chessGame",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"chessGame": {
		"id": "ID",
		"playerWhiteId": "ID",
		"playerBlackId": "ID",
		"createdById": "ID",
		"status": "Enum",
		"status_idx": "Integer",
		"mode": "Enum",
		"mode_idx": "Integer",
		"invitationCode": "String",
		"currentFEN": "String",
		"gameType": "Enum",
		"gameType_idx": "Integer",
		"saveStatus": "Enum",
		"saveStatus_idx": "Integer",
		"saveRequestWhite": "Boolean",
		"saveRequestBlack": "Boolean",
		"movedAt": "Date",
		"result": "Enum",
		"result_idx": "Integer",
		"terminatedById": "ID",
		"reportStatus": "Enum",
		"reportStatus_idx": "Integer",
		"guestPlayerWhite": "Boolean",
		"guestPlayerBlack": "Boolean",
		"initialFEN": "String",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Delete Game API

[Default delete API] — This is the designated default delete API for the chessGame data object. Frontend generators and AI agents should use this API for standard CRUD operations. Deletes a chess game (soft-delete). Only allowed for admins or system cleanup.

API Frontend Description By The Backend Architect

Hard deletion not recommended; soft-deletion disables user/game access. Used for moderation/cleanup only. Regular users cannot delete games. Raise event for gameDeleted for moderation/audit.

Rest Route

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

/v1/game/:chessGameId

Rest Request Parameters

The deleteGame api has got 1 regular request parameter

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

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

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "chessGame",
	"method": "DELETE",
	"action": "delete",
	"appVersion": "Version",
	"rowCount": 1,
	"chessGame": {
		"id": "ID",
		"playerWhiteId": "ID",
		"playerBlackId": "ID",
		"createdById": "ID",
		"status": "Enum",
		"status_idx": "Integer",
		"mode": "Enum",
		"mode_idx": "Integer",
		"invitationCode": "String",
		"currentFEN": "String",
		"gameType": "Enum",
		"gameType_idx": "Integer",
		"saveStatus": "Enum",
		"saveStatus_idx": "Integer",
		"saveRequestWhite": "Boolean",
		"saveRequestBlack": "Boolean",
		"movedAt": "Date",
		"result": "Enum",
		"result_idx": "Integer",
		"terminatedById": "ID",
		"reportStatus": "Enum",
		"reportStatus_idx": "Integer",
		"guestPlayerWhite": "Boolean",
		"guestPlayerBlack": "Boolean",
		"initialFEN": "String",
		"isActive": false,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Get Game API

[Default get API] — This is the designated default get API for the chessGame data object. Frontend generators and AI agents should use this API for standard CRUD operations. Fetch a single chess game by ID. Only participants, admin, or invitation recipient may access.

API Frontend Description By The Backend Architect

Retrieve all game details and limited move history for preview/study. If user is not participant, must check invitation. Raise event for gameFetched.

Rest Route

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

/v1/game/:chessGameId

Rest Request Parameters

The getGame api has got 1 regular request parameter

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

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

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "chessGame",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"chessGame": {
		"id": "ID",
		"playerWhiteId": "ID",
		"playerBlackId": "ID",
		"createdById": "ID",
		"status": "Enum",
		"status_idx": "Integer",
		"mode": "Enum",
		"mode_idx": "Integer",
		"invitationCode": "String",
		"currentFEN": "String",
		"gameType": "Enum",
		"gameType_idx": "Integer",
		"saveStatus": "Enum",
		"saveStatus_idx": "Integer",
		"saveRequestWhite": "Boolean",
		"saveRequestBlack": "Boolean",
		"movedAt": "Date",
		"result": "Enum",
		"result_idx": "Integer",
		"terminatedById": "ID",
		"reportStatus": "Enum",
		"reportStatus_idx": "Integer",
		"guestPlayerWhite": "Boolean",
		"guestPlayerBlack": "Boolean",
		"initialFEN": "String",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"moves": [
			{
				"moveNumber": "Integer",
				"moveNotation": "String",
				"moveTime": "Integer",
				"movedById": "ID",
				"moveTimestamp": "Date"
			},
			{},
			{}
		]
	}
}

List Games API

[Default list API] — This is the designated default list API for the chessGame data object. Frontend generators and AI agents should use this API for standard CRUD operations. List chess games by participant or admin query. Supports filtering by status, participants, mode, etc.

API Frontend Description By The Backend Architect

Used for history browsing, admin review, or finding ongoing/mutually saved games. Raise event for gameListFetched for audit/UX.

Rest Route

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

/v1/games

Rest Request Parameters

Filter Parameters

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

status (Enum): Lifecycle status: pending, active, paused, completed, terminated

invitationCode (String): Filter by invitationCode

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

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

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "chessGames",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"chessGames": [
		{
			"id": "ID",
			"playerWhiteId": "ID",
			"playerBlackId": "ID",
			"createdById": "ID",
			"status": "Enum",
			"status_idx": "Integer",
			"mode": "Enum",
			"mode_idx": "Integer",
			"invitationCode": "String",
			"currentFEN": "String",
			"gameType": "Enum",
			"gameType_idx": "Integer",
			"saveStatus": "Enum",
			"saveStatus_idx": "Integer",
			"saveRequestWhite": "Boolean",
			"saveRequestBlack": "Boolean",
			"movedAt": "Date",
			"result": "Enum",
			"result_idx": "Integer",
			"terminatedById": "ID",
			"reportStatus": "Enum",
			"reportStatus_idx": "Integer",
			"guestPlayerWhite": "Boolean",
			"guestPlayerBlack": "Boolean",
			"initialFEN": "String",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID"
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Create Gamemove API

[Default create API] — This is the designated default create API for the chessGameMove data object. Frontend generators and AI agents should use this API for standard CRUD operations. Record a move in an ongoing chess game. Only participants or admin can add moves.

API Frontend Description By The Backend Architect

Called in-order for each legitimate move. Ensures move sequence is preserved. Move time and timestamp acquired on submit. Raises event for moveAdded.

Rest Route

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

/v1/gamemove

Rest Request Parameters

The createGameMove api has got 6 regular request parameters

Parameter Type Required Population
gameId ID true request.body?.[“gameId”]
moveNumber Integer true request.body?.[“moveNumber”]
moveNotation String true request.body?.[“moveNotation”]
moveTime Integer false request.body?.[“moveTime”]
movedById ID true request.body?.[“movedById”]
moveTimestamp Date true request.body?.[“moveTimestamp”]
gameId : Reference to the chessGame this move belongs to.
moveNumber : Move number (starting from 1 in each game).
moveNotation : Chess move in either Standard Algebraic or Long Algebraic Notation (SAN/LAN).
moveTime : Time in milliseconds since the previous move (for time control, etc.).
movedById : User ID of the player who made the move (guest/registered); references auth:user.id.
moveTimestamp : Timestamp when move was made.

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

  axios({
    method: 'POST',
    url: '/v1/gamemove',
    data: {
            gameId:"ID",  
            moveNumber:"Integer",  
            moveNotation:"String",  
            moveTime:"Integer",  
            movedById:"ID",  
            moveTimestamp:"Date",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "chessGameMove",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"chessGameMove": {
		"id": "ID",
		"gameId": "ID",
		"moveNumber": "Integer",
		"moveNotation": "String",
		"moveTime": "Integer",
		"movedById": "ID",
		"moveTimestamp": "Date",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

List Gamemoves API

[Default list API] — This is the designated default list API for the chessGameMove data object. Frontend generators and AI agents should use this API for standard CRUD operations. List moves for a given game. Only participants or admin can view.

API Frontend Description By The Backend Architect

Used for reviewing game history/study. Returns moves ordered by moveNumber asc.

Rest Route

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

/v1/gamemoves

Rest Request Parameters

Filter Parameters

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

gameId (ID): Reference to the chessGame this move belongs to.

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

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

REST Response

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

Create Gameinvitation API

[Default create API] — This is the designated default create API for the chessGameInvitation data object. Frontend generators and AI agents should use this API for standard CRUD operations. Send an invitation for a private chess game to a user (guest or registered).

API Frontend Description By The Backend Architect

Used for starting private games. Invitation auto-invalidates on expiry. Raise event for invitationSent for notification.

Rest Route

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

/v1/gameinvitation

Rest Request Parameters

The createGameInvitation api has got 5 regular request parameters

Parameter Type Required Population
gameId ID true request.body?.[“gameId”]
senderId ID true request.body?.[“senderId”]
recipientId ID true request.body?.[“recipientId”]
status Enum true request.body?.[“status”]
expiresAt Date true request.body?.[“expiresAt”]
gameId : Game this invitation is linked to.
senderId :
recipientId :
status :
expiresAt : Expiration date/time for the invitation.

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

  axios({
    method: 'POST',
    url: '/v1/gameinvitation',
    data: {
            gameId:"ID",  
            senderId:"ID",  
            recipientId:"ID",  
            status:"Enum",  
            expiresAt:"Date",  
    
    },
    params: {
    
        }
  });

REST Response

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

Update Gameinvitation API

[Default update API] — This is the designated default update API for the chessGameInvitation data object. Frontend generators and AI agents should use this API for standard CRUD operations. Update the status or expiry of a game invitation (accept, decline, cancel, expire). Only sender, recipient, or admin can change status.

API Frontend Description By The Backend Architect

Used for invitation workflow (accept, decline, cancel); handled securely as only involved users or admin can update. Event is raised for notification.

Rest Route

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

/v1/gameinvitation/:chessGameInvitationId

Rest Request Parameters

The updateGameInvitation api has got 5 regular request parameters

Parameter Type Required Population
chessGameInvitationId ID true request.params?.[“chessGameInvitationId”]
senderId ID request.body?.[“senderId”]
recipientId ID request.body?.[“recipientId”]
status Enum request.body?.[“status”]
expiresAt Date false request.body?.[“expiresAt”]
chessGameInvitationId : This id paremeter is used to select the required data object that will be updated
senderId :
recipientId :
status :
expiresAt : Expiration date/time for the invitation.

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

  axios({
    method: 'PATCH',
    url: `/v1/gameinvitation/${chessGameInvitationId}`,
    data: {
            senderId:"ID",  
            recipientId:"ID",  
            status:"Enum",  
            expiresAt:"Date",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "chessGameInvitation",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"chessGameInvitation": {
		"id": "ID",
		"gameId": "ID",
		"senderId": "ID",
		"recipientId": "ID",
		"status": "Enum",
		"status_idx": "Integer",
		"expiresAt": "Date",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Delete Gameinvitation API

Delete a game invitation (soft-deletes); only admin may do this for moderation/cleanup.

API Frontend Description By The Backend Architect

Not available to normal users. Moderation purposes only. Raise event for invitationRemoved for mods.

Rest Route

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

/v1/gameinvitation/:chessGameInvitationId

Rest Request Parameters

The deleteGameInvitation api has got 1 regular request parameter

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

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

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "chessGameInvitation",
	"method": "DELETE",
	"action": "delete",
	"appVersion": "Version",
	"rowCount": 1,
	"chessGameInvitation": {
		"id": "ID",
		"gameId": "ID",
		"senderId": "ID",
		"recipientId": "ID",
		"status": "Enum",
		"status_idx": "Integer",
		"expiresAt": "Date",
		"isActive": false,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

List Gameinvitations API

[Default list API] — This is the designated default list API for the chessGameInvitation data object. Frontend generators and AI agents should use this API for standard CRUD operations. List game invitations. Supports filtering by recipientId, senderId, status, gameId.

API Frontend Description By The Backend Architect

Used to show pending invitations to a user, or to list all invitations for a game.

Rest Route

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

/v1/gameinvitations

Rest Request Parameters

Filter Parameters

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

senderId (ID): Filter by senderId

recipientId (ID): Filter by recipientId

status (Enum): Filter by status

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

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

REST Response

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

Create Customboard API

[Default create API] — This is the designated default create API for the customBoard data object. Frontend generators and AI agents should use this API for standard CRUD operations. Create a new custom chess board position. Any logged-in user can create boards.

API Frontend Description By The Backend Architect

Called when a user saves a custom board position from the board editor. createdById is auto-set from session.

Rest Route

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

/v1/customboards

Rest Request Parameters

The createCustomBoard api has got 6 regular request parameters

Parameter Type Required Population
name String true request.body?.[“name”]
fen String true request.body?.[“fen”]
description Text false request.body?.[“description”]
isPublished Boolean true request.body?.[“isPublished”]
category Enum true request.body?.[“category”]
createdById ID true request.body?.[“createdById”]
name : Name of the custom board position
fen : FEN string representing the board position
description : Optional description of the custom board
isPublished :
category :
createdById :

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

  axios({
    method: 'POST',
    url: '/v1/customboards',
    data: {
            name:"String",  
            fen:"String",  
            description:"Text",  
            isPublished:"Boolean",  
            category:"Enum",  
            createdById:"ID",  
    
    },
    params: {
    
        }
  });

REST Response

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

List Customboards API

[Default list API] — This is the designated default list API for the customBoard data object. Frontend generators and AI agents should use this API for standard CRUD operations. List custom board positions. Supports filtering by isPublished, category, and createdById.

API Frontend Description By The Backend Architect

Used to browse published community boards or user’s own boards. Filter by isPublished=true for public boards.

Rest Route

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

/v1/customboards

Rest Request Parameters

Filter Parameters

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

isPublished (Boolean): Filter by isPublished

category (Enum): Filter by category

createdById (ID): Filter by createdById

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

  axios({
    method: 'GET',
    url: '/v1/customboards',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section above)
        // isPublished: '<value>' // Filter by isPublished
        // category: '<value>' // Filter by category
        // createdById: '<value>' // Filter by createdById
            }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "customBoards",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"customBoards": [
		{
			"id": "ID",
			"name": "String",
			"fen": "String",
			"description": "Text",
			"isPublished": "Boolean",
			"category": "Enum",
			"category_idx": "Integer",
			"createdById": "ID",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID"
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Get Customboard API

[Default get API] — This is the designated default get API for the customBoard data object. Frontend generators and AI agents should use this API for standard CRUD operations. Fetch a single custom board position by ID.

API Frontend Description By The Backend Architect

Used to load a specific custom board for editing or playing.

Rest Route

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

/v1/customboards/:customBoardId

Rest Request Parameters

The getCustomBoard api has got 1 regular request parameter

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

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

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "customBoard",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"customBoard": {
		"id": "ID",
		"name": "String",
		"fen": "String",
		"description": "Text",
		"isPublished": "Boolean",
		"category": "Enum",
		"category_idx": "Integer",
		"createdById": "ID",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Update Customboard API

[Default update API] — This is the designated default update API for the customBoard data object. Frontend generators and AI agents should use this API for standard CRUD operations. Update a custom board position. Only the creator can update their own boards.

API Frontend Description By The Backend Architect

Used to edit board name, description, FEN, category, or publish/unpublish.

Rest Route

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

/v1/customboards/:customBoardId

Rest Request Parameters

The updateCustomBoard api has got 7 regular request parameters

Parameter Type Required Population
customBoardId ID true request.params?.[“customBoardId”]
name String false request.body?.[“name”]
fen String false request.body?.[“fen”]
description Text false request.body?.[“description”]
isPublished Boolean request.body?.[“isPublished”]
category Enum request.body?.[“category”]
createdById ID request.body?.[“createdById”]
customBoardId : This id paremeter is used to select the required data object that will be updated
name : Name of the custom board position
fen : FEN string representing the board position
description : Optional description of the custom board
isPublished :
category :
createdById :

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

  axios({
    method: 'PATCH',
    url: `/v1/customboards/${customBoardId}`,
    data: {
            name:"String",  
            fen:"String",  
            description:"Text",  
            isPublished:"Boolean",  
            category:"Enum",  
            createdById:"ID",  
    
    },
    params: {
    
        }
  });

REST Response

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

Delete Customboard API

[Default delete API] — This is the designated default delete API for the customBoard data object. Frontend generators and AI agents should use this API for standard CRUD operations. Delete a custom board position (soft-delete). Only creator or admin can delete.

API Frontend Description By The Backend Architect

Used to remove a custom board. Soft-deletes so data can be recovered if needed.

Rest Route

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

/v1/customboards/:customBoardId

Rest Request Parameters

The deleteCustomBoard api has got 1 regular request parameter

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

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

REST Response

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

Create Boardtheme API

[Default create API] — This is the designated default create API for the boardTheme data object. Frontend generators and AI agents should use this API for standard CRUD operations. Create a custom board color theme.

API Frontend Description By The Backend Architect

Called when user saves a new custom theme from the themes picker.

Rest Route

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

/v1/boardthemes

Rest Request Parameters

The createBoardTheme api has got 4 regular request parameters

Parameter Type Required Population
name String true request.body?.[“name”]
lightSquare String true request.body?.[“lightSquare”]
darkSquare String true request.body?.[“darkSquare”]
createdById ID true request.body?.[“createdById”]
name : Theme display name
lightSquare : Hex color for light squares
darkSquare : Hex color for dark squares
createdById : User who created this theme

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

  axios({
    method: 'POST',
    url: '/v1/boardthemes',
    data: {
            name:"String",  
            lightSquare:"String",  
            darkSquare:"String",  
            createdById:"ID",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "boardTheme",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"boardTheme": {
		"id": "ID",
		"name": "String",
		"lightSquare": "String",
		"darkSquare": "String",
		"isPublished": "Boolean",
		"createdById": "ID",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

List Boardthemes API

[Default list API] — This is the designated default list API for the boardTheme data object. Frontend generators and AI agents should use this API for standard CRUD operations. List board themes. Filter by isPublished for community themes or createdById for user’s own.

API Frontend Description By The Backend Architect

Used to load user’s custom themes and community-published themes.

Rest Route

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

/v1/boardthemes

Rest Request Parameters

Filter Parameters

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

isPublished (Boolean): Whether the theme is publicly visible

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

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

REST Response

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

Update Boardtheme API

[Default update API] — This is the designated default update API for the boardTheme data object. Frontend generators and AI agents should use this API for standard CRUD operations. Update a custom board theme. Only creator can update.

API Frontend Description By The Backend Architect

Used to edit theme colors/name or publish/unpublish.

Rest Route

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

/v1/boardthemes/:boardThemeId

Rest Request Parameters

The updateBoardTheme api has got 5 regular request parameters

Parameter Type Required Population
boardThemeId ID true request.params?.[“boardThemeId”]
name String false request.body?.[“name”]
lightSquare String false request.body?.[“lightSquare”]
darkSquare String false request.body?.[“darkSquare”]
isPublished Boolean false request.body?.[“isPublished”]
boardThemeId : This id paremeter is used to select the required data object that will be updated
name : Theme display name
lightSquare : Hex color for light squares
darkSquare : Hex color for dark squares
isPublished : Whether the theme is publicly visible

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

  axios({
    method: 'PATCH',
    url: `/v1/boardthemes/${boardThemeId}`,
    data: {
            name:"String",  
            lightSquare:"String",  
            darkSquare:"String",  
            isPublished:"Boolean",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "boardTheme",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"boardTheme": {
		"id": "ID",
		"name": "String",
		"lightSquare": "String",
		"darkSquare": "String",
		"isPublished": "Boolean",
		"createdById": "ID",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Delete Boardtheme API

[Default delete API] — This is the designated default delete API for the boardTheme data object. Frontend generators and AI agents should use this API for standard CRUD operations. Delete a custom board theme (soft-delete). Only creator can delete.

API Frontend Description By The Backend Architect

Used to remove user’s custom theme.

Rest Route

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

/v1/boardthemes/:boardThemeId

Rest Request Parameters

The deleteBoardTheme api has got 1 regular request parameter

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

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

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "boardTheme",
	"method": "DELETE",
	"action": "delete",
	"appVersion": "Version",
	"rowCount": 1,
	"boardTheme": {
		"id": "ID",
		"name": "String",
		"lightSquare": "String",
		"darkSquare": "String",
		"isPublished": "Boolean",
		"createdById": "ID",
		"isActive": false,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Create Userpreference API

[Default create API] — This is the designated default create API for the userPreference data object. Frontend generators and AI agents should use this API for standard CRUD operations. Create user preferences record. One per user, auto-sets userId from session.

API Frontend Description By The Backend Architect

Called once when user first changes a preference. userId is auto-set.

Rest Route

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

/v1/userpreferences

Rest Request Parameters

The createUserPreference api has got 6 regular request parameters

Parameter Type Required Population
userId ID true request.body?.[“userId”]
activeThemeId String false request.body?.[“activeThemeId”]
soundEnabled Boolean false request.body?.[“soundEnabled”]
showAnimations Boolean false request.body?.[“showAnimations”]
boardOrientation Enum false request.body?.[“boardOrientation”]
premoveEnabled Boolean false request.body?.[“premoveEnabled”]
userId : The user this preferences record belongs to
activeThemeId : ID of the currently selected board theme (preset ID or custom theme ID)
soundEnabled : Whether game sounds are enabled
showAnimations : Whether board animations are shown
boardOrientation : Default board orientation preference
premoveEnabled : Whether premove feature is enabled

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

  axios({
    method: 'POST',
    url: '/v1/userpreferences',
    data: {
            userId:"ID",  
            activeThemeId:"String",  
            soundEnabled:"Boolean",  
            showAnimations:"Boolean",  
            boardOrientation:"Enum",  
            premoveEnabled:"Boolean",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "userPreference",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"userPreference": {
		"id": "ID",
		"userId": "ID",
		"activeThemeId": "String",
		"soundEnabled": "Boolean",
		"showAnimations": "Boolean",
		"boardOrientation": "Enum",
		"boardOrientation_idx": "Integer",
		"premoveEnabled": "Boolean",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Update Userpreference API

[Default update API] — This is the designated default update API for the userPreference data object. Frontend generators and AI agents should use this API for standard CRUD operations. Update user preferences. Only the owner can update their own preferences.

API Frontend Description By The Backend Architect

Called when user changes theme, sound, animation, or other settings.

Rest Route

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

/v1/userpreferences/:userPreferenceId

Rest Request Parameters

The updateUserPreference api has got 6 regular request parameters

Parameter Type Required Population
userPreferenceId ID true request.params?.[“userPreferenceId”]
activeThemeId String false request.body?.[“activeThemeId”]
soundEnabled Boolean false request.body?.[“soundEnabled”]
showAnimations Boolean false request.body?.[“showAnimations”]
boardOrientation Enum false request.body?.[“boardOrientation”]
premoveEnabled Boolean false request.body?.[“premoveEnabled”]
userPreferenceId : This id paremeter is used to select the required data object that will be updated
activeThemeId : ID of the currently selected board theme (preset ID or custom theme ID)
soundEnabled : Whether game sounds are enabled
showAnimations : Whether board animations are shown
boardOrientation : Default board orientation preference
premoveEnabled : Whether premove feature is enabled

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

  axios({
    method: 'PATCH',
    url: `/v1/userpreferences/${userPreferenceId}`,
    data: {
            activeThemeId:"String",  
            soundEnabled:"Boolean",  
            showAnimations:"Boolean",  
            boardOrientation:"Enum",  
            premoveEnabled:"Boolean",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "userPreference",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"userPreference": {
		"id": "ID",
		"userId": "ID",
		"activeThemeId": "String",
		"soundEnabled": "Boolean",
		"showAnimations": "Boolean",
		"boardOrientation": "Enum",
		"boardOrientation_idx": "Integer",
		"premoveEnabled": "Boolean",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Get Userpreference API

[Default get API] — This is the designated default get API for the userPreference data object. Frontend generators and AI agents should use this API for standard CRUD operations. Get a user’s preferences by ID.

API Frontend Description By The Backend Architect

Called on app load to restore user’s preferences.

Rest Route

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

/v1/userpreferences/:userPreferenceId

Rest Request Parameters

The getUserPreference api has got 1 regular request parameter

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

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

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "userPreference",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"userPreference": {
		"id": "ID",
		"userId": "ID",
		"activeThemeId": "String",
		"soundEnabled": "Boolean",
		"showAnimations": "Boolean",
		"boardOrientation": "Enum",
		"boardOrientation_idx": "Integer",
		"premoveEnabled": "Boolean",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

List Userpreferences API

[Default list API] — This is the designated default list API for the userPreference data object. Frontend generators and AI agents should use this API for standard CRUD operations. List user preferences. Filter by userId to get a specific user’s preferences.

API Frontend Description By The Backend Architect

Used to find user’s preference record by userId filter.

Rest Route

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

/v1/userpreferences

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

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

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

REST Response

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

List Gamehubmessages API

[Default list API] — This is the designated default list API for the gameHubMessage data object. Frontend generators and AI agents should use this API for standard CRUD operations. List messages in a gameHub hub room. Accessible by admins and room participants.

Rest Route

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

/v1/v1/gameHub-messages

Rest Request Parameters

Filter Parameters

The listGameHubMessages api supports 8 optional filter parameters for filtering list results:

roomId (ID): Reference to the room this message belongs to

senderId (ID): Reference to the user who sent this message

senderName (String): Display name of the sender (denormalized from user profile at send time)

senderAvatar (String): Avatar URL of the sender (denormalized from user profile at send time)

messageType (Enum): Content type discriminator for this message

content (Object): Type-specific content payload (structure depends on messageType)

timestamp (String): Message creation time

status (Enum): Message moderation status

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

  axios({
    method: 'GET',
    url: '/v1/v1/gameHub-messages',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section above)
        // roomId: '<value>' // Filter by roomId
        // senderId: '<value>' // Filter by senderId
        // senderName: '<value>' // Filter by senderName
        // senderAvatar: '<value>' // Filter by senderAvatar
        // messageType: '<value>' // Filter by messageType
        // content: '<value>' // Filter by content
        // timestamp: '<value>' // Filter by timestamp
        // status: '<value>' // Filter by status
            }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "gameHubMessages",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"gameHubMessages": [
		{
			"id": "ID",
			"roomId": "ID",
			"senderId": "ID",
			"senderName": "String",
			"senderAvatar": "String",
			"messageType": "Enum",
			"messageType_idx": "Integer",
			"content": "Object",
			"timestamp": null,
			"status": "Enum",
			"status_idx": "Integer",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID"
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Get Gamehubmessage API

[Default get API] — This is the designated default get API for the gameHubMessage data object. Frontend generators and AI agents should use this API for standard CRUD operations. Get a single gameHub hub message by ID.

Rest Route

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

/v1/v1/gameHub-messages/:id

Rest Request Parameters

The getGameHubMessage api has got 2 regular request parameters

Parameter Type Required Population
gameHubMessageId ID true request.params?.[“gameHubMessageId”]
id String true request.params?.[“id”]
gameHubMessageId : 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/v1/gameHub-messages/:id

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

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "gameHubMessage",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"gameHubMessage": {
		"id": "ID",
		"roomId": "ID",
		"senderId": "ID",
		"senderName": "String",
		"senderAvatar": "String",
		"messageType": "Enum",
		"messageType_idx": "Integer",
		"content": "Object",
		"timestamp": null,
		"status": "Enum",
		"status_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Delete Gamehubmessage API

[Default delete API] — This is the designated default delete API for the gameHubMessage data object. Frontend generators and AI agents should use this API for standard CRUD operations. Delete a gameHub hub message. Admins can delete any message; users can delete their own.

Rest Route

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

/v1/v1/gameHub-messages/:id

Rest Request Parameters

The deleteGameHubMessage api has got 2 regular request parameters

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

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

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

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "gameHubMessage",
	"method": "DELETE",
	"action": "delete",
	"appVersion": "Version",
	"rowCount": 1,
	"gameHubMessage": {
		"id": "ID",
		"roomId": "ID",
		"senderId": "ID",
		"senderName": "String",
		"senderAvatar": "String",
		"messageType": "Enum",
		"messageType_idx": "Integer",
		"content": "Object",
		"timestamp": null,
		"status": "Enum",
		"status_idx": "Integer",
		"isActive": false,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Update Gamehubmessage API

[Default update API] — This is the designated default update API for the gameHubMessage data object. Frontend generators and AI agents should use this API for standard CRUD operations. Update a gameHub hub message content. Only the message sender or admins can edit.

Rest Route

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

/v1/v1/gameHub-messages/:id

Rest Request Parameters

The updateGameHubMessage api has got 4 regular request parameters

Parameter Type Required Population
gameHubMessageId ID true request.params?.[“gameHubMessageId”]
content Object false request.body?.[“content”]
status Enum false request.body?.[“status”]
id String true request.params?.[“id”]
gameHubMessageId : This id paremeter is used to select the required data object that will be updated
content : Type-specific content payload (structure depends on messageType)
status : Message moderation status
id : This parameter will be used to select the data object that want to be updated

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

  axios({
    method: 'PATCH',
    url: `/v1/v1/gameHub-messages/${id}`,
    data: {
            content:"Object",  
            status:"Enum",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "gameHubMessage",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"gameHubMessage": {
		"id": "ID",
		"roomId": "ID",
		"senderId": "ID",
		"senderName": "String",
		"senderAvatar": "String",
		"messageType": "Enum",
		"messageType_idx": "Integer",
		"content": "Object",
		"timestamp": null,
		"status": "Enum",
		"status_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

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


Gameplay Service Realtime Hubs

WECHESS

FRONTEND GUIDE FOR AI CODING AGENTS - PART 8 - Gameplay Service Realtime Hubs

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

This document provides the Realtime Hub integration guide for the Gameplay service. Realtime Hubs use Socket.IO for bidirectional communication between clients and the server, enabling features like chat rooms, live collaboration, game lobbies, and dashboards.

Connection Setup

Service URLs

The Socket.IO server runs on the same host as the REST API for the gameplay service:

Authentication

Every Socket.IO connection must include the user’s access token and the correct path for the reverse proxy:

import { io } from "socket.io-client";

const socket = io("{baseUrl}/hub/{hubName}", {
  path: "/gameplay-api/socket.io/",  // HTTP transport path (reverse proxy)
  auth: { token: accessToken },           // Bearer token from login
  transports: ["websocket", "polling"],    // prefer websocket
});

Where {baseUrl} is the service base URL (e.g., https://wechess.mindbricks.co/gameplay-api).

How Socket.IO works behind a reverse proxy:

The server validates the token and resolves the user session before allowing any interaction. If the token is invalid or missing, the connection is rejected with an "Authentication required" or "Invalid token" error.

Connection Lifecycle

connect  →  authenticate  →  join rooms  →  send/receive  →  leave rooms  →  disconnect

Listen for connection events:

socket.on("connect", () => {
  console.log("Connected to hub", socket.id);
});

socket.on("connect_error", (err) => {
  console.error("Connection failed:", err.message);
  // Handle re-auth if token expired
});

socket.on("disconnect", (reason) => {
  console.log("Disconnected:", reason);
});

Protocol Reference

All hub events use the hub: prefix. Below is the complete protocol that applies to every hub in this service.

Room Management

Event Direction Payload Description
hub:join Client → Server { roomId, meta? } Join a room. meta is optional user metadata broadcast to others.
hub:joined Server → Client { roomId, hubRole, userInfo } Confirmation that the client successfully joined. userInfo contains { fullname, avatar }.
hub:leave Client → Server { roomId } Leave a room.
hub:error Server → Client { roomId?, error } Error response for any failed operation.
hub:presence Server → Room { event, roomId, user } Broadcast when a user joins or leaves. event is "joined" or "left". user includes { id, fullname, avatar, hubRole }.

Join a room:

socket.emit("hub:join", { roomId: "room-abc-123" });

socket.on("hub:joined", ({ roomId, hubRole, userInfo }) => {
  console.log("Joined room", roomId, "as", hubRole);
  // userInfo = { fullname: "John Doe", avatar: "https://..." }
});

socket.on("hub:presence", ({ event, roomId, user }) => {
  // user = { id, fullname, avatar, hubRole }
  if (event === "joined") showUserJoined(roomId, user);
  if (event === "left") showUserLeft(roomId, user);
});

socket.on("hub:error", ({ error }) => {
  console.error("Error:", error);
});

Sending Messages

Event Direction Payload
hub:send Client → Server { roomId, messageType, content, replyTo?, forwarded? }
hub:messageArrived Server → Room { roomId, sender, message }sender includes { id, fullname, avatar }

Send a message:

socket.emit("hub:send", {
  roomId: "room-abc-123",
  messageType: "text",
  content: { body: "Hello everyone!" }
});

Receive messages:

socket.on("hub:messageArrived", ({ roomId, sender, message }) => {
  // sender = { id, fullname, avatar }
  // message = { id, messageType, content, timestamp, senderName, senderAvatar, ... }
  addMessageToUI(roomId, sender, message);
});

History

When joining a room (if history is enabled), the server automatically sends the most recent messages right after the hub:joined event. Each message in the history array includes senderName and senderAvatar fields, so the frontend can render user display names and avatars without additional lookups.

Event Direction Payload
hub:history Server → Client { roomId, messages[] }

Automatic history on join:

socket.on("hub:history", ({ roomId, messages }) => {
  // messages are ordered newest-first, each has: id, roomId, senderId,
  // senderName, senderAvatar, messageType, content, timestamp, status
  renderMessageHistory(roomId, messages);
});

Paginated history via REST (for “load more” / scroll-up):

For older messages beyond the initial batch, use the REST endpoint:

GET /{hubKebabName}/{roomId}/messages?limit=50&offset=50
Authorization: Bearer {accessToken}

Response: { data: Message[], pagination: { total: number } }

Each message in the REST response also contains senderName and senderAvatar.

Custom Events

Event Direction Payload
hub:event Client → Server { roomId, event, data }
hub:{eventName} Server → Room { roomId, userId, ...data }
// Emit a custom event
socket.emit("hub:event", {
  roomId: "room-abc-123",
  event: "customAction",
  data: { key: "value" }
});

// Listen for custom events
socket.on("hub:customAction", ({ roomId, userId, ...data }) => {
  handleCustomEvent(roomId, userId, data);
});

Hub Definitions

Hub: gameHub

Namespace: /gameplay-api/hub/gameHub Description: Real-time chess game hub. Each chessGame is a room where two players exchange moves, see board state, and receive game lifecycle events (draw offer, resign, timeout, save requests). Supports both guest and registered players.

Connection

const gameHubSocket = io("{baseUrl}/gameplay-api/hub/gameHub", {
  path: "/gameplay-api/socket.io/",
  auth: { token: accessToken },
  transports: ["websocket", "polling"]
});

Room Settings

Setting Value
Room DataObject chessGame
Room Eligibility `chessGame.status == ‘active’
Absolute Roles (bypass auth) administrator

Authorization Sources (checked in order, first match wins):

# Name Source Object User Field Room Field Hub Role Condition
1 whitePlayer chessGame playerWhiteId id player
2 blackPlayer chessGame playerBlackId id player

Hub Roles

Role Read Send Allowed Types Moderated Moderate Delete Any Manage Room
player Yes Yes all No No No No

Users with absoluteRoles get a built-in system role with all permissions.

Room Eligibility Check: Before joining, you can check if a room supports real-time features:

GET /game-hub/{roomId}/eligible

Response: { "success": true, "eligible": true/false }

Use this to conditionally show/hide the chat UI.

Message Types

Messages are stored in the gameHubMessage DataObject with the following structure:

Field Type Description
id ID Primary key
roomId ID Reference to the room
senderId ID Reference to the sending user
senderName String Display name of the sender (denormalized at send time)
senderAvatar String Avatar URL of the sender (denormalized at send time)
messageType Enum One of: text, system, chessMove, drawOffer, drawAccepted, drawDeclined, resignation, saveRequest, saveAccepted, saveDeclined, resumeRequest, resumeAccepted, resumeDeclined
content JSON Type-specific payload (see below)
timestamp DateTime Message creation time

Built-in Message Types

Each message type requires specific fields in the content object:

text

Field Type Required
body Text Yes
socket.emit("hub:send", {
  roomId,
  messageType: "text",
  content: { body: "..." }
});

system

Field Type Required
systemAction String Yes
systemData JSON No
socket.emit("hub:send", {
  roomId,
  messageType: "system",
  content: { systemAction: "..." }
});

Custom Message Types

chessMove

Field Type Required
socket.emit("hub:send", {
  roomId,
  messageType: "chessMove",
  content: {  }
});

drawOffer

Field Type Required
socket.emit("hub:send", {
  roomId,
  messageType: "drawOffer",
  content: {  }
});

drawAccepted

Field Type Required
socket.emit("hub:send", {
  roomId,
  messageType: "drawAccepted",
  content: {  }
});

drawDeclined

Field Type Required
socket.emit("hub:send", {
  roomId,
  messageType: "drawDeclined",
  content: {  }
});

resignation

Field Type Required
socket.emit("hub:send", {
  roomId,
  messageType: "resignation",
  content: {  }
});

saveRequest

Field Type Required
socket.emit("hub:send", {
  roomId,
  messageType: "saveRequest",
  content: {  }
});

saveAccepted

Field Type Required
socket.emit("hub:send", {
  roomId,
  messageType: "saveAccepted",
  content: {  }
});

saveDeclined

Field Type Required
socket.emit("hub:send", {
  roomId,
  messageType: "saveDeclined",
  content: {  }
});

resumeRequest

Field Type Required
socket.emit("hub:send", {
  roomId,
  messageType: "resumeRequest",
  content: {  }
});

resumeAccepted

Field Type Required
socket.emit("hub:send", {
  roomId,
  messageType: "resumeAccepted",
  content: {  }
});

resumeDeclined

Field Type Required
socket.emit("hub:send", {
  roomId,
  messageType: "resumeDeclined",
  content: {  }
});

Cross-cutting Features

No cross-cutting features (reply, forward, reaction) are enabled for this hub.

Standard Events

Event Client Emits Server Broadcasts
Presence Online (automatic on connect) hub:online { roomId, userId }
Presence Offline (automatic on disconnect) hub:offline { roomId, userId }

Example — Typing indicator:

// Start typing
socket.emit("hub:event", { roomId, event: "typing" });

// Stop typing (call after a debounce timeout)
socket.emit("hub:event", { roomId, event: "stopTyping" });

// Listen for others typing
socket.on("hub:typing", ({ roomId, userId }) => {
  showTypingIndicator(roomId, userId);
});
socket.on("hub:stopTyping", ({ roomId, userId }) => {
  hideTypingIndicator(roomId, userId);
});

Custom Events

gameStateUpdate — Broadcast updated game state (status, result, timers) to both players when the game state changes server-side. Direction: serverToRoom

// Emit
socket.emit("hub:event", {
  roomId,
  event: "gameStateUpdate",
  data: { /* your payload */ }
});

// Listen
socket.on("hub:gameStateUpdate", ({ roomId, userId, ...data }) => {
  // handle event
});

clockTick — Server broadcasts remaining time for each player (for timed/blitz/rapid games). Direction: serverToRoom

// Emit
socket.emit("hub:event", {
  roomId,
  event: "clockTick",
  data: { /* your payload */ }
});

// Listen
socket.on("hub:clockTick", ({ roomId, userId, ...data }) => {
  // handle event
});

Auto-Bridged Server Events

These events are automatically emitted to rooms when DataObject changes occur on the backend (via Kafka). The frontend only needs to listen:

Event Trigger Payload
hub:messageEdited gameHubMessage updated DataObject record fields
hub:messageDeleted gameHubMessage deleted DataObject record fields
hub:roomUpdated chessGame updated DataObject record fields
hub:roomClosed chessGame deleted DataObject record fields
socket.on("hub:messageEdited", ({ roomId, ...data }) => {
  handleMessageEdited(roomId, data);
});
socket.on("hub:messageDeleted", ({ roomId, ...data }) => {
  handleMessageDeleted(roomId, data);
});
socket.on("hub:roomUpdated", ({ roomId, ...data }) => {
  handleRoomUpdated(roomId, data);
});
socket.on("hub:roomClosed", ({ roomId, ...data }) => {
  handleRoomClosed(roomId, data);
});

Moderation Commands

Users with canModerate permission can block, silence, and manage messages:

Block/Unblock a user:

socket.emit("hub:block", { roomId, userId: targetUserId, reason: "Spam", duration: 3600 });
socket.emit("hub:unblock", { roomId, userId: targetUserId });

Silence/Unsilence a user:

socket.emit("hub:silence", { roomId, userId: targetUserId, reason: "Off-topic", duration: 600 });
socket.emit("hub:unsilence", { roomId, userId: targetUserId });

Duration is in seconds. 0 or omitted = permanent.

Listen for moderation actions on your user:

socket.on("hub:blocked", ({ roomId, reason }) => {
  // You have been blocked — leave UI, show message
});
socket.on("hub:unblocked", ({ roomId }) => {
  // Block lifted — you may rejoin the room
});
socket.on("hub:silenced", ({ roomId, reason }) => {
  // You have been silenced — disable send button
});
socket.on("hub:unsilenced", ({ roomId }) => {
  // Silence lifted — re-enable send button
});

REST API Endpoints

In addition to Socket.IO, the hub exposes REST endpoints for message history and management:

Get message history:

GET /game-hub/{roomId}/messages?limit=50&offset=0

Response:

{
  "success": true,
  "data": [ /* message objects */ ],
  "pagination": { "limit": 50, "offset": 0, "total": 120 }
}

Send a message via REST:

POST /game-hub/{roomId}/messages
Content-Type: application/json
Authorization: Bearer {accessToken}

{
  "data": { "body": "Hello from REST" },
  "replyTo": null
}

Messages sent via REST are also broadcast to all connected Socket.IO clients in the room.

Delete a message:

DELETE /game-hub/{roomId}/messages/{messageId}
Authorization: Bearer {accessToken}

Guardrails

Limit Value
Max users per room 3
Max rooms per user 5
Message rate limit 120 msg/min
Max message size 16384 bytes
Connection timeout 600000 ms
History on join Last 100 messages

Frontend Integration Checklist

  1. Install socket.io-client: npm install socket.io-client
  2. Create a connection manager that handles connect/disconnect/reconnect with token refresh.
  3. Join rooms after connection. Listen for hub:joined before sending messages. The hub:joined event includes the user’s hubRole and userInfo (fullname, avatar).
  4. Render chat history from the hub:history event that arrives automatically after joining. Each message includes senderName and senderAvatar for display.
  5. Handle hub:error globally for all error responses.
  6. Use sender info from hub:messageArrived events — the sender object includes { id, fullname, avatar }. For history messages, use the stored senderName and senderAvatar fields.
  7. Parse messageType to render different message bubbles (text, image, video, etc.).
  8. Use REST endpoints for paginated history when scrolling up in a conversation (GET /{hubKebabName}/{roomId}/messages?limit=50&offset=50).
  9. Debounce typing indicators — emit typing on keypress, stopTyping after 2–3 seconds of inactivity.
  10. Track read receipts per room to show unread counts and read status.
  11. Handle presence to show online/offline status. The hub:presence event includes user.fullname and user.avatar for display.
  12. Reconnect gracefully — re-join rooms and fetch missed messages via REST on reconnect.

Example: Full Chat Integration

import { io } from "socket.io-client";

class ChatHub {
  constructor(baseUrl, token) {
    this.socket = io(`${baseUrl}/gameplay-api/hub/gameHub`, {
      path: "/gameplay-api/socket.io/",
      auth: { token },
      transports: ["websocket", "polling"]
    });

    this.rooms = new Map();
    this._setupListeners();
  }

  _setupListeners() {
    this.socket.on("hub:joined", ({ roomId, hubRole, userInfo }) => {
      this.rooms.set(roomId, { joined: true, hubRole, userInfo, messages: [], members: new Map() });
    });

    this.socket.on("hub:history", ({ roomId, messages }) => {
      const room = this.rooms.get(roomId);
      if (room) room.messages = messages;
      // Each message has senderName and senderAvatar for display
    });

    this.socket.on("hub:presence", ({ event, roomId, user }) => {
      const room = this.rooms.get(roomId);
      if (!room) return;
      if (event === "joined") {
        room.members.set(user.id, { fullname: user.fullname, avatar: user.avatar, hubRole: user.hubRole });
      } else if (event === "left") {
        room.members.delete(user.id);
      }
    });

    this.socket.on("hub:messageArrived", ({ roomId, sender, message }) => {
      // sender = { id, fullname, avatar }
      const room = this.rooms.get(roomId);
      if (room) room.messages.push(message);
      this.onNewMessage?.(roomId, sender, message);
    });

    this.socket.on("hub:error", ({ error }) => {
      console.error("[ChatHub]", error);
    });

    this.socket.on("hub:online", ({ roomId, userId }) => {
      this.onPresence?.(userId, "online");
    });
    this.socket.on("hub:offline", ({ roomId, userId }) => {
      this.onPresence?.(userId, "offline");
    });
  }

  joinRoom(roomId) {
    this.socket.emit("hub:join", { roomId });
  }

  leaveRoom(roomId) {
    this.socket.emit("hub:leave", { roomId });
    this.rooms.delete(roomId);
  }

  sendMessage(roomId, messageType, content, options = {}) {
    this.socket.emit("hub:send", {
      roomId,
      messageType,
      content,
      ...options
    });
  }

  disconnect() {
    this.socket.disconnect();
  }
}

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


LobbyChat Service

WECHESS

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

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

Service Access

LobbyChat service management is handled through service specific base urls.

LobbyChat 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 lobbyChat service, the base URLs are:

Scope

LobbyChat Service Description

Public lobby chat microservice. Manages create, list, reporting, moderation, and 24-hour message expiry for guest/registered users.

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

lobbyMessage Data Object: A single lobby/public chat message between any logged-in user (guest, registered, admin). Ephemeral (24h retention), with reporting and moderation support. Muting is tracked by senderId+mutedUntil for punishment management.

lobbyRoom Data Object: Daily lobby chat room. One record per day (roomId format: lobby-YYYY-MM-DD). Older rooms kept as history.

lobbyChatHubMessage Data Object: Auto-generated message DataObject for the lobbyChatHub RealtimeHub. Stores all messages with typed content payloads.

lobbyChatHubModeration Data Object: Auto-generated moderation DataObject for the lobbyChatHub RealtimeHub. Stores block and silence actions for room-level user moderation.

LobbyChat Service Frontend Description By The Backend Architect

Lobby Chat Service (lobbyChat)

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

LobbyMessage Data Object

A single lobby/public chat message between any logged-in user (guest, registered, admin). Ephemeral (24h retention), with reporting and moderation support. Muting is tracked by senderId+mutedUntil for punishment management.

LobbyMessage Data Object Frontend Description By The Backend Architect

LobbyMessage Data Object Properties

LobbyMessage 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
senderId ID false Yes No User ID (guest or registered) who sent the message. References auth:user.id.
senderDisplayName String false Yes No Display name (from user fullname at send time; allows historical display even if name changes).
content String false Yes No Chat message body (limited at UI, backend-enforces not empty; max 500 chars).
sentAt Date false Yes No UTC timestamp when message was sent. Used to enforce 24h retention and sorting.
reportStatus Enum false Yes No Moderation/report workflow state: none (default), reported (user), underReview (admin).
mutedUntil Date false No No If set, the message sender is muted in the lobby until this timestamp. Only admins may set. Used with senderId for lookup on enforcement.
removed Boolean false Yes No If true, message is hidden/removed by admin moderation (soft-remove).
roomId String false Yes No Daily room identifier (lobby-YYYY-MM-DD). Scopes message to that day.

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

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

Filter Properties

senderId reportStatus removed

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.

LobbyRoom Data Object

Daily lobby chat room. One record per day (roomId format: lobby-YYYY-MM-DD). Older rooms kept as history.

LobbyRoom Data Object Properties

LobbyRoom 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
roomId String false Yes No Room identifier, e.g. lobby-2026-03-10

LobbyChatHubMessage Data Object

Auto-generated message DataObject for the lobbyChatHub RealtimeHub. Stores all messages with typed content payloads.

LobbyChatHubMessage Data Object Properties

LobbyChatHubMessage 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
roomId ID false Yes No Reference to the room this message belongs to
senderId ID false No No Reference to the user who sent this message
senderName String false No No Display name of the sender (denormalized from user profile at send time)
senderAvatar String false No No Avatar URL of the sender (denormalized from user profile at send time)
messageType Enum false Yes No Content type discriminator for this message
content Object false Yes No Type-specific content payload (structure depends on messageType)
timestamp false No No Message creation time
status Enum false No No Message moderation status
reaction Object false No No Emoji reactions [{ emoji, userId, timestamp }]

Enum Properties

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

Filter Properties

roomId senderId senderName senderAvatar messageType content timestamp status reaction

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.

LobbyChatHubModeration Data Object

Auto-generated moderation DataObject for the lobbyChatHub RealtimeHub. Stores block and silence actions for room-level user moderation.

LobbyChatHubModeration Data Object Properties

LobbyChatHubModeration 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
roomId ID false Yes No Reference to the room where the moderation action applies
userId ID false Yes No The user who is blocked or silenced
action Enum false Yes No Moderation action type
reason Text false No No Optional reason for the moderation action
duration Integer false No No Duration in seconds. 0 means permanent
expiresAt false No No Expiry timestamp. Null means permanent
issuedBy ID false No No The moderator who issued the action

Enum Properties

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

Relation Properties

roomId

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

roomId userId action reason duration expiresAt issuedBy

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.

LobbyMessage Default APIs

Operation API Name Route Explicitly Set
Create createLobbyMessage /v1/lobbymessages Yes
Update updateLobbyMessageModeration /v1/lobbymessagemoderation/:lobbyMessageId Yes
Delete deleteLobbyMessage /v1/lobbymessages/:lobbyMessageId Yes
Get none - Auto
List listLobbyMessages /v1/listlobbymessages/:roomId Yes

LobbyRoom Default APIs

Operation API Name Route Explicitly Set
Create ensureLobbyRoom /v1/ensurelobbyroom Auto
Update none - Auto
Delete none - Auto
Get none - Auto
List listLobbyRooms /v1/listlobbyrooms/:roomId Auto

LobbyChatHubMessage Default APIs

Operation API Name Route Explicitly Set
Create none - Auto
Update updateLobbyChatHubMessage /v1/v1/lobbyChatHub-messages/:id Yes
Delete deleteLobbyChatHubMessage /v1/v1/lobbyChatHub-messages/:id Yes
Get getLobbyChatHubMessage /v1/v1/lobbyChatHub-messages/:id Yes
List listLobbyChatHubMessages /v1/v1/lobbyChatHub-messages Yes

LobbyChatHubModeration Default APIs

Operation API Name Route Explicitly Set
Create none - Auto
Update none - Auto
Delete none - Auto
Get none - Auto
List none - Auto

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

[Default create API] — This is the designated default create API for the lobbyMessage data object. Frontend generators and AI agents should use this API for standard CRUD operations. Post a new lobby chat message. Enforces mute (mutedUntil > now), ensures message is not empty and under 500 chars. SenderId and senderDisplayName are populated from session.

API Frontend Description By The Backend Architect

Rest Route

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

/v1/lobbymessages

Rest Request Parameters

The createLobbyMessage api has got 8 regular request parameters

Parameter Type Required Population
senderId ID true request.body?.[“senderId”]
senderDisplayName String true request.body?.[“senderDisplayName”]
content String true request.body?.[“content”]
sentAt Date true request.body?.[“sentAt”]
reportStatus Enum true request.body?.[“reportStatus”]
mutedUntil Date false request.body?.[“mutedUntil”]
removed Boolean true request.body?.[“removed”]
roomId String true request.body?.[“roomId”]
senderId : User ID (guest or registered) who sent the message. References auth:user.id.
senderDisplayName : Display name (from user fullname at send time; allows historical display even if name changes).
content : Chat message body (limited at UI, backend-enforces not empty; max 500 chars).
sentAt : UTC timestamp when message was sent. Used to enforce 24h retention and sorting.
reportStatus : Moderation/report workflow state: none (default), reported (user), underReview (admin).
mutedUntil : If set, the message sender is muted in the lobby until this timestamp. Only admins may set. Used with senderId for lookup on enforcement.
removed : If true, message is hidden/removed by admin moderation (soft-remove).
roomId : Daily room identifier (lobby-YYYY-MM-DD). Scopes message to that day.

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

  axios({
    method: 'POST',
    url: '/v1/lobbymessages',
    data: {
            senderId:"ID",  
            senderDisplayName:"String",  
            content:"String",  
            sentAt:"Date",  
            reportStatus:"Enum",  
            mutedUntil:"Date",  
            removed:"Boolean",  
            roomId:"String",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "lobbyMessage",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"lobbyMessage": {
		"id": "ID",
		"senderId": "ID",
		"senderDisplayName": "String",
		"content": "String",
		"sentAt": "Date",
		"reportStatus": "Enum",
		"reportStatus_idx": "Integer",
		"mutedUntil": "Date",
		"removed": "Boolean",
		"roomId": "String",
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"isActive": true
	}
}

List Lobbymessages API

[Default list API] — This is the designated default list API for the lobbyMessage data object. Frontend generators and AI agents should use this API for standard CRUD operations. Fetch latest lobby chat messages from the last 24 hours (not removed). Sorted sentAt desc. Paginated by default (50 per page).

API Frontend Description By The Backend Architect

Rest Route

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

/v1/listlobbymessages/:roomId

Rest Request Parameters

The listLobbyMessages api has got 1 regular request parameter

Parameter Type Required Population
roomId String true request.params?.[“roomId”]
roomId : Daily room identifier (lobby-YYYY-MM-DD). Scopes message to that day… The parameter is used to query data.

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

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

Update Lobbymessagemoderation API

[Default update API] — This is the designated default update API for the lobbyMessage data object. Frontend generators and AI agents should use this API for standard CRUD operations. Update message for moderation: only admins may set removed (true), mutedUntil, or set reportStatus to underReview. All users may set reportStatus to reported on a message they wish to report. Message owner may not update content or displayName.

API Frontend Description By The Backend Architect

Rest Route

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

/v1/lobbymessagemoderation/:lobbyMessageId

Rest Request Parameters

The updateLobbyMessageModeration api has got 5 regular request parameters

Parameter Type Required Population
lobbyMessageId ID true request.params?.[“lobbyMessageId”]
reportStatus Enum false request.body?.[“reportStatus”]
mutedUntil Date false request.body?.[“mutedUntil”]
removed Boolean false request.body?.[“removed”]
roomId String false request.body?.[“roomId”]
lobbyMessageId : This id paremeter is used to select the required data object that will be updated
reportStatus : Moderation/report workflow state: none (default), reported (user), underReview (admin).
mutedUntil : If set, the message sender is muted in the lobby until this timestamp. Only admins may set. Used with senderId for lookup on enforcement.
removed : If true, message is hidden/removed by admin moderation (soft-remove).
roomId : Daily room identifier (lobby-YYYY-MM-DD). Scopes message to that day.

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

  axios({
    method: 'PATCH',
    url: `/v1/lobbymessagemoderation/${lobbyMessageId}`,
    data: {
            reportStatus:"Enum",  
            mutedUntil:"Date",  
            removed:"Boolean",  
            roomId:"String",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "lobbyMessage",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"lobbyMessage": {
		"id": "ID",
		"senderId": "ID",
		"senderDisplayName": "String",
		"content": "String",
		"sentAt": "Date",
		"reportStatus": "Enum",
		"reportStatus_idx": "Integer",
		"mutedUntil": "Date",
		"removed": "Boolean",
		"roomId": "String",
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"isActive": true
	}
}

Delete Lobbymessage API

[Default delete API] — This is the designated default delete API for the lobbyMessage data object. Frontend generators and AI agents should use this API for standard CRUD operations. Physical delete of a lobby message (should only be possible for admin batch/cleanup or hard moderation). In practice, most moderation is via removed:true.

API Frontend Description By The Backend Architect

Rest Route

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

/v1/lobbymessages/:lobbyMessageId

Rest Request Parameters

The deleteLobbyMessage api has got 1 regular request parameter

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

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

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "lobbyMessage",
	"method": "DELETE",
	"action": "delete",
	"appVersion": "Version",
	"rowCount": 1,
	"lobbyMessage": {
		"id": "ID",
		"senderId": "ID",
		"senderDisplayName": "String",
		"content": "String",
		"sentAt": "Date",
		"reportStatus": "Enum",
		"reportStatus_idx": "Integer",
		"mutedUntil": "Date",
		"removed": "Boolean",
		"roomId": "String",
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"isActive": false
	}
}

Ensure Lobbyroom API

Rest Route

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

/v1/ensurelobbyroom

Rest Request Parameters

The ensureLobbyRoom api has got 1 regular request parameter

Parameter Type Required Population
roomId String true request.body?.[“roomId”]
roomId : Room identifier, e.g. lobby-2026-03-10

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

  axios({
    method: 'POST',
    url: '/v1/ensurelobbyroom',
    data: {
            roomId:"String",  
    
    },
    params: {
    
        }
  });

REST Response

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

List Lobbyrooms API

Rest Route

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

/v1/listlobbyrooms/:roomId

Rest Request Parameters

The listLobbyRooms api has got 1 regular request parameter

Parameter Type Required Population
roomId String true request.params?.[“roomId”]
roomId : Room identifier, e.g. lobby-2026-03-10. The parameter is used to query data.

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

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

REST Response

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

List Lobbychathubmessages API

[Default list API] — This is the designated default list API for the lobbyChatHubMessage data object. Frontend generators and AI agents should use this API for standard CRUD operations. List messages in a lobbyChatHub hub room. Accessible by admins and room participants.

Rest Route

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

/v1/v1/lobbyChatHub-messages

Rest Request Parameters

Filter Parameters

The listLobbyChatHubMessages api supports 9 optional filter parameters for filtering list results:

roomId (ID): Reference to the room this message belongs to

senderId (ID): Reference to the user who sent this message

senderName (String): Display name of the sender (denormalized from user profile at send time)

senderAvatar (String): Avatar URL of the sender (denormalized from user profile at send time)

messageType (Enum): Content type discriminator for this message

content (Object): Type-specific content payload (structure depends on messageType)

timestamp (String): Message creation time

status (Enum): Message moderation status

reaction (Object): Emoji reactions [{ emoji, userId, timestamp }]

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

  axios({
    method: 'GET',
    url: '/v1/v1/lobbyChatHub-messages',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section above)
        // roomId: '<value>' // Filter by roomId
        // senderId: '<value>' // Filter by senderId
        // senderName: '<value>' // Filter by senderName
        // senderAvatar: '<value>' // Filter by senderAvatar
        // messageType: '<value>' // Filter by messageType
        // content: '<value>' // Filter by content
        // timestamp: '<value>' // Filter by timestamp
        // status: '<value>' // Filter by status
        // reaction: '<value>' // Filter by reaction
            }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "lobbyChatHubMessages",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"lobbyChatHubMessages": [
		{
			"id": "ID",
			"roomId": "ID",
			"senderId": "ID",
			"senderName": "String",
			"senderAvatar": "String",
			"messageType": "Enum",
			"messageType_idx": "Integer",
			"content": "Object",
			"timestamp": null,
			"status": "Enum",
			"status_idx": "Integer",
			"reaction": "Object",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID"
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Get Lobbychathubmessage API

[Default get API] — This is the designated default get API for the lobbyChatHubMessage data object. Frontend generators and AI agents should use this API for standard CRUD operations. Get a single lobbyChatHub hub message by ID.

Rest Route

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

/v1/v1/lobbyChatHub-messages/:id

Rest Request Parameters

The getLobbyChatHubMessage api has got 2 regular request parameters

Parameter Type Required Population
lobbyChatHubMessageId ID true request.params?.[“lobbyChatHubMessageId”]
id String true request.params?.[“id”]
lobbyChatHubMessageId : 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/v1/lobbyChatHub-messages/:id

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

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "lobbyChatHubMessage",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"lobbyChatHubMessage": {
		"id": "ID",
		"roomId": "ID",
		"senderId": "ID",
		"senderName": "String",
		"senderAvatar": "String",
		"messageType": "Enum",
		"messageType_idx": "Integer",
		"content": "Object",
		"timestamp": null,
		"status": "Enum",
		"status_idx": "Integer",
		"reaction": "Object",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Delete Lobbychathubmessage API

[Default delete API] — This is the designated default delete API for the lobbyChatHubMessage data object. Frontend generators and AI agents should use this API for standard CRUD operations. Delete a lobbyChatHub hub message. Admins can delete any message; users can delete their own.

Rest Route

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

/v1/v1/lobbyChatHub-messages/:id

Rest Request Parameters

The deleteLobbyChatHubMessage api has got 2 regular request parameters

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

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

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

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "lobbyChatHubMessage",
	"method": "DELETE",
	"action": "delete",
	"appVersion": "Version",
	"rowCount": 1,
	"lobbyChatHubMessage": {
		"id": "ID",
		"roomId": "ID",
		"senderId": "ID",
		"senderName": "String",
		"senderAvatar": "String",
		"messageType": "Enum",
		"messageType_idx": "Integer",
		"content": "Object",
		"timestamp": null,
		"status": "Enum",
		"status_idx": "Integer",
		"reaction": "Object",
		"isActive": false,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Update Lobbychathubmessage API

[Default update API] — This is the designated default update API for the lobbyChatHubMessage data object. Frontend generators and AI agents should use this API for standard CRUD operations. Update a lobbyChatHub hub message content. Only the message sender or admins can edit.

Rest Route

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

/v1/v1/lobbyChatHub-messages/:id

Rest Request Parameters

The updateLobbyChatHubMessage api has got 5 regular request parameters

Parameter Type Required Population
lobbyChatHubMessageId ID true request.params?.[“lobbyChatHubMessageId”]
content Object false request.body?.[“content”]
status Enum false request.body?.[“status”]
reaction Object false request.body?.[“reaction”]
id String true request.params?.[“id”]
lobbyChatHubMessageId : This id paremeter is used to select the required data object that will be updated
content : Type-specific content payload (structure depends on messageType)
status : Message moderation status
reaction : Emoji reactions [{ emoji, userId, timestamp }]
id : This parameter will be used to select the data object that want to be updated

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

  axios({
    method: 'PATCH',
    url: `/v1/v1/lobbyChatHub-messages/${id}`,
    data: {
            content:"Object",  
            status:"Enum",  
            reaction:"Object",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "lobbyChatHubMessage",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"lobbyChatHubMessage": {
		"id": "ID",
		"roomId": "ID",
		"senderId": "ID",
		"senderName": "String",
		"senderAvatar": "String",
		"messageType": "Enum",
		"messageType_idx": "Integer",
		"content": "Object",
		"timestamp": null,
		"status": "Enum",
		"status_idx": "Integer",
		"reaction": "Object",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

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


LobbyChat Service Realtime Hubs

WECHESS

FRONTEND GUIDE FOR AI CODING AGENTS - PART 10 - LobbyChat Service Realtime Hubs

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

This document provides the Realtime Hub integration guide for the LobbyChat service. Realtime Hubs use Socket.IO for bidirectional communication between clients and the server, enabling features like chat rooms, live collaboration, game lobbies, and dashboards.

Connection Setup

Service URLs

The Socket.IO server runs on the same host as the REST API for the lobbyChat service:

Authentication

Every Socket.IO connection must include the user’s access token and the correct path for the reverse proxy:

import { io } from "socket.io-client";

const socket = io("{baseUrl}/hub/{hubName}", {
  path: "/lobbychat-api/socket.io/",  // HTTP transport path (reverse proxy)
  auth: { token: accessToken },           // Bearer token from login
  transports: ["websocket", "polling"],    // prefer websocket
});

Where {baseUrl} is the service base URL (e.g., https://wechess.mindbricks.co/lobbychat-api).

How Socket.IO works behind a reverse proxy:

The server validates the token and resolves the user session before allowing any interaction. If the token is invalid or missing, the connection is rejected with an "Authentication required" or "Invalid token" error.

Connection Lifecycle

connect  →  authenticate  →  join rooms  →  send/receive  →  leave rooms  →  disconnect

Listen for connection events:

socket.on("connect", () => {
  console.log("Connected to hub", socket.id);
});

socket.on("connect_error", (err) => {
  console.error("Connection failed:", err.message);
  // Handle re-auth if token expired
});

socket.on("disconnect", (reason) => {
  console.log("Disconnected:", reason);
});

Protocol Reference

All hub events use the hub: prefix. Below is the complete protocol that applies to every hub in this service.

Room Management

Event Direction Payload Description
hub:join Client → Server { roomId, meta? } Join a room. meta is optional user metadata broadcast to others.
hub:joined Server → Client { roomId, hubRole, userInfo } Confirmation that the client successfully joined. userInfo contains { fullname, avatar }.
hub:leave Client → Server { roomId } Leave a room.
hub:error Server → Client { roomId?, error } Error response for any failed operation.
hub:presence Server → Room { event, roomId, user } Broadcast when a user joins or leaves. event is "joined" or "left". user includes { id, fullname, avatar, hubRole }.

Join a room:

socket.emit("hub:join", { roomId: "room-abc-123" });

socket.on("hub:joined", ({ roomId, hubRole, userInfo }) => {
  console.log("Joined room", roomId, "as", hubRole);
  // userInfo = { fullname: "John Doe", avatar: "https://..." }
});

socket.on("hub:presence", ({ event, roomId, user }) => {
  // user = { id, fullname, avatar, hubRole }
  if (event === "joined") showUserJoined(roomId, user);
  if (event === "left") showUserLeft(roomId, user);
});

socket.on("hub:error", ({ error }) => {
  console.error("Error:", error);
});

Sending Messages

Event Direction Payload
hub:send Client → Server { roomId, messageType, content, replyTo?, forwarded? }
hub:messageArrived Server → Room { roomId, sender, message }sender includes { id, fullname, avatar }

Send a message:

socket.emit("hub:send", {
  roomId: "room-abc-123",
  messageType: "text",
  content: { body: "Hello everyone!" }
});

Receive messages:

socket.on("hub:messageArrived", ({ roomId, sender, message }) => {
  // sender = { id, fullname, avatar }
  // message = { id, messageType, content, timestamp, senderName, senderAvatar, ... }
  addMessageToUI(roomId, sender, message);
});

History

When joining a room (if history is enabled), the server automatically sends the most recent messages right after the hub:joined event. Each message in the history array includes senderName and senderAvatar fields, so the frontend can render user display names and avatars without additional lookups.

Event Direction Payload
hub:history Server → Client { roomId, messages[] }

Automatic history on join:

socket.on("hub:history", ({ roomId, messages }) => {
  // messages are ordered newest-first, each has: id, roomId, senderId,
  // senderName, senderAvatar, messageType, content, timestamp, status
  renderMessageHistory(roomId, messages);
});

Paginated history via REST (for “load more” / scroll-up):

For older messages beyond the initial batch, use the REST endpoint:

GET /{hubKebabName}/{roomId}/messages?limit=50&offset=50
Authorization: Bearer {accessToken}

Response: { data: Message[], pagination: { total: number } }

Each message in the REST response also contains senderName and senderAvatar.

Custom Events

Event Direction Payload
hub:event Client → Server { roomId, event, data }
hub:{eventName} Server → Room { roomId, userId, ...data }
// Emit a custom event
socket.emit("hub:event", {
  roomId: "room-abc-123",
  event: "customAction",
  data: { key: "value" }
});

// Listen for custom events
socket.on("hub:customAction", ({ roomId, userId, ...data }) => {
  handleCustomEvent(roomId, userId, data);
});

Hub Definitions

Hub: lobbyChatHub

Namespace: /lobbychat-api/hub/lobbyChatHub Description: Public lobby chat hub. A single shared room where all authenticated users (guests and registered) can chat in real-time. Messages have 24-hour retention. Supports moderation: report, mute, and admin removal.

Connection

const lobbyChatHubSocket = io("{baseUrl}/lobbychat-api/hub/lobbyChatHub", {
  path: "/lobbychat-api/socket.io/",
  auth: { token: accessToken },
  transports: ["websocket", "polling"]
});

Room Settings

Setting Value
Room DataObject lobbyRoom
Absolute Roles (bypass auth) administrator

Authorization Sources (checked in order, first match wins):

# Name Source Object User Field Room Field Hub Role Condition
1 allowAllAuthenticated lobbyRoom id id lobbyUser

Hub Roles

Role Read Send Allowed Types Moderated Moderate Delete Any Manage Room
lobbyUser Yes Yes text No No No No
moderator Yes Yes all No Yes Yes No

Users with absoluteRoles get a built-in system role with all permissions.

Message Types

Messages are stored in the lobbyChatHubMessage DataObject with the following structure:

Field Type Description
id ID Primary key
roomId ID Reference to the room
senderId ID Reference to the sending user
senderName String Display name of the sender (denormalized at send time)
senderAvatar String Avatar URL of the sender (denormalized at send time)
messageType Enum One of: text, system
content JSON Type-specific payload (see below)
timestamp DateTime Message creation time
reaction JSON Emoji reactions [{ emoji, userId, timestamp }]

Built-in Message Types

Each message type requires specific fields in the content object:

text

Field Type Required
body Text Yes
socket.emit("hub:send", {
  roomId,
  messageType: "text",
  content: { body: "..." }
});

system

Field Type Required
systemAction String Yes
systemData JSON No
socket.emit("hub:send", {
  roomId,
  messageType: "system",
  content: { systemAction: "..." }
});

Cross-cutting Features

Reactions: Reactions are stored on the message object. Use the message DataObject’s update API to add/remove reactions.

Standard Events

Event Client Emits Server Broadcasts
Typing hub:event with event: "typing" hub:typing { roomId, userId }
Stop Typing hub:event with event: "stopTyping" hub:stopTyping { roomId, userId }
Presence Online (automatic on connect) hub:online { roomId, userId }
Presence Offline (automatic on disconnect) hub:offline { roomId, userId }

Example — Typing indicator:

// Start typing
socket.emit("hub:event", { roomId, event: "typing" });

// Stop typing (call after a debounce timeout)
socket.emit("hub:event", { roomId, event: "stopTyping" });

// Listen for others typing
socket.on("hub:typing", ({ roomId, userId }) => {
  showTypingIndicator(roomId, userId);
});
socket.on("hub:stopTyping", ({ roomId, userId }) => {
  hideTypingIndicator(roomId, userId);
});

Custom Events

userMuted — Broadcast when a user is muted in the lobby by an admin. Direction: serverToRoom

// Emit
socket.emit("hub:event", {
  roomId,
  event: "userMuted",
  data: { /* your payload */ }
});

// Listen
socket.on("hub:userMuted", ({ roomId, userId, ...data }) => {
  // handle event
});

messageModerated — Broadcast when a message is removed by admin moderation, so all users can hide it. Direction: serverToRoom

// Emit
socket.emit("hub:event", {
  roomId,
  event: "messageModerated",
  data: { /* your payload */ }
});

// Listen
socket.on("hub:messageModerated", ({ roomId, userId, ...data }) => {
  // handle event
});

Auto-Bridged Server Events

These events are automatically emitted to rooms when DataObject changes occur on the backend (via Kafka). The frontend only needs to listen:

Event Trigger Payload
hub:messageEdited lobbyChatHubMessage updated DataObject record fields
hub:messageDeleted lobbyChatHubMessage deleted DataObject record fields
hub:roomUpdated lobbyRoom updated DataObject record fields
hub:roomClosed lobbyRoom deleted DataObject record fields
socket.on("hub:messageEdited", ({ roomId, ...data }) => {
  handleMessageEdited(roomId, data);
});
socket.on("hub:messageDeleted", ({ roomId, ...data }) => {
  handleMessageDeleted(roomId, data);
});
socket.on("hub:roomUpdated", ({ roomId, ...data }) => {
  handleRoomUpdated(roomId, data);
});
socket.on("hub:roomClosed", ({ roomId, ...data }) => {
  handleRoomClosed(roomId, data);
});

Moderation Commands

Users with canModerate permission can block, silence, and manage messages:

Block/Unblock a user:

socket.emit("hub:block", { roomId, userId: targetUserId, reason: "Spam", duration: 3600 });
socket.emit("hub:unblock", { roomId, userId: targetUserId });

Silence/Unsilence a user:

socket.emit("hub:silence", { roomId, userId: targetUserId, reason: "Off-topic", duration: 600 });
socket.emit("hub:unsilence", { roomId, userId: targetUserId });

Duration is in seconds. 0 or omitted = permanent.

Listen for moderation actions on your user:

socket.on("hub:blocked", ({ roomId, reason }) => {
  // You have been blocked — leave UI, show message
});
socket.on("hub:unblocked", ({ roomId }) => {
  // Block lifted — you may rejoin the room
});
socket.on("hub:silenced", ({ roomId, reason }) => {
  // You have been silenced — disable send button
});
socket.on("hub:unsilenced", ({ roomId }) => {
  // Silence lifted — re-enable send button
});

REST API Endpoints

In addition to Socket.IO, the hub exposes REST endpoints for message history and management:

Get message history:

GET /lobby-chat-hub/{roomId}/messages?limit=50&offset=0

Response:

{
  "success": true,
  "data": [ /* message objects */ ],
  "pagination": { "limit": 50, "offset": 0, "total": 120 }
}

Send a message via REST:

POST /lobby-chat-hub/{roomId}/messages
Content-Type: application/json
Authorization: Bearer {accessToken}

{
  "data": { "body": "Hello from REST" },
  "replyTo": null
}

Messages sent via REST are also broadcast to all connected Socket.IO clients in the room.

Delete a message:

DELETE /lobby-chat-hub/{roomId}/messages/{messageId}
Authorization: Bearer {accessToken}

Guardrails

Limit Value
Max users per room 1000
Max rooms per user 3
Message rate limit 20 msg/min
Max message size 4096 bytes
Connection timeout 300000 ms
History on join Last 50 messages

Frontend Integration Checklist

  1. Install socket.io-client: npm install socket.io-client
  2. Create a connection manager that handles connect/disconnect/reconnect with token refresh.
  3. Join rooms after connection. Listen for hub:joined before sending messages. The hub:joined event includes the user’s hubRole and userInfo (fullname, avatar).
  4. Render chat history from the hub:history event that arrives automatically after joining. Each message includes senderName and senderAvatar for display.
  5. Handle hub:error globally for all error responses.
  6. Use sender info from hub:messageArrived events — the sender object includes { id, fullname, avatar }. For history messages, use the stored senderName and senderAvatar fields.
  7. Parse messageType to render different message bubbles (text, image, video, etc.).
  8. Use REST endpoints for paginated history when scrolling up in a conversation (GET /{hubKebabName}/{roomId}/messages?limit=50&offset=50).
  9. Debounce typing indicators — emit typing on keypress, stopTyping after 2–3 seconds of inactivity.
  10. Track read receipts per room to show unread counts and read status.
  11. Handle presence to show online/offline status. The hub:presence event includes user.fullname and user.avatar for display.
  12. Reconnect gracefully — re-join rooms and fetch missed messages via REST on reconnect.

Example: Full Chat Integration

import { io } from "socket.io-client";

class ChatHub {
  constructor(baseUrl, token) {
    this.socket = io(`${baseUrl}/lobbychat-api/hub/lobbyChatHub`, {
      path: "/lobbychat-api/socket.io/",
      auth: { token },
      transports: ["websocket", "polling"]
    });

    this.rooms = new Map();
    this._setupListeners();
  }

  _setupListeners() {
    this.socket.on("hub:joined", ({ roomId, hubRole, userInfo }) => {
      this.rooms.set(roomId, { joined: true, hubRole, userInfo, messages: [], members: new Map() });
    });

    this.socket.on("hub:history", ({ roomId, messages }) => {
      const room = this.rooms.get(roomId);
      if (room) room.messages = messages;
      // Each message has senderName and senderAvatar for display
    });

    this.socket.on("hub:presence", ({ event, roomId, user }) => {
      const room = this.rooms.get(roomId);
      if (!room) return;
      if (event === "joined") {
        room.members.set(user.id, { fullname: user.fullname, avatar: user.avatar, hubRole: user.hubRole });
      } else if (event === "left") {
        room.members.delete(user.id);
      }
    });

    this.socket.on("hub:messageArrived", ({ roomId, sender, message }) => {
      // sender = { id, fullname, avatar }
      const room = this.rooms.get(roomId);
      if (room) room.messages.push(message);
      this.onNewMessage?.(roomId, sender, message);
    });

    this.socket.on("hub:error", ({ error }) => {
      console.error("[ChatHub]", error);
    });

    this.socket.on("hub:typing", ({ roomId, userId }) => {
      this.onTyping?.(roomId, userId, true);
    });
    this.socket.on("hub:stopTyping", ({ roomId, userId }) => {
      this.onTyping?.(roomId, userId, false);
    });

    this.socket.on("hub:online", ({ roomId, userId }) => {
      this.onPresence?.(userId, "online");
    });
    this.socket.on("hub:offline", ({ roomId, userId }) => {
      this.onPresence?.(userId, "offline");
    });
  }

  joinRoom(roomId) {
    this.socket.emit("hub:join", { roomId });
  }

  leaveRoom(roomId) {
    this.socket.emit("hub:leave", { roomId });
    this.rooms.delete(roomId);
  }

  sendMessage(roomId, messageType, content, options = {}) {
    this.socket.emit("hub:send", {
      roomId,
      messageType,
      content,
      ...options
    });
  }

  sendTyping(roomId) {
    this.socket.emit("hub:event", { roomId, event: "typing" });
  }

  sendStopTyping(roomId) {
    this.socket.emit("hub:event", { roomId, event: "stopTyping" });
  }

  disconnect() {
    this.socket.disconnect();
  }
}

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


Leaderboard Service

WECHESS

FRONTEND GUIDE FOR AI CODING AGENTS - PART 11 - Leaderboard Service

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

Service Access

Leaderboard service management is handled through service specific base urls.

Leaderboard 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 leaderboard service, the base URLs are:

Scope

Leaderboard Service Description

Handles ELO/stat computation and leaderboard management for registered players only. Excludes guest users entirely.

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

playerStats Data Object: Stores aggregate stats for a registered chess player: ELO, win/loss history, streak, last game, etc. Excludes guests. One per registered user.

leaderboardEntry Data Object: Holds global leaderboard standings for registered players. Rank, ELO, and season support. Excludes guests.

Leaderboard Service Frontend Description By The Backend Architect

Leaderboard Service Frontend Guide

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

PlayerStats Data Object

Stores aggregate stats for a registered chess player: ELO, win/loss history, streak, last game, etc. Excludes guests. One per registered user.

PlayerStats Data Object Frontend Description By The Backend Architect

Display these stats on the user’s profile and stats page. Guests never have a playerStats object. All stats are global (no season).

PlayerStats Data Object Properties

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

Property Type IsArray Required Secret Description
userId ID false Yes No The registered user this record belongs to (auth:user.id).
eloRating Integer false Yes No Current ELO rating for registered player.
totalGames Integer false Yes No Total completed games (wins + losses + draws) for this player.
wins Integer false Yes No Number of games won by the player.
losses Integer false Yes No Number of games lost by the player.
draws Integer false Yes No Number of drawn games by the player.
streak Integer false Yes No Current win or loss streak. Positive=win streak, negative=loss streak, 0=none/neutral.
lastGameAt Date false No No Timestamp of last completed game for user.
username String false No No Display name for the player, publicly visible.

Relation Properties

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

LeaderboardEntry Data Object

Holds global leaderboard standings for registered players. Rank, ELO, and season support. Excludes guests.

LeaderboardEntry Data Object Frontend Description By The Backend Architect

Use for leaderboard views and global player ranking displays. userId relates to registered player; can include fullname/avatar when needed for display. Season field may be used for future seasonal leaderboard resets.

LeaderboardEntry Data Object Properties

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

Property Type IsArray Required Secret Description
userId ID false Yes No The registered user this leaderboard entry represents.
currentRank Integer false Yes No Current leaderboard rank (1=top). Lower is better.
eloRating Integer false Yes No Player’s current ELO rating (copy from playerStats).
season String false No No Leaderboard season identifier (null for all-time/global, can be set for seasonal leaderboards as needed).
lastRankChangeAt Date false No No Timestamp of last rank change/leaderboard update.
username String false No No Display name for the player, publicly visible on leaderboard.

Relation Properties

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

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.

PlayerStats Default APIs

Operation API Name Route Explicitly Set
Create createPlayerStats /v1/playerstatses Yes
Update updatePlayerStats /v1/playerstatses/:playerStatsId Yes
Delete none - Auto
Get getPlayerStats /v1/playerstatses/:userId Yes
List none - Auto

LeaderboardEntry Default APIs

Operation API Name Route Explicitly Set
Create createLeaderboardEntry /v1/leaderboardentries Auto
Update none - Auto
Delete none - Auto
Get getLeaderboardEntry /v1/leaderboardentries/:userId Yes
List listLeaderboardTopN /v1/leaderboardtopn Yes

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

Event Subscriptions

This service exposes 1 event subscription that allow clients to receive real-time Kafka events. Each subscription groups related topics with built-in authorization derived from the linked DataObject’s access configuration.

Subscription Overview

Subscription Transport Topics Auth
gameEvents websocket 1 Absolute: administrator

Subscription: gameEvents

Subscribes to gameplay events so the leaderboard can update ELO ratings, player stats, and rankings when games are completed.

Available Topics

Event Name DataObject Access Level Tenant Filter Owner Filter Description
gameCompleted playerStats accessPrivate No No Fires when a chess game is updated (status changes to completed/terminated). Used to trigger ELO recalculation and leaderboard rank updates for both players.

Connection & Subscription

import { io } from "socket.io-client";

const socket = io(`${baseUrl}/leaderboard-api/events/gameEvents`, {
  auth: {
    token: `Bearer ${accessToken}`,
  },
  transports: ["websocket"],
});

socket.on("connect", () => {
  // Subscribe to a subset (or all) of the available topics
  socket.emit("subscribe", {
    topics: [&#34;gameCompleted&#34;],
  });
});

// Server confirms which topics were allowed and which were rejected
socket.on("subscribed", ({ topics, rejected }) => {
  console.log("Subscribed to:", topics);
  if (rejected.length > 0) {
    // Some topics may be rejected based on authorization
    // Resubscribe with the allowed subset if needed
    console.warn("Rejected:", rejected);
  }
});

// Receive events
socket.on("event", ({ topic, name, data }) => {
  switch (name) {
    case "gameCompleted":
      // Handle gameCompleted — data from playerStats
      break;
  }
});

// Unsubscribe from topics you no longer need
socket.emit("unsubscribe", { topics: ["gameCompleted"] });

socket.on("unsubscribed", ({ topics }) => {
  console.log("Unsubscribed from:", topics);
});

socket.on("error", ({ message }) => {
  console.error("Subscription error:", message);
});

socket.on("connect_error", (err) => {
  console.error("Connection failed:", err.message);
});

Authorization Details

Each topic’s authorization is derived from its linked DataObject:

API Reference

Create Playerstats API

[Default create API] — This is the designated default create API for the playerStats data object. Frontend generators and AI agents should use this API for standard CRUD operations. Create a player stats record for a newly registered player. Only registered users (never guests) should have this object. Typically used at registration or conversion.

API Frontend Description By The Backend Architect

Called only at registration or on converting guest to registered. Prepares stats for profile display.

Rest Route

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

/v1/playerstatses

Rest Request Parameters

The createPlayerStats api has got 9 regular request parameters

Parameter Type Required Population
userId ID true request.body?.[“userId”]
eloRating Integer true request.body?.[“eloRating”]
totalGames Integer true request.body?.[“totalGames”]
wins Integer true request.body?.[“wins”]
losses Integer true request.body?.[“losses”]
draws Integer true request.body?.[“draws”]
streak Integer true request.body?.[“streak”]
lastGameAt Date false request.body?.[“lastGameAt”]
username String false request.body?.[“username”]
userId : The registered user this record belongs to (auth:user.id).
eloRating : Current ELO rating for registered player.
totalGames : Total completed games (wins + losses + draws) for this player.
wins : Number of games won by the player.
losses : Number of games lost by the player.
draws : Number of drawn games by the player.
streak : Current win or loss streak. Positive=win streak, negative=loss streak, 0=none/neutral.
lastGameAt : Timestamp of last completed game for user.
username : Display name for the player, publicly visible.

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

  axios({
    method: 'POST',
    url: '/v1/playerstatses',
    data: {
            userId:"ID",  
            eloRating:"Integer",  
            totalGames:"Integer",  
            wins:"Integer",  
            losses:"Integer",  
            draws:"Integer",  
            streak:"Integer",  
            lastGameAt:"Date",  
            username:"String",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "playerStats",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"playerStats": {
		"id": "ID",
		"userId": "ID",
		"eloRating": "Integer",
		"totalGames": "Integer",
		"wins": "Integer",
		"losses": "Integer",
		"draws": "Integer",
		"streak": "Integer",
		"lastGameAt": "Date",
		"username": "String",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Update Playerstats API

[Default update API] — This is the designated default update API for the playerStats data object. Frontend generators and AI agents should use this API for standard CRUD operations. Update player statistics when a game completes. Only called for registered users by gameplay service (M2M) or admin; guests not allowed.

API Frontend Description By The Backend Architect

System/gameplay triggers this to update stats at game end. Never called for guests.

Rest Route

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

/v1/playerstatses/:playerStatsId

Rest Request Parameters

The updatePlayerStats api has got 9 regular request parameters

Parameter Type Required Population
playerStatsId ID true request.params?.[“playerStatsId”]
eloRating Integer true request.body?.[“eloRating”]
totalGames Integer true request.body?.[“totalGames”]
wins Integer true request.body?.[“wins”]
losses Integer true request.body?.[“losses”]
draws Integer true request.body?.[“draws”]
streak Integer true request.body?.[“streak”]
lastGameAt Date false request.body?.[“lastGameAt”]
username String false request.body?.[“username”]
playerStatsId : This id paremeter is used to select the required data object that will be updated
eloRating : Current ELO rating for registered player.
totalGames : Total completed games (wins + losses + draws) for this player.
wins : Number of games won by the player.
losses : Number of games lost by the player.
draws : Number of drawn games by the player.
streak : Current win or loss streak. Positive=win streak, negative=loss streak, 0=none/neutral.
lastGameAt : Timestamp of last completed game for user.
username : Display name for the player, publicly visible.

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

  axios({
    method: 'PATCH',
    url: `/v1/playerstatses/${playerStatsId}`,
    data: {
            eloRating:"Integer",  
            totalGames:"Integer",  
            wins:"Integer",  
            losses:"Integer",  
            draws:"Integer",  
            streak:"Integer",  
            lastGameAt:"Date",  
            username:"String",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "playerStats",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"playerStats": {
		"id": "ID",
		"userId": "ID",
		"eloRating": "Integer",
		"totalGames": "Integer",
		"wins": "Integer",
		"losses": "Integer",
		"draws": "Integer",
		"streak": "Integer",
		"lastGameAt": "Date",
		"username": "String",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Get Playerstats API

[Default get API] — This is the designated default get API for the playerStats data object. Frontend generators and AI agents should use this API for standard CRUD operations. Fetch a single registered user’s player stats (private to user or admin).

API Frontend Description By The Backend Architect

Used to display profile stats. User can only view own; admin can view any.

Rest Route

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

/v1/playerstatses/:userId

Rest Request Parameters

The getPlayerStats api has got 1 regular request parameter

Parameter Type Required Population
userId ID true request.params?.[“userId”]
userId : The registered user this record belongs to (auth:user.id)… The parameter is used to query data.

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

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

Get Leaderboardentry API

[Default get API] — This is the designated default get API for the leaderboardEntry data object. Frontend generators and AI agents should use this API for standard CRUD operations. Fetch this player’s leaderboard rank entry (registered users only).

API Frontend Description By The Backend Architect

Allow user to view their own leaderboard position (or admin to view any user). Entry includes user info for display.

Rest Route

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

/v1/leaderboardentries/:userId

Rest Request Parameters

The getLeaderboardEntry api has got 1 regular request parameter

Parameter Type Required Population
userId ID true request.params?.[“userId”]
userId : The registered user this leaderboard entry represents… The parameter is used to query data.

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

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

List Leaderboardtopn API

[Default list API] — This is the designated default list API for the leaderboardEntry data object. Frontend generators and AI agents should use this API for standard CRUD operations. List top N players for leaderboard display (e.g., leaderboard page top 100). Sorted by currentRank ascending (best = 1).

API Frontend Description By The Backend Architect

Leaderboard screen populates using this API; accessible to all authenticated users (guests see empty/null result).

Rest Route

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

/v1/leaderboardtopn

Rest Request Parameters

The listLeaderboardTopN api has got 1 regular request parameter

Parameter Type Required Population
topN Integer false request.query?.[“topN”]
topN : Number of top players to return (max 500)

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

  axios({
    method: 'GET',
    url: '/v1/leaderboardtopn',
    data: {
    
    },
    params: {
             topN:'"Integer"',  
    
        }
  });

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

Create Leaderboardentry API

Create a leaderboard entry for a registered player. Called when PlayerStats exists but LeaderboardEntry is missing.

API Frontend Description By The Backend Architect

Called by ensureLeaderboardEntry when a user has PlayerStats but no LeaderboardEntry.

Rest Route

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

/v1/leaderboardentries

Rest Request Parameters

The createLeaderboardEntry api has got 6 regular request parameters

Parameter Type Required Population
userId ID true request.body?.[“userId”]
currentRank Integer true request.body?.[“currentRank”]
eloRating Integer true request.body?.[“eloRating”]
season String false request.body?.[“season”]
lastRankChangeAt Date false request.body?.[“lastRankChangeAt”]
username String false request.body?.[“username”]
userId : The registered user this leaderboard entry represents.
currentRank : Current leaderboard rank (1=top). Lower is better.
eloRating : Player’s current ELO rating (copy from playerStats).
season : Leaderboard season identifier (null for all-time/global, can be set for seasonal leaderboards as needed).
lastRankChangeAt : Timestamp of last rank change/leaderboard update.
username : Display name for the player, publicly visible on leaderboard.

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

  axios({
    method: 'POST',
    url: '/v1/leaderboardentries',
    data: {
            userId:"ID",  
            currentRank:"Integer",  
            eloRating:"Integer",  
            season:"String",  
            lastRankChangeAt:"Date",  
            username:"String",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "leaderboardEntry",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"leaderboardEntry": {
		"id": "ID",
		"userId": "ID",
		"currentRank": "Integer",
		"eloRating": "Integer",
		"season": "String",
		"lastRankChangeAt": "Date",
		"username": "String",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

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


AgentHub Service

WECHESS

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

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

This document provides extensive instruction for the usage of agentHub

Service Access

AgentHub service management is handled through service specific base urls.

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

For the agentHub service, the base URLs are:

Scope

AgentHub Service Description

AI Agent Hub

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

sys_agentOverride Data Object: Runtime overrides for design-time agents. Null fields use the design default.

sys_agentExecution Data Object: Agent execution log. Records each agent invocation with input, output, and performance metrics.

sys_toolCatalog Data Object: Cached tool catalog discovered from project services. Refreshed periodically.

API Structure

Object Structure of a Successful Response

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

HTTP Status Codes:

Success Response Format:

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

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

Additional Data

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

Error Response

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

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

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

Sys_agentOverride Data Object

Runtime overrides for design-time agents. Null fields use the design default.

Sys_agentOverride Data Object Properties

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

Property Type IsArray Required Secret Description
agentName String Yes No Design-time agent name this override applies to.
provider String No No Override AI provider (e.g., openai, anthropic).
model String No No Override model name.
systemPrompt Text No No Override system prompt.
temperature Double No No Override temperature (0-2).
maxTokens Integer No No Override max tokens.
responseFormat String No No Override response format (text/json).
selectedTools Object No No Array of tool names from the catalog that this agent can use.
guardrails Object No No Override guardrails: { maxToolCalls, timeout, maxTokenBudget }.
enabled Boolean Yes No Enable or disable this agent.
updatedBy ID No No User who last updated this override.

Sys_agentExecution Data Object

Agent execution log. Records each agent invocation with input, output, and performance metrics.

Sys_agentExecution Data Object Properties

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

Property Type IsArray Required Secret Description
agentName String Yes No Agent that was executed.
agentType Enum Yes No Whether this was a design-time or dynamic agent.
source Enum Yes No How the agent was triggered.
userId ID No No User who triggered the execution.
input Object No No Request input (truncated for large payloads).
output Object No No Response output (truncated for large payloads).
toolCalls Integer No No Number of tool calls made during execution.
tokenUsage Object No No Token usage: { prompt, completion, total }.
durationMs Integer No No Execution time in milliseconds.
status Enum Yes No Execution status.
error Text No No Error message if execution failed.

Enum Properties

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

Filter Properties

agentName agentType source userId status

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

Sys_toolCatalog Data Object

Cached tool catalog discovered from project services. Refreshed periodically.

Sys_toolCatalog Data Object Properties

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

Property Type IsArray Required Secret Description
toolName String Yes No Full tool name (e.g., service:apiName).
serviceName String Yes No Source service name.
description Text No No Tool description.
parameters Object No No JSON Schema of tool parameters.
lastRefreshed Date No No When this tool was last discovered/refreshed.

Filter Properties

serviceName

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

Default CRUD APIs

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

Sys_agentOverride Default APIs

Operation API Name Route Explicitly Set
Create createAgentOverride /v1/agentoverride Yes
Update updateAgentOverride /v1/agentoverride/:sys_agentOverrideId Yes
Delete deleteAgentOverride /v1/agentoverride/:sys_agentOverrideId Yes
Get getAgentOverride /v1/agentoverride/:sys_agentOverrideId Yes
List listAgentOverrides /v1/agentoverrides Yes

Sys_agentExecution Default APIs

Operation API Name Route Explicitly Set
Create none - Auto
Update none - Auto
Delete none - Auto
Get getAgentExecution /v1/agentexecution/:sys_agentExecutionId Yes
List listAgentExecutions /v1/agentexecutions Yes

Sys_toolCatalog Default APIs

Operation API Name Route Explicitly Set
Create none - Auto
Update none - Auto
Delete none - Auto
Get getToolCatalogEntry /v1/toolcatalogentry/:sys_toolCatalogId Yes
List listToolCatalog /v1/toolcatalog Yes

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

API Reference

Get Agentoverride API

[Default get API] — This is the designated default get API for the sys_agentOverride data object. Frontend generators and AI agents should use this API for standard CRUD operations.

Rest Route

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

/v1/agentoverride/:sys_agentOverrideId

Rest Request Parameters

The getAgentOverride api has got 1 regular request parameter

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

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

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

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_agentOverride",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"sys_agentOverride": {
		"id": "ID",
		"agentName": "String",
		"provider": "String",
		"model": "String",
		"systemPrompt": "Text",
		"temperature": "Double",
		"maxTokens": "Integer",
		"responseFormat": "String",
		"selectedTools": "Object",
		"guardrails": "Object",
		"enabled": "Boolean",
		"updatedBy": "ID",
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"isActive": true
	}
}

List Agentoverrides API

[Default list API] — This is the designated default list API for the sys_agentOverride data object. Frontend generators and AI agents should use this API for standard CRUD operations.

Rest Route

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

/v1/agentoverrides

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

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

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

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_agentOverrides",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"sys_agentOverrides": [
		{
			"id": "ID",
			"agentName": "String",
			"provider": "String",
			"model": "String",
			"systemPrompt": "Text",
			"temperature": "Double",
			"maxTokens": "Integer",
			"responseFormat": "String",
			"selectedTools": "Object",
			"guardrails": "Object",
			"enabled": "Boolean",
			"updatedBy": "ID",
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID",
			"isActive": true
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Update Agentoverride API

[Default update API] — This is the designated default update API for the sys_agentOverride data object. Frontend generators and AI agents should use this API for standard CRUD operations.

Rest Route

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

/v1/agentoverride/:sys_agentOverrideId

Rest Request Parameters

The updateAgentOverride api has got 10 regular request parameters

Parameter Type Required Population
sys_agentOverrideId ID true request.params?.[“sys_agentOverrideId”]
provider String request.body?.[“provider”]
model String request.body?.[“model”]
systemPrompt Text request.body?.[“systemPrompt”]
temperature Double request.body?.[“temperature”]
maxTokens Integer request.body?.[“maxTokens”]
responseFormat String request.body?.[“responseFormat”]
selectedTools Object request.body?.[“selectedTools”]
guardrails Object request.body?.[“guardrails”]
enabled Boolean request.body?.[“enabled”]
sys_agentOverrideId : This id paremeter is used to select the required data object that will be updated
provider : Override AI provider (e.g., openai, anthropic).
model : Override model name.
systemPrompt : Override system prompt.
temperature : Override temperature (0-2).
maxTokens : Override max tokens.
responseFormat : Override response format (text/json).
selectedTools : Array of tool names from the catalog that this agent can use.
guardrails : Override guardrails: { maxToolCalls, timeout, maxTokenBudget }.
enabled : Enable or disable this agent.

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

  axios({
    method: 'PATCH',
    url: `/v1/agentoverride/${sys_agentOverrideId}`,
    data: {
            provider:"String",  
            model:"String",  
            systemPrompt:"Text",  
            temperature:"Double",  
            maxTokens:"Integer",  
            responseFormat:"String",  
            selectedTools:"Object",  
            guardrails:"Object",  
            enabled:"Boolean",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_agentOverride",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"sys_agentOverride": {
		"id": "ID",
		"agentName": "String",
		"provider": "String",
		"model": "String",
		"systemPrompt": "Text",
		"temperature": "Double",
		"maxTokens": "Integer",
		"responseFormat": "String",
		"selectedTools": "Object",
		"guardrails": "Object",
		"enabled": "Boolean",
		"updatedBy": "ID",
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"isActive": true
	}
}

Create Agentoverride API

[Default create API] — This is the designated default create API for the sys_agentOverride data object. Frontend generators and AI agents should use this API for standard CRUD operations.

Rest Route

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

/v1/agentoverride

Rest Request Parameters

The createAgentOverride api has got 9 regular request parameters

Parameter Type Required Population
agentName String true request.body?.[“agentName”]
provider String false request.body?.[“provider”]
model String false request.body?.[“model”]
systemPrompt Text false request.body?.[“systemPrompt”]
temperature Double false request.body?.[“temperature”]
maxTokens Integer false request.body?.[“maxTokens”]
responseFormat String false request.body?.[“responseFormat”]
selectedTools Object false request.body?.[“selectedTools”]
guardrails Object false request.body?.[“guardrails”]
agentName : Design-time agent name this override applies to.
provider : Override AI provider (e.g., openai, anthropic).
model : Override model name.
systemPrompt : Override system prompt.
temperature : Override temperature (0-2).
maxTokens : Override max tokens.
responseFormat : Override response format (text/json).
selectedTools : Array of tool names from the catalog that this agent can use.
guardrails : Override guardrails: { maxToolCalls, timeout, maxTokenBudget }.

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

  axios({
    method: 'POST',
    url: '/v1/agentoverride',
    data: {
            agentName:"String",  
            provider:"String",  
            model:"String",  
            systemPrompt:"Text",  
            temperature:"Double",  
            maxTokens:"Integer",  
            responseFormat:"String",  
            selectedTools:"Object",  
            guardrails:"Object",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_agentOverride",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"sys_agentOverride": {
		"id": "ID",
		"agentName": "String",
		"provider": "String",
		"model": "String",
		"systemPrompt": "Text",
		"temperature": "Double",
		"maxTokens": "Integer",
		"responseFormat": "String",
		"selectedTools": "Object",
		"guardrails": "Object",
		"enabled": "Boolean",
		"updatedBy": "ID",
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"isActive": true
	}
}

Delete Agentoverride API

[Default delete API] — This is the designated default delete API for the sys_agentOverride data object. Frontend generators and AI agents should use this API for standard CRUD operations.

Rest Route

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

/v1/agentoverride/:sys_agentOverrideId

Rest Request Parameters

The deleteAgentOverride api has got 1 regular request parameter

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

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

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

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_agentOverride",
	"method": "DELETE",
	"action": "delete",
	"appVersion": "Version",
	"rowCount": 1,
	"sys_agentOverride": {
		"id": "ID",
		"agentName": "String",
		"provider": "String",
		"model": "String",
		"systemPrompt": "Text",
		"temperature": "Double",
		"maxTokens": "Integer",
		"responseFormat": "String",
		"selectedTools": "Object",
		"guardrails": "Object",
		"enabled": "Boolean",
		"updatedBy": "ID",
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"isActive": false
	}
}

List Toolcatalog API

[Default list API] — This is the designated default list API for the sys_toolCatalog data object. Frontend generators and AI agents should use this API for standard CRUD operations.

Rest Route

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

/v1/toolcatalog

Rest Request Parameters

Filter Parameters

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

serviceName (String): Source service name.

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

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

REST Response

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

Get Toolcatalogentry API

[Default get API] — This is the designated default get API for the sys_toolCatalog data object. Frontend generators and AI agents should use this API for standard CRUD operations.

Rest Route

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

/v1/toolcatalogentry/:sys_toolCatalogId

Rest Request Parameters

The getToolCatalogEntry api has got 1 regular request parameter

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

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

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

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_toolCatalog",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"sys_toolCatalog": {
		"id": "ID",
		"toolName": "String",
		"serviceName": "String",
		"description": "Text",
		"parameters": "Object",
		"lastRefreshed": "Date",
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"isActive": true
	}
}

List Agentexecutions API

[Default list API] — This is the designated default list API for the sys_agentExecution data object. Frontend generators and AI agents should use this API for standard CRUD operations.

Rest Route

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

/v1/agentexecutions

Rest Request Parameters

Filter Parameters

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

agentName (String): Agent that was executed.

agentType (Enum): Whether this was a design-time or dynamic agent.

source (Enum): How the agent was triggered.

userId (ID): User who triggered the execution.

status (Enum): Execution status.

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

  axios({
    method: 'GET',
    url: '/v1/agentexecutions',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section above)
        // agentName: '<value>' // Filter by agentName
        // agentType: '<value>' // Filter by agentType
        // source: '<value>' // Filter by source
        // userId: '<value>' // Filter by userId
        // status: '<value>' // Filter by status
            }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_agentExecutions",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"sys_agentExecutions": [
		{
			"id": "ID",
			"agentName": "String",
			"agentType": "Enum",
			"agentType_idx": "Integer",
			"source": "Enum",
			"source_idx": "Integer",
			"userId": "ID",
			"input": "Object",
			"output": "Object",
			"toolCalls": "Integer",
			"tokenUsage": "Object",
			"durationMs": "Integer",
			"status": "Enum",
			"status_idx": "Integer",
			"error": "Text",
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID",
			"isActive": true
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Get Agentexecution API

[Default get API] — This is the designated default get API for the sys_agentExecution data object. Frontend generators and AI agents should use this API for standard CRUD operations.

Rest Route

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

/v1/agentexecution/:sys_agentExecutionId

Rest Request Parameters

The getAgentExecution api has got 1 regular request parameter

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

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

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

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_agentExecution",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"sys_agentExecution": {
		"id": "ID",
		"agentName": "String",
		"agentType": "Enum",
		"agentType_idx": "Integer",
		"source": "Enum",
		"source_idx": "Integer",
		"userId": "ID",
		"input": "Object",
		"output": "Object",
		"toolCalls": "Integer",
		"tokenUsage": "Object",
		"durationMs": "Integer",
		"status": "Enum",
		"status_idx": "Integer",
		"error": "Text",
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"isActive": true
	}
}

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


Auth Service

Service Design Specification

Service Design Specification

Athentication documentation -Version:1.0.29

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 ‘wechess-auth-service’.

So in this document you will find

This document has been automatically generated based on the authetication module definition within Mindbricks, ensuring that the information reflects the source of truth used during code generation and deployment.

The document is intended to serve multiple audiences:

Note for Frontend Developers: While this document is valuable for understanding business logic and data interactions, please refer to the Service API Documentation for endpoint-level specifications and integration details.

Note for Backend Developers: Since the code for this service is automatically generated by Mindbricks, you typically won’t need to implement or modify it manually. However, this document is especially valuable when you’re building other services—whether within Mindbricks or externally—that need to interact with or depend on this service. It provides a clear reference to the service’s data contracts, business rules, and API structure, helping ensure compatibility and correct integration.

This service is accessible via the following environment-specific URLs:

Authentication Essentials

Mindbricks provides a comprehensive authentication module that serves as the foundation for user management and security across all services. This module is designed to be flexible, allowing for the generation of authentication and authorization code tailored to project’s specific needs. Mindbricks supports multiple authentication strategies, for the first validation of the user, the auth service supports the following authentication strategies:

JWT tokens are generated by the auth service and can be used to access protected resources of the service. The JWT token is open and contains the user’s identity and any additional claims required for authorization. The token is signed using a private RSA key, ensuring its integrity and authenticity. Once the JWT token is generated, it can be used to access protected resources of the service.

The JWT token is structured as follows:

{
  "keyId": "716a8738ec3d499f84d58bda6ee772ce",
  "sessionId": "9cf23fa8-07d4-4e7c-80a6-ec6d6ac96bb9",
  "userId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38",
  "sub": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38",
  loginDate: "2023-10-01T12:00:00Z"
}

Key id for a token represents the private-public key pair used to sign the token. To validate the signature of the token, the public key is used. Any service which will use the JWT token can request a publick ket from the auth service using the following endpoint:

GET /publickey?keyId=[keyIdInToken]

Mindbricks generated services manages the key rotation automatically, so the public key is always up to date and valid for the JWT tokens generated by the auth service. If you add any manual service to the project which should validate the JWT token, you can use the public key endpoint to get the public key and validate the JWT token signature.

The JWT token life cycle is configured in the authentication module of the project. This project uses the following configuration for the JWT token: The token is valid for days after it is issued. And the private key used to sign the token is rotated every days.

Note that when a new key is generated to sign the JWT tokens, the old key is still valid for the period of days. So it is recommended to cache the old public keys for the period of days to validate the JWT tokens issued with the old keys.

The Login Definition

The login definition is a crucial part of the authentication module, as it defines how user and tenant model is defined. In this section it is specified how users, user groups, and tenants are defined in the project’s data model. These definitions allow Mindbricks to dynamically extract identity and authorization data from project-specific data objects.

User Settings

Super Admin Identifier: tua@admin.com The login email of the super admin user. This user has full permissions across the project and is not tenant-scoped. When primaryLoginIdentifier is ‘email’ or ‘emailOrMobile’, this should be an email address. When it is ‘mobile’, this should be a mobile number in E.164 format.

Super admin user is created automatically when the project is initialized with a roleId of superAdmin and a userId of f7103b85-fcda-4dec-92c6-c336f71fd3a2. The primary identifier field is populated with superAdminIdentifier and marked as verified. When the secondary identifier field is required (secondaryIdentifierPresence: "required" or dualIdentifierRegistration: "both"), a placeholder value is used ("noreply@system.local" for email, "+10000000000" for mobile) to satisfy the NOT NULL constraint.

Super Admin User Password: Super admin user password is defined in this module as well, but masked in this document. To edit it you can use the User Settings section of Login Definition chapter of the Mindbricks Authentication Module.

Username Type: The type of the username which is stored in the database and written to the session object for information purposes.: -asFullName: The username is stored in one property, fullname, and represents the full name of the user, which is a combination of first name and last name. -asNamePair: The username is stored in two properties, name and surname, which are combined to form the full name of the user.

This project uses the asFullName type, so the user name is stored in one property, fullname, and represents the full name of the user, which is a combination of first name and last name.

User Groups: The project does not support user groups, so the auth service will not create any user group related data objects.

Public User Registration: The project allows public user registration, meaning that users can register themselves without the need for an admin to create an account for them. This is useful for projects that require user self-registration, such as social networks, forums, or any application where users need to create their own accounts. The user registration process is handled by the auth service, which will create a new user data object in the database. The user registration process will create a new user with the userId and roleId set to user, and the user will be able to log in using the username and password they provided during registration. The reigstered user’s roleId will be updated later to any other roleId by the super admin or admin users. If any social login is enabled for the project, the user can also sign up using the social login providers. Note that when users register themselves using socila logi, first all the data that can be provided by the social login provider will written to Redis cache with a key called socialCode, and this code will be returned to the api consumer, which can be used to complete the registration process.

Email Verification Is Not Required For Login: The project does not require email verification for user login, meaning that users can log in without verifying their email address. This is useful for projects that do not require email verification, such as enterprise applications, internal tools, or any application where email verification is not required. The email verification process is not handled by the auth service, and users can log in without verifying their email address. While the email verification is not required, the aut service will still support email verification if it is configured in the verification services. You can prefer email verification at any time before any action or make it optional which means that users can verify their email address if they want to, but it is not required for login. You can check the email verification details in the REST API documentation of the auth service.

Email 2FA Is Not Required For Login: The project does not require email-based two-factor authentication (2FA) for user login, meaning that users can log in using only their username and password without providing a second factor of authentication. This is useful for projects that do not require an additional layer of security for user login, such as enterprise applications, internal tools, or any application where email-based 2FA is not required. While the email 2FA is not required, the auth service will still support email 2FA if it is configured in the verification services. You can prefer email 2FA at any time before any action or make it optional which means that users can provide a second factor of authentication if they want to, but it is not required for login. You can check the email 2FA details in the REST API documentation of the auth service.

User Mobile Is Not Active: The authetication module is not configured to support mobile numbers for users.

User Auto Avatar Script: Mindbricks stores an avatar property inthe user data model automatically. This project supports also automatic avatar generation for users with the following script configuretion. The auth service will generate an avatar for each user when it is not specified in the registration process.

The script is defined in the authentication module and can be edited in the User Settings section of Login Definition chapter of the Mindbricks Authentication Module. The script is executed when a new user is created, and it generates an avatar based on user properties.

`https://gravatar.com/avatar/${LIB.common.md5(this.email ?? 'nullValue')}?s=200&d=identicon`

Tenant Settings

This project is not configured to support multi-tenancy, meaning that users and other data are not scoped to a specific tenant. This allows for a single-tenant data management, where all users and other data are shared across the project.

Verification Services

The project supports various verification services that enhance security and user experience. These services are designed to verify user identity through different channels, such as email and mobile, and can be configured to suit the project’s needs. Please check the auth service API documentation for more details on how to use these services through the REST API.

A verification service is configured with the following settings: -verificationType: The type of verification handling, which can be one of the following: – byCode: The verification is handled by entering a code in the frontend. – byLink: The verification is handled by clicking a link in the frontend, which will automatically verify the user through the auth service. -resendTimeWindow: The time window in seconds during which the user can request a new verification code or link. -expireTimeWindow: The time window in seconds after which the verification code or link will expire and become invalid.

Password Reset By Email

The project supports password reset by email, allowing users to reset their passwords securely through a verification code sent to their registered email address. This service is useful for projects that require users to reset their passwords securely, such as social networks, forums, or any application where password reset is required. The password reset by email process is handled by the auth service, which will send a verification code to the user’s email address after they request a password reset.

{
    verificationType: "byLink",
    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: "byLink",
    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: "byLink",
    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: guest registeredPlayer administrator

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

{
  "superAdmin": "'superAdmin'",
  "admin": "'admin'",
  "user": "'user'",
  "guest": "'guest'",
  "registeredPlayer": "'registeredPlayer'",
  "administrator": "'administrator'"
}

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 (Not Configured)

The project does not support any user properties, meaning that users can only have the default properties defined in the user data object. If you want to add user properties, you can do so in the User Properties chapter of Mindbricks Authentication Module.

To see a detailed configuration 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 wechess-auth-service.

Data deletion is managed using a soft delete strategy. Instead of removing records from the database, they are flagged as inactive by setting the isActive field to false.

Object Name Description Public Access
user A data object that stores the user information and handles login settings. accessPrivate
userAvatarsFile Auto-generated file storage for the userAvatars database bucket. Files are stored as BYTEA in PostgreSQL. accessPublic

user Data Object

Object Overview

Description: A data object that stores the user information and handles login settings.

This object represents a core data structure within the service and acts as the blueprint for database interaction, API generation, and business logic enforcement. It is defined using the ObjectSettings pattern, which governs its behavior, access control, caching strategy, and integration points with other systems such as Stripe and Redis.

Core Configuration

Redis Entity Caching

This data object is configured for Redis entity caching, which improves data retrieval performance by storing frequently accessed data in Redis. Each time a new instance is created, updated or deleted, the cache is updated accordingly. Any get requests by id will first check the cache before querying the database. If you want to use the cache by other select criteria, you can configure any data property as a Redis cluster.

Properties Schema

Property Type Required Description
email String Yes A string value to represent the user's email.
password String Yes A string value to represent the user's password. It will be stored as hashed.
fullname String Yes A string value to represent the fullname of the user
avatar String No The avatar url of the user. A random avatar will be generated if not provided
roleId String Yes A string value to represent the roleId of the user.
emailVerified Boolean Yes A boolean value to represent the email verification status of the user.

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

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.

Elastic Search Indexing

email fullname roleId emailVerified

Properties that are indexed in Elastic Search will be searchable via the Elastic Search API. While all properties are stored in the elastic search index of the data object, only those marked for Elastic Search indexing will be available for search queries.

Database Indexing

email

Properties that are indexed in the database will be optimized for query performance, allowing for faster data retrieval. Make a property indexed in the database if you want to use it frequently in query filters or sorting.

Unique Properties

email

Unique properties are enforced to have distinct values across all instances of the data object, preventing duplicate entries. Note that a unique property is automatically indexed in the database so you will not need to set the Indexed in DB option.

Cache Select Properties

email

Cache select properties are used to collect data from Redis entity cache with a different key than the data object id. This allows you to cache data that is not directly related to the data object id, but a frequently used filter.

Secondary Key Properties

email

Secondary key properties are used to create an additional indexed identifiers for the data object, allowing for alternative access patterns. Different than normal indexed properties, secondary keys will act as primary keys and Mindbricks will provide automatic secondary key db utility functions to access the data object by the secondary key.

Filter Properties

email fullname roleId

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

userAvatarsFile Data Object

Object Overview

Description: Auto-generated file storage for the userAvatars database bucket. Files are stored as BYTEA in PostgreSQL.

This object represents a core data structure within the service and acts as the blueprint for database interaction, API generation, and business logic enforcement. It is defined using the ObjectSettings pattern, which governs its behavior, access control, caching strategy, and integration points with other systems such as Stripe and Redis.

Core Configuration

Properties Schema

Property Type Required Description
fileName String Yes Original file name as uploaded by the client.
mimeType String Yes MIME type of the uploaded file (e.g., image/png, application/pdf).
fileSize Integer Yes File size in bytes.
accessKey String Yes 12-character random key for shareable access. Auto-generated on upload.
ownerId ID No ID of the user who uploaded the file (from session).
fileData Blob Yes Binary file content. Stored as BYTEA in PostgreSQL or Buffer in MongoDB.
metadata Object No Optional JSON metadata for the file (tags, alt text, etc.).
userId ID No Reference to the owner user record.

Default Values

Default values are automatically assigned to properties when a new object is created, if no value is provided in the request body. Since default values are applied on db level, they should be literal values, not expressions.If you want to use expressions, you can use transposed parameters in any business API to set default values dynamically.

Constant Properties

fileName mimeType fileSize accessKey ownerId fileData userId

Constant properties are defined to be immutable after creation, meaning they cannot be updated or changed once set. They are typically used for properties that should remain constant throughout the object’s lifecycle. A property is set to be constant if the Allow Update option is set to false.

Auto Update Properties

fileName mimeType fileSize accessKey ownerId fileData metadata userId

An update crud API created with the option Auto Params enabled will automatically update these properties with the provided values in the request body. If you want to update any property in your own business logic not by user input, you can set the Allow Auto Update option to false. These properties will be added to the update API’s body parameters and can be updated by the user if any value is provided in the request body.

Elastic Search Indexing

fileName mimeType fileSize ownerId userId

Properties that are indexed in Elastic Search will be searchable via the Elastic Search API. While all properties are stored in the elastic search index of the data object, only those marked for Elastic Search indexing will be available for search queries.

Database Indexing

fileName mimeType accessKey ownerId userId

Properties that are indexed in the database will be optimized for query performance, allowing for faster data retrieval. Make a property indexed in the database if you want to use it frequently in query filters or sorting.

Unique Properties

accessKey

Unique properties are enforced to have distinct values across all instances of the data object, preventing duplicate entries. Note that a unique property is automatically indexed in the database so you will not need to set the Indexed in DB option.

Session Data Properties

ownerId

Session data properties are used to store data that is specific to the user session, allowing for personalized experiences and temporary data storage. If a property is configured as session data, it will be automatically mapped to the related field in the user session during CRUD operations. Note that session data properties can not be mutated by the user, but only by the system.

This property is also used to store the owner of the session data, allowing for ownership checks and access control.

Filter Properties

mimeType ownerId userId

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


REST API GUIDE

REST API GUIDE

wechess-auth-service

Version: 1.0.29

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 wechess-access-token
Cookie wechess-access-token

Please ensure the token is correctly placed in one of these locations, using the appropriate label as indicated. The service prioritizes these locations in the order listed, processing the first token it successfully identifies.

Api Definitions

This section outlines the API endpoints available within the Auth service. Each endpoint can receive parameters through various methods, meticulously described in the following definitions. It’s important to understand the flexibility in how parameters can be included in requests to effectively interact with the Auth service.

This service is configured to listen for HTTP requests on port 3011, serving both the main API interface and default administrative endpoints.

The following routes are available by default:

This service is accessible via the following environment-specific URLs:

Parameter Inclusion Methods: Parameters can be incorporated into API requests in several ways, each with its designated location. Understanding these methods is crucial for correctly constructing your requests:

Query Parameters: Included directly in the URL’s query string.

Path Parameters: Embedded within the URL’s path.

Body Parameters: Sent within the JSON body of the request.

Session Parameters: Automatically read from the session object. This method is used for parameters that are intrinsic to the user’s session, such as userId. When using an API that involves session parameters, you can omit these from your request. The service will automatically bind them to the API layer, provided that a session is associated with your request.

Note on Session Parameters: Session parameters represent a unique method of parameter inclusion, relying on the context of the user’s session. A common example of a session parameter is userId, which the service automatically associates with your request when a session exists. This feature ensures seamless integration of user-specific data without manual input for each request.

By adhering to the specified parameter inclusion methods, you can effectively utilize the Auth service’s API endpoints. For detailed information on each endpoint, including required parameters and their accepted locations, refer to the individual API definitions below.

Common Parameters

The Auth service’s business API support several common parameters designed to modify and enhance the behavior of API requests. These parameters are not individually listed in the API route definitions to avoid repetition. Instead, refer to this section to understand how to leverage these common behaviors across different routes. Note that all common parameters should be included in the query part of the URL.

Supported Common Parameters:

By utilizing these common parameters, you can tailor the behavior of API requests to suit your specific requirements, ensuring optimal performance and usability of the Auth service.

Error Response

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

Each error response is structured to provide meaningful insight into the problem, assisting in diagnosing and resolving issues efficiently.

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

Object Structure of a Successfull Response

When the Auth service processes requests successfully, it wraps the requested resource(s) within a JSON envelope. This envelope not only contains the data but also includes essential metadata, such as configuration details and pagination information, to enrich the response and provide context to the client.

Key Characteristics of the Response Envelope:

Design Considerations: The structure of a API’s response data is meticulously crafted during the service’s architectural planning. This design ensures that responses adequately reflect the intended data relationships and service logic, providing clients with rich and meaningful information.

Brief Data: Certain API’s return a condensed version of the object data, intentionally selecting only specific fields deemed useful for that request. In such instances, the API documentation will detail the properties included in the response, guiding developers on what to expect.

API Response Structure

The API utilizes a standardized JSON envelope to encapsulate responses. This envelope is designed to consistently deliver both the requested data and essential metadata, ensuring that clients can efficiently interpret and utilize the response.

HTTP Status Codes:

Success Response Format:

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

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

Handling Errors:

For details on handling error scenarios and understanding the structure of error responses, please refer to the “Error Response” section provided earlier in this documentation. It outlines how error conditions are communicated, including the use of HTTP status codes and standardized JSON structures for error messages.

Resources

Auth service provides the following resources which are stored in its own database as a data object. Note that a resource for an api access is a data object for the service.

User resource

Resource Definition : A data object that stores the user information and handles login settings. User Resource Properties

Name Type Required Default Definition
email String * A string value to represent the user's email.*
password String * A string value to represent the user's password. It will be stored as hashed.*
fullname String A string value to represent the fullname of the user
avatar String The avatar url of the user. A random avatar will be generated if not provided
roleId String A string value to represent the roleId of the user.
emailVerified Boolean A boolean value to represent the email verification status of the user.

UserAvatarsFile resource

Resource Definition : Auto-generated file storage for the userAvatars database bucket. Files are stored as BYTEA in PostgreSQL. UserAvatarsFile Resource Properties

Name Type Required Default Definition
fileName String Original file name as uploaded by the client.
mimeType String MIME type of the uploaded file (e.g., image/png, application/pdf).
fileSize Integer File size in bytes.
accessKey String 12-character random key for shareable access. Auto-generated on upload.
ownerId ID ID of the user who uploaded the file (from session).
fileData Blob Binary file content. Stored as BYTEA in PostgreSQL or Buffer in MongoDB.
metadata Object Optional JSON metadata for the file (tags, alt text, etc.).
userId ID Reference to the owner user record.

Business Api

Get User API

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

Rest Route

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

/v1/users/:userId

Rest Request Parameters

The getUser api has got 1 regular request parameter

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

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

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

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "user",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"user": {
		"id": "ID",
		"email": "String",
		"password": "String",
		"fullname": "String",
		"avatar": "String",
		"roleId": "String",
		"emailVerified": "Boolean",
		"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 3 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”]
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

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",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "user",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"user": {
		"id": "ID",
		"email": "String",
		"password": "String",
		"fullname": "String",
		"avatar": "String",
		"roleId": "String",
		"emailVerified": "Boolean",
		"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 3 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”]
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

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",  
    
    },
    params: {
    
        }
  });

REST Response

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

Create User API

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

Rest Route

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

/v1/users

Rest Request Parameters

The createUser api has got 4 regular request parameters

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

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

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

REST Response

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

Delete User API

This api is used by admins to delete user profiles.

Rest Route

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

/v1/users/:userId

Rest Request Parameters

The deleteUser api has got 1 regular request parameter

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

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

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

REST Response

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

Archive Profile API

This api is used by users to archive their profiles.

Rest Route

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

/v1/archiveprofile/:userId

Rest Request Parameters

The archiveProfile api has got 1 regular request parameter

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

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

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

REST Response

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

List Users API

The list of users is filtered by the tenantId.

Rest Route

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

/v1/users

Rest Request Parameters

Filter Parameters

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

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

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

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

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

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

REST Response

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

Search Users API

The list of users is filtered by the tenantId.

Rest Route

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

/v1/searchusers

Rest Request Parameters

The searchUsers api has got 1 regular request parameter

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

Filter Parameters

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

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

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

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

REST Response

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

Update Userrole API

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

Rest Route

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

/v1/userrole/:userId

Rest Request Parameters

The updateUserRole api has got 2 regular request parameters

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

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

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

REST Response

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

Update Userpassword API

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

Rest Route

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

/v1/userpassword/:userId

Rest Request Parameters

The updateUserPassword api has got 3 regular request parameters

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

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

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

REST Response

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

Update Userpasswordbyadmin API

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

Rest Route

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

/v1/userpasswordbyadmin/:userId

Rest Request Parameters

The updateUserPasswordByAdmin api has got 2 regular request parameters

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

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

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

REST Response

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

Get Briefuser API

This route is used by public to get simple user profile information.

Rest Route

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

/v1/briefuser/:userId

Rest Request Parameters

The getBriefUser api has got 1 regular request parameter

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

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

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

REST Response

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

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

Stream Test API

Test API for iterator action streaming via SSE.

Rest Route

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

/v1/streamtest/:userId

Rest Request Parameters

The streamTest api has got 1 regular request parameter

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

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

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

REST Response

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

Register User API

This api is used by public users to register themselves

Rest Route

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

/v1/registeruser

Rest Request Parameters

The registerUser api has got 4 regular request parameters

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

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

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

REST Response

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

Get Useravatarsfile API

[Default get API] — This is the designated default get API for the userAvatarsFile data object. Frontend generators and AI agents should use this API for standard CRUD operations.

Rest Route

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

/v1/useravatarsfiles/:userAvatarsFileId

Rest Request Parameters

The getUserAvatarsFile api has got 1 regular request parameter

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

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

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

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "userAvatarsFile",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"userAvatarsFile": {
		"id": "ID",
		"fileName": "String",
		"mimeType": "String",
		"fileSize": "Integer",
		"accessKey": "String",
		"ownerId": "ID",
		"fileData": "Blob",
		"metadata": "Object",
		"userId": "ID",
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"isActive": true
	}
}

List Useravatarsfiles API

[Default list API] — This is the designated default list API for the userAvatarsFile data object. Frontend generators and AI agents should use this API for standard CRUD operations.

Rest Route

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

/v1/useravatarsfiles

Rest Request Parameters

Filter Parameters

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

mimeType (String): MIME type of the uploaded file (e.g., image/png, application/pdf).

ownerId (ID): ID of the user who uploaded the file (from session).

userId (ID): Reference to the owner user record.

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

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

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "userAvatarsFiles",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"userAvatarsFiles": [
		{
			"id": "ID",
			"fileName": "String",
			"mimeType": "String",
			"fileSize": "Integer",
			"accessKey": "String",
			"ownerId": "ID",
			"fileData": "Blob",
			"metadata": "Object",
			"userId": "ID",
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID",
			"isActive": true
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Delete Useravatarsfile API

[Default delete API] — This is the designated default delete API for the userAvatarsFile data object. Frontend generators and AI agents should use this API for standard CRUD operations.

Rest Route

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

/v1/useravatarsfiles/:userAvatarsFileId

Rest Request Parameters

The deleteUserAvatarsFile api has got 1 regular request parameter

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

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

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

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "userAvatarsFile",
	"method": "DELETE",
	"action": "delete",
	"appVersion": "Version",
	"rowCount": 1,
	"userAvatarsFile": {
		"id": "ID",
		"fileName": "String",
		"mimeType": "String",
		"fileSize": "Integer",
		"accessKey": "String",
		"ownerId": "ID",
		"fileData": "Blob",
		"metadata": "Object",
		"userId": "ID",
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"isActive": false
	}
}

Authentication Specific Routes

Route: login

Route Definition: Handles the login process by verifying user credentials and generating an authenticated session.

Route Type: login

Access Routes:

Parameters

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

Notes

// Sample POST /login call
axios.post("/login", {
  username: "user@example.com",
  password: "securePassword"
});

Success Response

Returns the authenticated session object with a status code 200 OK.

A secure HTTP-only cookie and an access token header are included in the response.

{
  "userId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38",
  "email": "user@example.com",
  "fullname": "John Doe",
  ...
}

Error Responses

Route: logout

Route Definition: Logs the user out by terminating the current session and clearing the access token.

Route Type: logout

Access Route: POST /logout

Parameters

This route does not require any parameters in the body or query.

Behavior

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

Notes

Error Responses 00200 OK:** Always returned, regardless of whether a session existed. Logout is treated as idempotent.

Route: publickey

Route Definition: Returns the public RSA key used to verify JWT access tokens issued by the auth service.

Route Type: publicKeyFetch

Access Route: GET /publickey

Parameters

Parameter Type Required Population
keyId String No request.query.keyId

Behavior

// Sample GET /publickey call
axios.get("/publickey", {
  params: {
    keyId: "currentKeyIdOptional"
  }
});

Success Response Returns the active public key and its associated keyId.

{
    "keyId": "a1b2c3d4",
    "keyData": "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhki...\n-----END PUBLIC KEY-----"
}

Error Responses 404 Not Found: Public key file could not be found on the server.

Token Key Management

Mindbricks uses RSA key pairs to sign and verify JWT access tokens securely.
While the auth service signs each token with a private key, other services within the system — or external clients — need the corresponding public key to verify the authenticity and integrity of received tokens.

The /publickey endpoint allows services and clients to dynamically fetch the currently active public key, ensuring that token verification remains secure even if key rotation is performed.

Note:
The /publickey route is not intended for direct frontend (browser) consumption.
Instead, it is primarily used by trusted backend services, APIs, or middleware systems that need to independently verify access tokens issued by the auth service — without making verification-dependent API calls to the auth service itself.

Accessing the public key is crucial for validating user sessions efficiently and maintaining a decentralized trust model across your platform.

Route: relogin

Route Definition: Performs a silent login by verifying the current access token, refreshing the session, and returning a new access token along with updated user information.

Route Type: sessionRefresh

Access Route: GET /relogin

Parameters

This route does not require any request parameters.

Behavior

// Example call to refresh session
axios.get("/relogin", {
  headers: {
    "Authorization": "Bearer your-jwt-token"
  }
});

Success Response Returns a new session object, refreshed from database data.

{
  "sessionId": "new-session-uuid",
  "userId": "user-uuid",
  "email": "user@example.com",
  "roleId": "admin",
  "accessToken": "new-jwt-token",
  ...
}

Error Responses

{
  "status": "ERR",
  "message": "Cannot relogin"
}

Notes

Tip: This route is ideal when you want to rebuild a user’s session in the frontend without requiring them to manually log in again.

Verification Services — Email Verification

Email verification is a two-step flow that ensures a user’s email address is verified and trusted by the system.

All verification services, including email verification, are located under the /verification-services base path.

When is Email Verification Triggered?

Email Verification Flow

  1. Frontend calls /verification-services/email-verification/start with the user’s email address.
    • Mindbricks checks if the email is already verified.
    • A secret code is generated and stored in the cache linked to the user.
    • The code is sent to the user’s email or returned in the response (only in development environments for easier testing).
  2. User receives the code and enters it into the frontend application.
  3. Frontend calls /verification-services/email-verification/complete with the email and the received secretCode.
    • Mindbricks checks that the code is valid, not expired, and matches.
    • If valid, the user’s emailVerified flag is set to true, and a success response is returned.

API Endpoints

POST /verification-services/email-verification/start

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

Request Body

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

Success Response

Secret code details (in development environment). Confirms that the verification step has been started.

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

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

Error Responses


POST /verification-services/email-verification/complete

Purpose
Completes the email verification by validating the secret code.

Request Body

Parameter Type Required Description
email String Yes The user email being verified
secretCode String Yes The secret code received via email
{
  "email": "user@example.com",
  "secretCode": "123456"
}

Success Response

Returns confirmation that the email has been verified.

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

Error Responses


Important Behavioral Notes

Resend Throttling

You can only request a new verification code after a cooldown period (resendTimeWindow, e.g., 60 seconds).

Expiration Handling

Verification codes expire after a configured period (expireTimeWindow, e.g., 1 day).

One Code Per Session

Only one active verification session per user is allowed at a time.

💡 Mindbricks automatically manages spam prevention, session caching, expiration, and event broadcasting (start/complete events) for all verification steps.

Verification Services — Mobile Verification

Mobile verification is a two-step flow that ensures a user’s mobile number is verified and trusted by the system.

All verification services, including mobile verification, are located under the /verification-services base path.

When is Mobile Verification Triggered?

Mobile Verification Flow

  1. Frontend calls /verification-services/mobile-verification/start with the user’s email address (used to locate the user).
    • Mindbricks checks if the mobile number is already verified.
    • A secret code is generated and stored in the cache linked to the user.
    • The code is sent to the user’s mobile via SMS or returned in the response (only in development environments for easier testing).
  2. User receives the code and enters it into the frontend application.
  3. Frontend calls /verification-services/mobile-verification/complete with the email and the received secretCode.
    • Mindbricks checks that the code is valid, not expired, and matches.
    • If valid, the user’s mobileVerified flag is set to true, and a success response is returned.

API Endpoints

POST /verification-services/mobile-verification/start

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

Request Body

Parameter Type Required Description
email String Yes The email address associated with the mobile number to verify
{
  "email": "user@example.com"
}

Success Response
Secret code details (in development environment). Confirms that the verification step has been started.

{
  "userId": "user-uuid",
  "mobile": "+15551234567",
  "secretCode": "123456",
  "expireTime": 86400,
  "date": "2024-04-29T10:00:00.000Z"
}

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

Error Responses


POST /verification-services/mobile-verification/complete

Purpose:
Completes the mobile verification by validating the secret code.

Request Body

Parameter Type Required Description
email String Yes The user’s email being verified
secretCode String Yes The secret code received via SMS
{
  "email": "user@example.com",
  "secretCode": "123456"
}

Success Response
Returns confirmation that the mobile number has been verified.

{
  "userId": "user-uuid",
  "mobile": "+15551234567",
  "isVerified": true
}

Error Responses
403 Forbidden:


Important Behavioral Notes

Resend Throttling:
You can only request a new verification code after a cooldown period (resendTimeWindow, e.g., 60 seconds).

Expiration Handling:
Verification codes expire after a configured period (expireTimeWindow, e.g., 1 day).

One Code Per Session:
Only one active verification session per user is allowed at a time.

💡 Mindbricks automatically manages spam prevention, session caching, expiration, and event broadcasting (start/complete events) for all verification steps.

Verification Services — Email 2FA Verification

Email 2FA (Two-Factor Authentication) provides an additional layer of security by requiring users to confirm their identity using a secret code sent to their email address. This process is used in login flows or sensitive actions that need extra verification.

All verification services, including 2FA, are located under the /verification-services base path.

When is Email 2FA Triggered?

Email 2FA Flow

  1. Frontend calls /verification-services/email-2factor-verification/start with the user’s id, session id, client info, and reason.
    • Mindbricks identifies the user and checks if a cooldown period applies.
    • A new secret code is generated and stored, linked to the current session ID.
    • The code is sent via email or returned in development environments.
  2. User receives the code and enters it into the frontend application.
  3. Frontend calls /verification-services/email-2factor-verification/complete with the userId, sessionId, and the secretCode.
    • Mindbricks verifies the code, validates the session, and updates the session to remove the 2FA requirement.

API Endpoints

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

Purpose:
Starts the email-based 2FA process by generating and sending a verification code.

Request Body

Parameter Type Required Description
userId String Yes The user’s ID
sessionId String Yes The current session ID
client String No Optional client tag or context
reason String No Optional reason for triggering 2FA
{
  "userId": "user-uuid",
  "sessionId": "session-uuid",
  "client": "login-page",
  "reason": "Login requires email 2FA"
}

Success Response

{
  "sessionId": "session-uuid",
  "userId": "user-uuid",
  "email": "user@example.com",
  "secretCode": "123456",
  "expireTime": 300,
  "date": "2024-04-29T10:00:00.000Z"
}

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

Error Responses


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

Purpose:
Completes the email 2FA process by validating the secret code and session.

Request Body

Parameter Type Required Description
userId String Yes The user’s ID
sessionId String Yes The session ID the code is tied to
secretCode String Yes The secret code received via email
{
  "userId": "user-uuid",
  "sessionId": "session-uuid",
  "secretCode": "123456"
}

Success Response

Returns an updated session with 2FA disabled:

{
  "sessionId": "session-uuid",
  "userId": "user-uuid",
  "sessionNeedsEmail2FA": false,
  ...
}

Error Responses


Important Behavioral Notes

Verification Services — Mobile 2FA Verification

Mobile 2FA (Two-Factor Authentication) is a security mechanism that adds an extra layer of authentication using a user’s verified mobile number.

All verification services, including mobile 2FA, are accessible under the /verification-services base path.

When is Mobile 2FA Triggered?

Mobile 2FA Verification Flow

  1. Frontend calls /verification-services/mobile-2factor-verification/start with the user’s id, session id, client info, and reason.
    • Mindbricks finds the user by id.
    • Verifies that the user has a verified mobile number.
    • A secret code is generated and cached against the session.
    • The code is sent to the user’s verified mobile number or returned in the response (only in development environments).
  2. User receives the code and enters it in the frontend app.
  3. Frontend calls /verification-services/mobile-2factor-verification/complete with the userId, sessionId, and secretCode.
    • Mindbricks validates the code for expiration and correctness.
    • If valid, the session flag sessionNeedsMobile2FA is cleared.
    • A refreshed session object is returned.

API Endpoints

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

Purpose:
Initiates mobile-based 2FA by generating and sending a secret code.

Request Body

Parameter Type Required Description
userId String Yes The user’s ID
sessionId String Yes The current session ID
client String No Optional client tag or context
reason String No Optional reason for triggering 2FA
{
  "userId": "user-uuid",
  "sessionId": "session-uuid",
  "client": "login-page",
  "reason": "Login requires mobile 2FA"
}

Success Response
Returns the generated code (only in development), expiration info, and metadata.

{
  "userId": "user-uuid",
  "sessionId": "session-uuid",
  "mobile": "+15551234567",
  "secretCode": "654321",
  "expireTime": 300,
  "date": "2024-04-29T11:00:00.000Z"
}

⚠️ In production environments, the secret code is not included in the response and is instead delivered via SMS.

Error Responses


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

Purpose:
Completes mobile 2FA verification by validating the secret code and updating the session.

Request Body

Parameter Type Required Description
userId String Yes ID of the user
sessionId String Yes ID of the session
secretCode String Yes The 6-digit code received via SMS
{
  "userId": "user-uuid",
  "sessionId": "session-uuid",
  "secretCode": "654321"
}

Success Response
Returns the updated session with sessionNeedsMobile2FA: false.

{
  "sessionId": "session-uuid",
  "userId": "user-uuid",
  "sessionNeedsMobile2FA": false,
  "accessToken": "jwt-token",
  "expiresIn": 86400
}

Error Responses


Behavioral Notes

💡 Mindbricks handles session integrity, rate limiting, and secure code delivery to ensure a robust mobile 2FA process.

Verification Services — Password Reset by Email

Password Reset by Email enables a user to securely reset their password using a secret code sent to their registered email address.

All verification services, including password reset by email, are located under the /verification-services base path.

When is Password Reset by Email Triggered?

Password Reset Flow

  1. Frontend calls /verification-services/password-reset-by-email/start with the user’s email.
    • Mindbricks checks if the user exists and if the email is registered.
    • A secret code is generated and stored in the cache linked to the user.
    • The code is sent to the user’s email, or returned in the response (in development environments only for testing).
  2. User receives the code and enters it into the frontend along with the new password.
  3. Frontend calls /verification-services/password-reset-by-email/complete with the email, the secretCode, and the new password.
    • Mindbricks checks that the code is valid, not expired, and matches.
    • If valid, the user’s password is reset, their emailVerified flag is set to true, and a success response is returned.

API Endpoints

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

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

Request Body

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

Success Response

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

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

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

Error Responses


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

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

Request Body

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

Success Response

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

Error Responses


Important Behavioral Notes

Resend Throttling:

A new verification code can only be requested after a cooldown period (configured via resendTimeWindow, e.g., 60 seconds).

Expiration Handling:

Verification codes automatically expire after a predefined period (expireTimeWindow, e.g., 1 day).

Session & Event Handling:

Mindbricks manages:

Verification Services — Password Reset by Mobile

Password reset by mobile provides users with a secure mechanism to reset their password using a verification code sent via SMS to their registered mobile number.

All verification services, including password reset by mobile, are located under the /verification-services base path.

When is Password Reset by Mobile Triggered?

Password Reset by Mobile Flow

  1. Frontend calls /verification-services/password-reset-by-mobile/start with the user’s mobile number or associated identifier.
    • Mindbricks checks if a user with the given mobile exists.
    • A secret code is generated and stored in the cache for that user.
    • The code is sent to the user’s mobile (or returned in development environments for testing).
  2. User receives the code via SMS and enters it into the frontend app.
  3. Frontend calls /verification-services/password-reset-by-mobile/complete with the user’s email, the secretCode, and the new password.
    • Mindbricks validates the secret code and its expiration.
    • If valid, it updates the user’s password and returns a success response.

API Endpoints

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

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

Request Body

Parameter Type Required Description
mobile String Yes The mobile number to verify
{
  "mobile": "+905551234567"
}

Success Response

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

{
  "userId": "user-uuid",
  "mobile": "+905551234567",
  "secretCode": "123456", 
  "expireTime": 86400,
  "date": "2024-04-29T10:00:00.000Z"
}

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

Error Responses


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

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

Request Body

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

Success Response

{
  "userId": "user-uuid",
  "mobile": "+905551234567",
  "isVerified": true
}

Important Behavioral Notes

💡 Mindbricks handles spam protection, session caching, and event-based logging (for both start and complete operations) as part of the verification service base class.

Verification Method Types

🧾 For byCode Verifications

This verification type requires the user to manually enter a 6-digit code.

Frontend Action:
Display a secure input page where the user can enter the code they received via email or SMS. After collecting the code and any required metadata (such as userId or sessionId), make a POST request to the corresponding /complete endpoint.


🔗 For byLink Verifications

This verification type uses a clickable link embedded in an email (or SMS message).

Frontend Action:
The link points to a GET page in your frontend that parses userId and code from the query string and sends them to the backend via a POST request to the corresponding /complete endpoint. This enables one-click verification without requiring the user to type in a code.

Common Routes

Route: currentuser

Route Definition: Retrieves the currently authenticated user’s session information.

Route Type: sessionInfo

Access Route: GET /currentuser

Parameters

This route does not require any request parameters.

Behavior

// Sample GET /currentuser call
axios.get("/currentuser", {
  headers: {
    "Authorization": "Bearer your-jwt-token"
  }
});

Success Response Returns the session object, including user-related data and token information.

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

Error Response 401 Unauthorized: No active session found.

{
  "status": "ERR",
  "message": "No login found"
}

Notes

Route: permissions

*Route Definition*: Retrieves all effective permission records assigned to the currently authenticated user.

*Route Type*: permissionFetch

Access Route: GET /permissions

Parameters

This route does not require any request parameters.

Behavior

// Sample GET /permissions call
axios.get("/permissions", {
  headers: {
    "Authorization": "Bearer your-jwt-token"
  }
});

Success Response

Returns an array of permission objects.

[
  {
    "id": "perm1",
    "permissionName": "adminPanel.access",
    "roleId": "admin",
    "subjectUserId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38",
    "subjectUserGroupId": null,
    "objectId": null,
    "canDo": true,
    "tenantCodename": "store123"
  },
  {
    "id": "perm2",
    "permissionName": "orders.manage",
    "roleId": null,
    "subjectUserId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38",
    "subjectUserGroupId": null,
    "objectId": null,
    "canDo": true,
    "tenantCodename": "store123"
  }
]

Each object reflects a single permission grant, aligned with the givenPermissions model:

Error Responses

{
  "status": "ERR",
  "message": "No login found"
}

Notes

Tip: Applications can cache permission results client-side or server-side, but should occasionally refresh by calling this endpoint, especially after login or permission-changing operations.

Route: permissions/:permissionName

Route Definition: Checks whether the current user has access to a specific permission, and provides a list of scoped object exceptions or inclusions.

Route Type: permissionScopeCheck

Access Route: GET /permissions/:permissionName

Parameters

Parameter Type Required Population
permissionName String Yes request.params.permissionName

Behavior

// Sample GET /permissions/orders.manage
axios.get("/permissions/orders.manage", {
  headers: {
    "Authorization": "Bearer your-jwt-token"
  }
});

Success Response

{
  "canDo": true,
  "exceptions": [
    "a1f2e3d4-xxxx-yyyy-zzzz-object1",
    "b2c3d4e5-xxxx-yyyy-zzzz-object2"
  ]
}

Copyright

All sources, documents and other digital materials are copyright of .

About Us

For more information please visit our website: .

. .


EVENT GUIDE

EVENT GUIDE

wechess-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: wechess-auth-service-dbevent-user-created

This event is triggered upon the creation of a user data object in the database. The event payload encompasses the newly created data, encapsulated within the root of the paylod.

Event payload:

{"id":"ID","email":"String","password":"String","fullname":"String","avatar":"String","roleId":"String","emailVerified":"Boolean","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

DbEvent user-updated

Event topic: wechess-auth-service-dbevent-user-updated

Activation of this event follows the update of a user data object. The payload contains the updated information under the user attribute, along with the original data prior to update, labeled as old_user and also you can find the old and new versions of updated-only portion of the data…

Event payload:

{
old_user:{"id":"ID","email":"String","password":"String","fullname":"String","avatar":"String","roleId":"String","emailVerified":"Boolean","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},
user:{"id":"ID","email":"String","password":"String","fullname":"String","avatar":"String","roleId":"String","emailVerified":"Boolean","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},
oldDataValues,
newDataValues
}

DbEvent user-deleted

Event topic: wechess-auth-service-dbevent-user-deleted

This event announces the deletion of a user data object, covering both hard deletions (permanent removal) and soft deletions (where the isActive attribute is set to false). Regardless of the deletion type, the event payload will present the data as it was immediately before deletion, highlighting an isActive status of false for soft deletions.

Event payload:

{"id":"ID","email":"String","password":"String","fullname":"String","avatar":"String","roleId":"String","emailVerified":"Boolean","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

DbEvent userAvatarsFile-created

Event topic: wechess-auth-service-dbevent-useravatarsfile-created

This event is triggered upon the creation of a userAvatarsFile data object in the database. The event payload encompasses the newly created data, encapsulated within the root of the paylod.

Event payload:

{"id":"ID","fileName":"String","mimeType":"String","fileSize":"Integer","accessKey":"String","ownerId":"ID","fileData":"Blob","metadata":"Object","userId":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

DbEvent userAvatarsFile-updated

Event topic: wechess-auth-service-dbevent-useravatarsfile-updated

Activation of this event follows the update of a userAvatarsFile data object. The payload contains the updated information under the userAvatarsFile attribute, along with the original data prior to update, labeled as old_userAvatarsFile and also you can find the old and new versions of updated-only portion of the data…

Event payload:

{
old_userAvatarsFile:{"id":"ID","fileName":"String","mimeType":"String","fileSize":"Integer","accessKey":"String","ownerId":"ID","fileData":"Blob","metadata":"Object","userId":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},
userAvatarsFile:{"id":"ID","fileName":"String","mimeType":"String","fileSize":"Integer","accessKey":"String","ownerId":"ID","fileData":"Blob","metadata":"Object","userId":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},
oldDataValues,
newDataValues
}

DbEvent userAvatarsFile-deleted

Event topic: wechess-auth-service-dbevent-useravatarsfile-deleted

This event announces the deletion of a userAvatarsFile data object, covering both hard deletions (permanent removal) and soft deletions (where the isActive attribute is set to false). Regardless of the deletion type, the event payload will present the data as it was immediately before deletion, highlighting an isActive status of false for soft deletions.

Event payload:

{"id":"ID","fileName":"String","mimeType":"String","fileSize":"Integer","accessKey":"String","ownerId":"ID","fileData":"Blob","metadata":"Object","userId":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":false}

ElasticSearch Index Events

Within the Auth service, most data objects are mirrored in ElasticSearch indices, ensuring these indices remain syncronized with their database counterparts through creation, updates, and deletions. These indices serve dual purposes: they act as a data source for external services and furnish aggregated data tailored to enhance frontend user experiences. Consequently, an ElasticSearch index might encapsulate data in its original form or aggregate additional information from other data objects.

These aggregations can include both one-to-one and one-to-many relationships not only with database objects within the same service but also across different services. This capability allows developers to access comprehensive, aggregated data efficiently. By subscribing to ElasticSearch index events, developers are notified when an index is updated and can directly obtain the aggregated entity within the event payload, bypassing the need for separate ElasticSearch queries.

It’s noteworthy that some services may augment another service’s index by appending to the entity’s extends object. In such scenarios, an *-extended event will contain only the newly added data. Should you require the complete dataset, you would need to retrieve the full ElasticSearch index entity using the provided ID.

This approach to indexing and event handling facilitates a modular, interconnected architecture where services can seamlessly integrate and react to changes, enriching the overall data ecosystem and enabling more dynamic, responsive applications.

Index Event user-created

Event topic: elastic-index-wechess_user-created

Event payload:

{"id":"ID","email":"String","password":"String","fullname":"String","avatar":"String","roleId":"String","emailVerified":"Boolean","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event user-updated

Event topic: elastic-index-wechess_user-created

Event payload:

{"id":"ID","email":"String","password":"String","fullname":"String","avatar":"String","roleId":"String","emailVerified":"Boolean","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event user-deleted

Event topic: elastic-index-wechess_user-deleted

Event payload:

{"id":"ID","email":"String","password":"String","fullname":"String","avatar":"String","roleId":"String","emailVerified":"Boolean","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event user-extended

Event topic: elastic-index-wechess_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 : wechess-auth-service-user-retrived

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the user data object itself.

The following JSON included in the payload illustrates the fullest representation of the user object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

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

Route Event user-updated

Event topic : wechess-auth-service-user-updated

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the user data object itself.

The following JSON included in the payload illustrates the fullest representation of the user object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

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

Route Event profile-updated

Event topic : wechess-auth-service-profile-updated

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the user data object itself.

The following JSON included in the payload illustrates the fullest representation of the user object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

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

Route Event user-created

Event topic : wechess-auth-service-user-created

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the user data object itself.

The following JSON included in the payload illustrates the fullest representation of the user object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

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

Route Event user-deleted

Event topic : wechess-auth-service-user-deleted

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the user data object itself.

The following JSON included in the payload illustrates the fullest representation of the user object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

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

Route Event profile-archived

Event topic : wechess-auth-service-profile-archived

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the user data object itself.

The following JSON included in the payload illustrates the fullest representation of the user object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

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

Route Event users-listed

Event topic : wechess-auth-service-users-listed

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the users data object itself.

The following JSON included in the payload illustrates the fullest representation of the users object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"users","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","users":[{"id":"ID","email":"String","password":"String","fullname":"String","avatar":"String","roleId":"String","emailVerified":"Boolean","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 : wechess-auth-service-users-searched

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the users data object itself.

The following JSON included in the payload illustrates the fullest representation of the users object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"users","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","users":[{"id":"ID","email":"String","password":"String","fullname":"String","avatar":"String","roleId":"String","emailVerified":"Boolean","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 : wechess-auth-service-userrole-updated

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the user data object itself.

The following JSON included in the payload illustrates the fullest representation of the user object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

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

Route Event userpassword-updated

Event topic : wechess-auth-service-userpassword-updated

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the user data object itself.

The following JSON included in the payload illustrates the fullest representation of the user object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

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

Route Event userpasswordbyadmin-updated

Event topic : wechess-auth-service-userpasswordbyadmin-updated

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the user data object itself.

The following JSON included in the payload illustrates the fullest representation of the user object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

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

Route Event briefuser-retrived

Event topic : wechess-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 : wechess-auth-service-user-registered

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the user data object itself.

The following JSON included in the payload illustrates the fullest representation of the user object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

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

Route Event useravatarsfile-retrived

Event topic : wechess-auth-service-useravatarsfile-retrived

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the userAvatarsFile data object itself.

The following JSON included in the payload illustrates the fullest representation of the userAvatarsFile object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"userAvatarsFile","method":"GET","action":"get","appVersion":"Version","rowCount":1,"userAvatarsFile":{"id":"ID","fileName":"String","mimeType":"String","fileSize":"Integer","accessKey":"String","ownerId":"ID","fileData":"Blob","metadata":"Object","userId":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true}}

Route Event useravatarsfiles-listed

Event topic : wechess-auth-service-useravatarsfiles-listed

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the userAvatarsFiles data object itself.

The following JSON included in the payload illustrates the fullest representation of the userAvatarsFiles object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"userAvatarsFiles","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","userAvatarsFiles":[{"id":"ID","fileName":"String","mimeType":"String","fileSize":"Integer","accessKey":"String","ownerId":"ID","fileData":"Blob","metadata":"Object","userId":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]}

Route Event useravatarsfile-deleted

Event topic : wechess-auth-service-useravatarsfile-deleted

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the userAvatarsFile data object itself.

The following JSON included in the payload illustrates the fullest representation of the userAvatarsFile object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"userAvatarsFile","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"userAvatarsFile":{"id":"ID","fileName":"String","mimeType":"String","fileSize":"Integer","accessKey":"String","ownerId":"ID","fileData":"Blob","metadata":"Object","userId":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":false}}

Index Event useravatarsfile-created

Event topic: elastic-index-wechess_useravatarsfile-created

Event payload:

{"id":"ID","fileName":"String","mimeType":"String","fileSize":"Integer","accessKey":"String","ownerId":"ID","fileData":"Blob","metadata":"Object","userId":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event useravatarsfile-updated

Event topic: elastic-index-wechess_useravatarsfile-created

Event payload:

{"id":"ID","fileName":"String","mimeType":"String","fileSize":"Integer","accessKey":"String","ownerId":"ID","fileData":"Blob","metadata":"Object","userId":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event useravatarsfile-deleted

Event topic: elastic-index-wechess_useravatarsfile-deleted

Event payload:

{"id":"ID","fileName":"String","mimeType":"String","fileSize":"Integer","accessKey":"String","ownerId":"ID","fileData":"Blob","metadata":"Object","userId":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event useravatarsfile-extended

Event topic: elastic-index-wechess_useravatarsfile-extended

Event payload:

{
  id: id,
  extends: {
    [extendName]: "Object",
    [extendName + "_count"]: "Number",
  },
}

Route Events

Route events are emitted following the successful execution of a route. While most routes perform CRUD (Create, Read, Update, Delete) operations on data objects, resulting in route events that closely resemble database events, there are distinctions worth noting. A single route execution might trigger multiple CRUD actions and ElasticSearch indexing operations. However, for those primarily concerned with the overarching business logic and its outcomes, listening to the consolidated route event, published once at the conclusion of the route’s execution, is more pertinent.

Moreover, routes often deliver aggregated data beyond the primary database object, catering to specific client needs. For instance, creating a data object via a route might not only return the entity’s data but also route-specific metrics, such as the executing user’s permissions related to the entity. Alternatively, a route might automatically generate default child entities following the creation of a parent object. Consequently, the route event encapsulates a unified dataset encompassing both the parent and its children, in contrast to individual events triggered for each entity created. Therefore, subscribing to route events can offer a richer, more contextually relevant set of information aligned with business logic.

The payload of a route event mirrors the REST response JSON of the route, providing a direct and comprehensive reflection of the data and metadata communicated to the client. This ensures that subscribers to route events receive a payload that encapsulates both the primary data involved and any additional information deemed significant at the business level, facilitating a deeper understanding and integration of the service’s functional outcomes.

Route Event user-retrived

Event topic : wechess-auth-service-user-retrived

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the user data object itself.

The following JSON included in the payload illustrates the fullest representation of the user object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

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

Route Event user-updated

Event topic : wechess-auth-service-user-updated

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the user data object itself.

The following JSON included in the payload illustrates the fullest representation of the user object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

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

Route Event profile-updated

Event topic : wechess-auth-service-profile-updated

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the user data object itself.

The following JSON included in the payload illustrates the fullest representation of the user object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

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

Route Event user-created

Event topic : wechess-auth-service-user-created

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the user data object itself.

The following JSON included in the payload illustrates the fullest representation of the user object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

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

Route Event user-deleted

Event topic : wechess-auth-service-user-deleted

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the user data object itself.

The following JSON included in the payload illustrates the fullest representation of the user object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

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

Route Event profile-archived

Event topic : wechess-auth-service-profile-archived

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the user data object itself.

The following JSON included in the payload illustrates the fullest representation of the user object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

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

Route Event users-listed

Event topic : wechess-auth-service-users-listed

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the users data object itself.

The following JSON included in the payload illustrates the fullest representation of the users object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"users","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","users":[{"id":"ID","email":"String","password":"String","fullname":"String","avatar":"String","roleId":"String","emailVerified":"Boolean","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 : wechess-auth-service-users-searched

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the users data object itself.

The following JSON included in the payload illustrates the fullest representation of the users object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"users","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","users":[{"id":"ID","email":"String","password":"String","fullname":"String","avatar":"String","roleId":"String","emailVerified":"Boolean","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 : wechess-auth-service-userrole-updated

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the user data object itself.

The following JSON included in the payload illustrates the fullest representation of the user object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

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

Route Event userpassword-updated

Event topic : wechess-auth-service-userpassword-updated

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the user data object itself.

The following JSON included in the payload illustrates the fullest representation of the user object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

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

Route Event userpasswordbyadmin-updated

Event topic : wechess-auth-service-userpasswordbyadmin-updated

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the user data object itself.

The following JSON included in the payload illustrates the fullest representation of the user object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

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

Route Event briefuser-retrived

Event topic : wechess-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 : wechess-auth-service-user-registered

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the user data object itself.

The following JSON included in the payload illustrates the fullest representation of the user object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

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

Route Event useravatarsfile-retrived

Event topic : wechess-auth-service-useravatarsfile-retrived

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the userAvatarsFile data object itself.

The following JSON included in the payload illustrates the fullest representation of the userAvatarsFile object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"userAvatarsFile","method":"GET","action":"get","appVersion":"Version","rowCount":1,"userAvatarsFile":{"id":"ID","fileName":"String","mimeType":"String","fileSize":"Integer","accessKey":"String","ownerId":"ID","fileData":"Blob","metadata":"Object","userId":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true}}

Route Event useravatarsfiles-listed

Event topic : wechess-auth-service-useravatarsfiles-listed

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the userAvatarsFiles data object itself.

The following JSON included in the payload illustrates the fullest representation of the userAvatarsFiles object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"userAvatarsFiles","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","userAvatarsFiles":[{"id":"ID","fileName":"String","mimeType":"String","fileSize":"Integer","accessKey":"String","ownerId":"ID","fileData":"Blob","metadata":"Object","userId":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]}

Route Event useravatarsfile-deleted

Event topic : wechess-auth-service-useravatarsfile-deleted

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the userAvatarsFile data object itself.

The following JSON included in the payload illustrates the fullest representation of the userAvatarsFile object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"userAvatarsFile","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"userAvatarsFile":{"id":"ID","fileName":"String","mimeType":"String","fileSize":"Integer","accessKey":"String","ownerId":"ID","fileData":"Blob","metadata":"Object","userId":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":false}}

Copyright

All sources, documents and other digital materials are copyright of .

About Us

For more information please visit our website: .

. .


Data Objects

Service Design Specification - Object Design for user

Service Design Specification - Object Design for user

wechess-auth-service documentation

Document Overview

This document outlines the object design for the user model in our application. It includes details about the model’s attributes, relationships, and any specific validation or business logic that applies.

user Data Object

Object Overview

Description: A data object that stores the user information and handles login settings.

This object represents a core data structure within the service and acts as the blueprint for database interaction, API generation, and business logic enforcement. It is defined using the ObjectSettings pattern, which governs its behavior, access control, caching strategy, and integration points with other systems such as Stripe and Redis.

Core Configuration

Redis Entity Caching

This data object is configured for Redis entity caching, which improves data retrieval performance by storing frequently accessed data in Redis. Each time a new instance is created, updated or deleted, the cache is updated accordingly. Any get requests by id will first check the cache before querying the database. If you want to use the cache by other select criteria, you can configure any data property as a Redis cluster.

Properties Schema

Property Type Required Description
email String Yes A string value to represent the user's email.
password String Yes A string value to represent the user's password. It will be stored as hashed.
fullname String Yes A string value to represent the fullname of the user
avatar String No The avatar url of the user. A random avatar will be generated if not provided
roleId String Yes A string value to represent the roleId of the user.
emailVerified Boolean Yes A boolean value to represent the email verification status of the user.

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

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.

Elastic Search Indexing

email fullname roleId emailVerified

Properties that are indexed in Elastic Search will be searchable via the Elastic Search API. While all properties are stored in the elastic search index of the data object, only those marked for Elastic Search indexing will be available for search queries.

Database Indexing

email

Properties that are indexed in the database will be optimized for query performance, allowing for faster data retrieval. Make a property indexed in the database if you want to use it frequently in query filters or sorting.

Unique Properties

email

Unique properties are enforced to have distinct values across all instances of the data object, preventing duplicate entries. Note that a unique property is automatically indexed in the database so you will not need to set the Indexed in DB option.

Cache Select Properties

email

Cache select properties are used to collect data from Redis entity cache with a different key than the data object id. This allows you to cache data that is not directly related to the data object id, but a frequently used filter.

Secondary Key Properties

email

Secondary key properties are used to create an additional indexed identifiers for the data object, allowing for alternative access patterns. Different than normal indexed properties, secondary keys will act as primary keys and Mindbricks will provide automatic secondary key db utility functions to access the data object by the secondary key.

Filter Properties

email fullname roleId

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


Service Design Specification - Object Design for userAvatarsFile

Service Design Specification - Object Design for userAvatarsFile

wechess-auth-service documentation

Document Overview

This document outlines the object design for the userAvatarsFile model in our application. It includes details about the model’s attributes, relationships, and any specific validation or business logic that applies.

userAvatarsFile Data Object

Object Overview

Description: Auto-generated file storage for the userAvatars database bucket. Files are stored as BYTEA in PostgreSQL.

This object represents a core data structure within the service and acts as the blueprint for database interaction, API generation, and business logic enforcement. It is defined using the ObjectSettings pattern, which governs its behavior, access control, caching strategy, and integration points with other systems such as Stripe and Redis.

Core Configuration

Properties Schema

Property Type Required Description
fileName String Yes Original file name as uploaded by the client.
mimeType String Yes MIME type of the uploaded file (e.g., image/png, application/pdf).
fileSize Integer Yes File size in bytes.
accessKey String Yes 12-character random key for shareable access. Auto-generated on upload.
ownerId ID No ID of the user who uploaded the file (from session).
fileData Blob Yes Binary file content. Stored as BYTEA in PostgreSQL or Buffer in MongoDB.
metadata Object No Optional JSON metadata for the file (tags, alt text, etc.).
userId ID No Reference to the owner user record.

Default Values

Default values are automatically assigned to properties when a new object is created, if no value is provided in the request body. Since default values are applied on db level, they should be literal values, not expressions.If you want to use expressions, you can use transposed parameters in any business API to set default values dynamically.

Constant Properties

fileName mimeType fileSize accessKey ownerId fileData userId

Constant properties are defined to be immutable after creation, meaning they cannot be updated or changed once set. They are typically used for properties that should remain constant throughout the object’s lifecycle. A property is set to be constant if the Allow Update option is set to false.

Auto Update Properties

fileName mimeType fileSize accessKey ownerId fileData metadata userId

An update crud API created with the option Auto Params enabled will automatically update these properties with the provided values in the request body. If you want to update any property in your own business logic not by user input, you can set the Allow Auto Update option to false. These properties will be added to the update API’s body parameters and can be updated by the user if any value is provided in the request body.

Elastic Search Indexing

fileName mimeType fileSize ownerId userId

Properties that are indexed in Elastic Search will be searchable via the Elastic Search API. While all properties are stored in the elastic search index of the data object, only those marked for Elastic Search indexing will be available for search queries.

Database Indexing

fileName mimeType accessKey ownerId userId

Properties that are indexed in the database will be optimized for query performance, allowing for faster data retrieval. Make a property indexed in the database if you want to use it frequently in query filters or sorting.

Unique Properties

accessKey

Unique properties are enforced to have distinct values across all instances of the data object, preventing duplicate entries. Note that a unique property is automatically indexed in the database so you will not need to set the Indexed in DB option.

Session Data Properties

ownerId

Session data properties are used to store data that is specific to the user session, allowing for personalized experiences and temporary data storage. If a property is configured as session data, it will be automatically mapped to the related field in the user session during CRUD operations. Note that session data properties can not be mutated by the user, but only by the system.

This property is also used to store the owner of the session data, allowing for ownership checks and access control.

Filter Properties

mimeType ownerId userId

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


Business APIs

Business API Design Specification - Get User

Business API Design Specification - Get User

A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic.

While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized.

This document provides an in-depth explanation of the architectural design of the getUser Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side.

Main Data Object and CRUD Operation

The getUser Business API is designed to handle a get operation on the User data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

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

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The getUser Business API includes a REST controller that can be triggered via the following route:

/v1/users/:userId

By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the Parameters section.

gRPC Controller

The getUser Business API includes a gRPC controller that can be triggered via the following function:

getUser()

By calling this gRPC endpoint using a gRPC client, you can execute the Business API. Note that all parameters must be provided as function arguments, regardless of their HTTP location configuration, which is relevant only for the REST controller.

MCP Tool

REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This getUser Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The getUser Business API has 1 parameter that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client.

Business API parameters can be:

Regular Parameters

Name Type Required Default Location Data Path
userId ID Yes - urlpath userId
Description: This id paremeter is used to query the required data object.

Parameter Transformations

Some parameters are post-processed using transform scripts after being read from the request but before validation or workflow execution. Only parameters with a transform script are listed below.

No parameters are transformed in this API.

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the getUser Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Select Clause

Specifies which fields will be selected from the main data object during a get or list operation. Leave blank to select all properties. This applies only to get and list type APIs.",

``

Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({$and:[{id:this.userId},{isActive:true}]}), {"path":"services[0].businessLogic[0].whereClause.fullWhereClause"})

Get Options

Use these options to set get specific settings.

setAsRead: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed.

No setAsread field-value pair is configured.

Business Logic Workflow

[1] Step : startBusinessApi

Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Extracts parameters from request and Redis, applies defaults, and writes them to context.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Executes parameter transformation scripts, applies type coercion, merges derived values, and reshapes inputs for downstream milestones.


[4] Step : checkParameters

Validates required and custom parameters, enforcing business-specific rules and constraints.


[5] Step : checkBasicAuth

Performs login, role, and permission checks, and applies dynamic object-level access rules.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildWhereClause

Builds the WHERE clause for fetching the object and applies additional scoped filters if configured.

You can use the following settings to change some behavior of this step. whereClause

[7] Step : mainGetOperation

Executes the database fetch, retrieves the object, and stores it in context for enrichment or further checks.

You can use the following settings to change some behavior of this step. selectClause, getOptions

[8] Action : emitUserLoaded

Action Type: EmitSseEventAction

class Api {
  async emitUserLoaded() {
    const eventData = runMScript(
      () => ({
        userId: this.user?.id,
        fullname: this.user?.fullname,
        email: this.user?.email,
      }),
      {
        path: "services[0].businessLogic[0].actions.emitSseEventActions[0].data",
      },
    );
    await this.emitProgress(
      "userLoaded",
      typeof eventData === "string" ? eventData : "",
      typeof eventData === "object" ? eventData : {},
    );
  }
}

[9] Action : simulateEnrichment

Action Type: FunctionCallAction

class Api {
  async simulateEnrichment() {
    try {
      return await runMScript(
        () => (async () => await new Promise((r) => setTimeout(r, 50)))(),
        {
          path: "services[0].businessLogic[0].actions.functionCallActions[0].callScript",
        },
      );
    } catch (err) {
      console.error("Error in FunctionCallAction simulateEnrichment:", err);
      throw err;
    }
  }
}

[10] Step : checkInstance

Performs instance-level validations, such as ownership, existence, or access conditions.


[11] Step : buildOutput

Assembles the response from the object, applies masking, formatting, and injects additional metadata if needed.


[12] Step : sendResponse

Delivers the response to the controller for client delivery.


[13] Step : raiseApiEvent

Triggers optional API-level events after workflow completion, sending messages to integrations like Kafka if configured.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The getUser api has got 1 regular client parameter

Parameter Type Required Population
userId ID true request.params?.[“userId”]

REST Request

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

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

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the user object in the respones. However, some properties may be omitted based on the object’s internal logic.

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "user",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"user": {
		"id": "ID",
		"email": "String",
		"password": "String",
		"fullname": "String",
		"avatar": "String",
		"roleId": "String",
		"emailVerified": "Boolean",
		"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 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
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

Parameter Transformations

Some parameters are post-processed using transform scripts after being read from the request but before validation or workflow execution. Only parameters with a transform script are listed below.

No parameters are transformed in this API.

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the updateUser Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({$and:[{id:this.userId},{isActive:true}]}), {"path":"services[0].businessLogic[1].whereClause.fullWhereClause"})

Data Clause

Defines custom field-value assignments used to modify or augment the default payload for create and update operations. These settings override values derived from the session or parameters if explicitly provided.", Note that a default data clause is always prepared by Mindbricks using data property settings, however any property in the data clause can be override by Data Clause Settings.

An update data clause populates all update-allowed properties of a data object, however the null properties (that are not provided by client) are ignored in db layer.

Custom Data Clause Override No custom data clause override configured

Actual Data Clause

The business api will use the following data clause. Note that any calculated value will be added to the data clause in the api manager.

{
  fullname: this.fullname,
  avatar: this.avatar,
}

Business Logic Workflow

[1] Step : startBusinessApi

Manager initializes context, prepares request and session objects, and sets up internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Manager reads parameters from the request or Redis, applies defaults, and writes them into context for downstream milestones.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Manager executes parameter transform scripts and derives any helper values or reshaped payloads into the context.


[4] Step : checkParameters

Manager validates required parameters, checks ID formats (UUID/ObjectId), and ensures all preconditions for update are met.


[5] Step : checkBasicAuth

Manager performs login verification, role, and permission checks, enforcing tenant and access rules before update.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildWhereClause

Manager constructs the WHERE clause used to identify the record to update, applying ownership and parent checks if necessary.

You can use the following settings to change some behavior of this step. whereClause

[7] Step : fetchInstance

Manager fetches the existing record from the database and writes it to the context for validation or enrichment.


[8] Action : setRolesOrder

Action Type: CreateObjectAction

Sets the hiyerarchy of the roles to check user permissions on other users

class Api {
  async setRolesOrder() {
    // Construct base object
    const obj = {};

    // Merge dynamic object
    Object.assign(
      obj,
      runMScript(
        () => ({
          superAdmin: 20,
          saasAdmin: 19,
          admin: 18,
          tenantOwner: 17,
          tenantAdmin: 16,
          saasUser: 15,
          tenantUser: 14,
          user: 13,
        }),
        {
          path: "services[0].businessLogic[1].actions.createObjectActions[0].mergeObject",
        },
      ),
    );

    return obj;
  }
}

[9] Action : protectHigherRole

Action Type: ValidationAction

Prevents the update of a higher or equal user role if not themselves

class Api {
  async protectHigherRole() {
    const isValid = runMScript(
      () =>
        (this._r[this.session.roleId] ?? 0) > (this._r[this.user.roleId] ?? 0),
      {
        path: "services[0].businessLogic[1].actions.validationActions[0].validationScript",
      },
    );

    if (!isValid) {
      throw new BadRequestError("AHigherUserRoleCantBeChanged");
    }
    return isValid;
  }
}

[10] Step : checkInstance

Manager performs instance-level validations, including ownership, existence, lock status, or other pre-update checks.


[11] Step : buildDataClause

Manager prepares the data clause for the update, applying transformations or enhancements before persisting.

You can use the following settings to change some behavior of this step. dataClause

[12] Step : mainUpdateOperation

Manager executes the update operation with the WHERE and data clauses. Database-level events are raised if configured.


[13] Step : buildOutput

Manager assembles the response object from the update result, masking fields or injecting additional metadata.


[14] Step : sendResponse

Manager sends the response back to the controller for delivery to the client.


[15] Step : raiseApiEvent

Manager triggers API-level events, sending relevant messages to Kafka or other integrations if configured.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The updateUser api has got 3 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”]

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",  
    
    },
    params: {
    
        }
  });

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the user object in the respones. However, some properties may be omitted based on the object’s internal logic.

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "user",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"user": {
		"id": "ID",
		"email": "String",
		"password": "String",
		"fullname": "String",
		"avatar": "String",
		"roleId": "String",
		"emailVerified": "Boolean",
		"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 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
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

Parameter Transformations

Some parameters are post-processed using transform scripts after being read from the request but before validation or workflow execution. Only parameters with a transform script are listed below.

No parameters are transformed in this API.

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the updateProfile Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({$and:[{id:this.userId},{isActive:true}]}), {"path":"services[0].businessLogic[2].whereClause.fullWhereClause"})

Data Clause

Defines custom field-value assignments used to modify or augment the default payload for create and update operations. These settings override values derived from the session or parameters if explicitly provided.", Note that a default data clause is always prepared by Mindbricks using data property settings, however any property in the data clause can be override by Data Clause Settings.

An update data clause populates all update-allowed properties of a data object, however the null properties (that are not provided by client) are ignored in db layer.

Custom Data Clause Override No custom data clause override configured

Actual Data Clause

The business api will use the following data clause. Note that any calculated value will be added to the data clause in the api manager.

{
  fullname: this.fullname,
  avatar: this.avatar,
}

Business Logic Workflow

[1] Step : startBusinessApi

Manager initializes context, prepares request and session objects, and sets up internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Manager reads parameters from the request or Redis, applies defaults, and writes them into context for downstream milestones.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Manager executes parameter transform scripts and derives any helper values or reshaped payloads into the context.


[4] Step : checkParameters

Manager validates required parameters, checks ID formats (UUID/ObjectId), and ensures all preconditions for update are met.


[5] Step : checkBasicAuth

Manager performs login verification, role, and permission checks, enforcing tenant and access rules before update.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildWhereClause

Manager constructs the WHERE clause used to identify the record to update, applying ownership and parent checks if necessary.

You can use the following settings to change some behavior of this step. whereClause

[7] Step : fetchInstance

Manager fetches the existing record from the database and writes it to the context for validation or enrichment.


[8] Step : checkInstance

Manager performs instance-level validations, including ownership, existence, lock status, or other pre-update checks.


[9] Step : buildDataClause

Manager prepares the data clause for the update, applying transformations or enhancements before persisting.

You can use the following settings to change some behavior of this step. dataClause

[10] Step : mainUpdateOperation

Manager executes the update operation with the WHERE and data clauses. Database-level events are raised if configured.


[11] Step : buildOutput

Manager assembles the response object from the update result, masking fields or injecting additional metadata.


[12] Step : sendResponse

Manager sends the response back to the controller for delivery to the client.


[13] Step : raiseApiEvent

Manager triggers API-level events, sending relevant messages to Kafka or other integrations if configured.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The updateProfile api has got 3 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”]

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",  
    
    },
    params: {
    
        }
  });

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the user object in the respones. However, some properties may be omitted based on the object’s internal logic.

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

Business API Design Specification - Create User

Business API Design Specification - Create User

A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic.

While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized.

This document provides an in-depth explanation of the architectural design of the createUser Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side.

Main Data Object and CRUD Operation

The createUser Business API is designed to handle a create operation on the User data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

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

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The createUser Business API includes a REST controller that can be triggered via the following route:

/v1/users

By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the Parameters section.

gRPC Controller

The createUser Business API includes a gRPC controller that can be triggered via the following function:

createUser()

By calling this gRPC endpoint using a gRPC client, you can execute the Business API. Note that all parameters must be provided as function arguments, regardless of their HTTP location configuration, which is relevant only for the REST controller.

MCP Tool

REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This createUser Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The createUser Business API has 5 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client.

Business API parameters can be:

Regular Parameters

Name Type Required Default Location Data Path
userId ID No - body userId
Description: This id paremeter is used to create the data object with a given specific id. Leave null for automatic id.
avatar String No - body avatar
Description: The avatar url of the user. If not sent, a default random one will be generated.
email String Yes - body email
Description: A string value to represent the user’s email.
password String Yes - body password
Description: A string value to represent the user’s password. It will be stored as hashed.
fullname String Yes - body fullname
Description: A string value to represent the fullname of the user

Parameter Transformations

Some parameters are post-processed using transform scripts after being read from the request but before validation or workflow execution. Only parameters with a transform script are listed below.

this.avatar = 
  runMScript(() => (this.avatar ? `https://gravatar.com/avatar/${LIB.common.md5(this.email ?? 'nullValue')}?s=200&d=identicon` : null), {"path":"services[0].businessLogic[3].customParameters[0].transform"})

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the createUser Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Data Clause

Defines custom field-value assignments used to modify or augment the default payload for create and update operations. These settings override values derived from the session or parameters if explicitly provided.", Note that a default data clause is always prepared by Mindbricks using data property settings, however any property in the data clause can be override by Data Clause Settings.

Custom Data Clause Override No custom data clause override configured

Actual Data Clause

The business api will use the following data clause. Note that any calculated value will be added to the data clause in the api manager.

{
  id: this.userId,
  email: this.email,
  password: this.hashString(this.password),
  fullname: this.fullname,
  avatar: this.avatar,
  isActive: true,
  _archivedAt: null,
}

Business Logic Workflow

[1] Step : startBusinessApi

Manager initializes context, populates session and request objects, prepares internal structures for parameter handling and workflow execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Manager reads input parameters, normalizes missing values, applies default type casting, and stores them in the API context.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Manager transforms parameters, computes derived values, flattens or remaps arrays/objects, and adjusts formats for downstream processing.


[4] Step : checkParameters

Manager executes built-in validations: required field checks, type enforcement, and basic business rules. Prevents operation if validation fails.


[5] Action : validateEmail

Action Type: ValidationAction

Validates that the provided email address has a valid format

class Api {
  async validateEmail() {
    const isValid = runMScript(
      () => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(this.email),
      {
        path: "services[0].businessLogic[3].actions.validationActions[0].validationScript",
      },
    );

    if (!isValid) {
      throw new BadRequestError("InvalidEmailFormat");
    }
    return isValid;
  }
}

[6] Action : fetchArchivedUser

Action Type: FetchObjectAction

Check and get if any deleted user exists with the same identifier

class Api {
  async fetchArchivedUser() {
    // Fetch Object on childObject user

    const userQuery = runMScript(
      () => ({
        $and: [
          { email: this.email, isActive: false },
          {
            _archivedAt: {
              $gte: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000),
            },
          },
        ],
      }),
      {
        path: "services[0].businessLogic[3].actions.fetchObjectActions[0].whereClause",
      },
    );

    const { convertUserQueryToSequelizeQuery } = require("common");
    const scriptQuery = convertUserQueryToSequelizeQuery(userQuery);

    // get object from db
    const data = await getUserByQuery(scriptQuery);

    return data
      ? {
          id: data["id"],
        }
      : null;
  }
}

[7] Action : checkArchivedUser

Action Type: ValidationAction

Prevents re-register of a user when their profile is still in 30days archive

class Api {
  async checkArchivedUser() {
    const isError = runMScript(() => this.archivedUser?.email != null, {
      path: "services[0].businessLogic[3].actions.validationActions[1].validationScript",
    });

    if (isError) {
      throw new BadRequestError("ThisProfileIsArchivedPleaseLoginToRestore");
    }
    return isError;
  }
}

[8] Step : checkBasicAuth

Manager performs authentication and authorization checks: verifies session, user roles, permissions, and tenant restrictions.

You can use the following settings to change some behavior of this step. authOptions

[9] Step : buildDataClause

Manager constructs the final data object for creation, fills auto-generated fields (IDs, timestamps, owner fields), and ensures schema consistency.

You can use the following settings to change some behavior of this step. dataClause

[10] Step : mainCreateOperation

Manager executes the database insert operation, updates indexes/caches, and triggers internal post-processing like linked default records.


[11] Step : buildOutput

Manager shapes the response: masks sensitive fields, resolves linked references, and formats output according to API contract.


[12] Action : writeVerificationNeedsToResponse

Action Type: AddToResponseAction

Set if email or mobile verification needed

class Api {
  async writeVerificationNeedsToResponse() {
    try {
      this.output["emailVerificationNeeded"] = runMScript(() => false, {
        path: "services[0].businessLogic[3].actions.addToResponseActions[0].context[0].contextValue",
      });

      this.output["mobileVerificationNeeded"] = runMScript(() => false, {
        path: "services[0].businessLogic[3].actions.addToResponseActions[0].context[1].contextValue",
      });

      return true;
    } catch (error) {
      console.error("AddToResponseAction error:", error);
      throw error;
    }
  }
}

[13] Step : sendResponse

Manager sends the response to the client and finalizes internal tasks like flushing logs or updating session state.


[14] Step : raiseApiEvent

Manager triggers API-level events (Kafka, WebSocket, async workflows) as the final internal step.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The createUser api has got 4 regular client parameters

Parameter Type Required Population
avatar String false request.body?.[“avatar”]
email String true request.body?.[“email”]
password String true request.body?.[“password”]
fullname String true request.body?.[“fullname”]

REST Request

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

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

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the user object in the respones. However, some properties may be omitted based on the object’s internal logic.

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

Business API Design Specification - Delete User

Business API Design Specification - Delete User

A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic.

While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized.

This document provides an in-depth explanation of the architectural design of the deleteUser Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side.

Main Data Object and CRUD Operation

The deleteUser Business API is designed to handle a delete operation on the User data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

This api is used by admins to delete user profiles.

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The deleteUser Business API includes a REST controller that can be triggered via the following route:

/v1/users/:userId

By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the Parameters section.

gRPC Controller

The deleteUser Business API includes a gRPC controller that can be triggered via the following function:

deleteUser()

By calling this gRPC endpoint using a gRPC client, you can execute the Business API. Note that all parameters must be provided as function arguments, regardless of their HTTP location configuration, which is relevant only for the REST controller.

MCP Tool

REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This deleteUser Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The deleteUser Business API has 1 parameter that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client.

Business API parameters can be:

Regular Parameters

Name Type Required Default Location Data Path
userId ID Yes - urlpath userId
Description: This id paremeter is used to select the required data object that will be deleted

Parameter Transformations

Some parameters are post-processed using transform scripts after being read from the request but before validation or workflow execution. Only parameters with a transform script are listed below.

No parameters are transformed in this API.

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the deleteUser Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({$and:[{id:this.userId},{isActive:true}]}), {"path":"services[0].businessLogic[4].whereClause.fullWhereClause"})

Delete Options

Use these options to set delete specific settings.

useSoftDelete: If true, the record will be marked as deleted (isActive: false) instead of removed. The implementation depends on the data object’s soft delete configuration.

Business Logic Workflow

[1] Step : startBusinessApi

Manager initializes context, prepares request/session objects, and sets up internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Manager reads and normalizes parameters, applies defaults, and stores them in the context for downstream steps.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Manager executes parameter transform scripts, computes derived values, and remaps objects or arrays as needed for later processing.


[4] Step : checkParameters

Manager runs built-in validations including required field checks, type enforcement, and deletion preconditions. Stops execution if validation fails.


[5] Step : checkBasicAuth

Manager validates session, user roles, permissions, and tenant-specific access rules to enforce basic auth restrictions.

You can use the following settings to change some behavior of this step. authOptions

[6] Action : setRolesOrder

Action Type: CreateObjectAction

Sets the hiyerarchy of the roles to check user permissions on other users

class Api {
  async setRolesOrder() {
    // Construct base object
    const obj = {};

    // Merge dynamic object
    Object.assign(
      obj,
      runMScript(
        () => ({
          superAdmin: 20,
          saasAdmin: 19,
          admin: 18,
          tenantOwner: 17,
          tenantAdmin: 16,
          saasUser: 15,
          tenantUser: 0,
          user: 0,
        }),
        {
          path: "services[0].businessLogic[4].actions.createObjectActions[0].mergeObject",
        },
      ),
    );

    return obj;
  }
}

[7] Action : protectSuperAdmin

Action Type: ValidationAction

Prevents deletion of the SuperAdmin account. This safeguard ensures that the SuperAdmin userId cannot be removed under any circumstances.

class Api {
  async protectSuperAdmin() {
    const isError = runMScript(() => this.userId == this.auth?.superAdminId, {
      path: "services[0].businessLogic[4].actions.validationActions[0].validationScript",
    });

    if (isError) {
      throw new BadRequestError("SuperAdminCantBeDeleted");
    }
    return isError;
  }
}

[8] Step : buildWhereClause

Manager generates the query conditions, applies ownership and parent checks, and ensures the clause is correct for the delete operation.

You can use the following settings to change some behavior of this step. whereClause

[9] Step : fetchInstance

Manager fetches the target record, applies filters from WHERE clause, and writes the instance to the context for further checks.


[10] Step : checkInstance

Manager performs object-level validations such as lock status, soft-delete eligibility, and multi-step approval enforcement.


[11] Action : protectHigherRole

Action Type: ValidationAction

Prevents the delete of a higher or equal user role

class Api {
  async protectHigherRole() {
    const isValid = runMScript(
      () =>
        (this._r[this.session?.roleId] ?? 0) >
        (this._r[this.user?.roleId] ?? 0),
      {
        path: "services[0].businessLogic[4].actions.validationActions[1].validationScript",
      },
    );

    if (!isValid) {
      throw new BadRequestError("AHigherOrEqualUserRoleCantBeDeleted");
    }
    return isValid;
  }
}

[12] Step : mainDeleteOperation

Manager executes the delete query, updates related indexes/caches, and handles soft/hard delete logic according to configuration.

You can use the following settings to change some behavior of this step. deleteOptions

[13] Action : deleteUserSessions

Action Type: FunctionCallAction

Makes a call to this.auth to delete the sessions of the deleted user.

class Api {
  async deleteUserSessions() {
    try {
      return await runMScript(
        () =>
          (async () =>
            await (async (userId) => {
              await this.auth.deleteUserSessions(userId);
            })(this.userId))(),
        {
          path: "services[0].businessLogic[4].actions.functionCallActions[0].callScript",
        },
      );
    } catch (err) {
      console.error("Error in FunctionCallAction deleteUserSessions:", err);
      throw err;
    }
  }
}

[14] Step : buildOutput

Manager shapes the response payload, masks sensitive fields, and formats related cleanup results for output.


[15] Step : sendResponse

Manager delivers the response to the client and finalizes any temporary internal structures.


[16] Step : raiseApiEvent

Manager triggers asynchronous API events, notifies queues or streams, and performs final cleanup for the workflow.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The deleteUser api has got 1 regular client parameter

Parameter Type Required Population
userId ID true request.params?.[“userId”]

REST Request

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

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

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the user object in the respones. However, some properties may be omitted based on the object’s internal logic.

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

Business API Design Specification - Archive Profile

Business API Design Specification - Archive Profile

A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic.

While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized.

This document provides an in-depth explanation of the architectural design of the archiveProfile Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side.

Main Data Object and CRUD Operation

The archiveProfile Business API is designed to handle a delete operation on the User data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

This api is used by users to archive their profiles.

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The archiveProfile Business API includes a REST controller that can be triggered via the following route:

/v1/archiveprofile/:userId

By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the Parameters section.

gRPC Controller

The archiveProfile Business API includes a gRPC controller that can be triggered via the following function:

archiveProfile()

By calling this gRPC endpoint using a gRPC client, you can execute the Business API. Note that all parameters must be provided as function arguments, regardless of their HTTP location configuration, which is relevant only for the REST controller.

MCP Tool

REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This archiveProfile Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The archiveProfile Business API has 1 parameter that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client.

Business API parameters can be:

Regular Parameters

Name Type Required Default Location Data Path
userId ID Yes - urlpath userId
Description: This id paremeter is used to select the required data object that will be deleted

Parameter Transformations

Some parameters are post-processed using transform scripts after being read from the request but before validation or workflow execution. Only parameters with a transform script are listed below.

No parameters are transformed in this API.

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the archiveProfile Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({$and:[{id:this.userId},{isActive:true}]}), {"path":"services[0].businessLogic[5].whereClause.fullWhereClause"})

Delete Options

Use these options to set delete specific settings.

useSoftDelete: If true, the record will be marked as deleted (isActive: false) instead of removed. The implementation depends on the data object’s soft delete configuration.

Business Logic Workflow

[1] Step : startBusinessApi

Manager initializes context, prepares request/session objects, and sets up internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Manager reads and normalizes parameters, applies defaults, and stores them in the context for downstream steps.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Manager executes parameter transform scripts, computes derived values, and remaps objects or arrays as needed for later processing.


[4] Step : checkParameters

Manager runs built-in validations including required field checks, type enforcement, and deletion preconditions. Stops execution if validation fails.


[5] Step : checkBasicAuth

Manager validates session, user roles, permissions, and tenant-specific access rules to enforce basic auth restrictions.

You can use the following settings to change some behavior of this step. authOptions

[6] Action : protectSuperAdmin

Action Type: ValidationAction

Prevents deletion of the SuperAdmin account. This safeguard ensures that the SuperAdmin userId cannot be removed under any circumstances.

class Api {
  async protectSuperAdmin() {
    const isError = runMScript(() => this.userId == this.auth?.superAdminId, {
      path: "services[0].businessLogic[5].actions.validationActions[0].validationScript",
    });

    if (isError) {
      throw new BadRequestError("SuperAdminCantBeDeleted");
    }
    return isError;
  }
}

[7] Step : buildWhereClause

Manager generates the query conditions, applies ownership and parent checks, and ensures the clause is correct for the delete operation.

You can use the following settings to change some behavior of this step. whereClause

[8] Step : fetchInstance

Manager fetches the target record, applies filters from WHERE clause, and writes the instance to the context for further checks.


[9] Step : checkInstance

Manager performs object-level validations such as lock status, soft-delete eligibility, and multi-step approval enforcement.


[10] Step : mainDeleteOperation

Manager executes the delete query, updates related indexes/caches, and handles soft/hard delete logic according to configuration.

You can use the following settings to change some behavior of this step. deleteOptions

[11] Action : deleteUserSessions

Action Type: FunctionCallAction

Makes a call to this.auth to delete the sessions of the deleted user.

class Api {
  async deleteUserSessions() {
    try {
      return await runMScript(
        () =>
          (async () =>
            await (async (userId) => {
              await this.auth.deleteUserSessions(userId);
            })(this.userId))(),
        {
          path: "services[0].businessLogic[5].actions.functionCallActions[0].callScript",
        },
      );
    } catch (err) {
      console.error("Error in FunctionCallAction deleteUserSessions:", err);
      throw err;
    }
  }
}

[12] Step : buildOutput

Manager shapes the response payload, masks sensitive fields, and formats related cleanup results for output.


[13] Step : sendResponse

Manager delivers the response to the client and finalizes any temporary internal structures.


[14] Step : raiseApiEvent

Manager triggers asynchronous API events, notifies queues or streams, and performs final cleanup for the workflow.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The archiveProfile api has got 1 regular client parameter

Parameter Type Required Population
userId ID true request.params?.[“userId”]

REST Request

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

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

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the user object in the respones. However, some properties may be omitted based on the object’s internal logic.

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

Business API Design Specification - List Users

Business API Design Specification - List Users

A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic.

While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized.

This document provides an in-depth explanation of the architectural design of the listUsers Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side.

Main Data Object and CRUD Operation

The listUsers Business API is designed to handle a list operation on the User data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

The list of users is filtered by the tenantId.

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The listUsers Business API includes a REST controller that can be triggered via the following route:

/v1/users

By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the Parameters section.

gRPC Controller

The listUsers Business API includes a gRPC controller that can be triggered via the following function:

listUsers()

By calling this gRPC endpoint using a gRPC client, you can execute the Business API. Note that all parameters must be provided as function arguments, regardless of their HTTP location configuration, which is relevant only for the REST controller.

MCP Tool

REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This listUsers Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The listUsers Business API has 3 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client.

Business API parameters can be:

Filter Parameters

The listUsers api supports 3 optional filter parameters for filtering list results using URL query parameters. These parameters are only available for list type APIs.

email Filter

Type: String
Description: A string value to represent the user’s email.
Location: Query Parameter

Usage:

Non-Array Property (Case-Insensitive Partial Matching):

Examples:

// Find records with "john" in the field (case-insensitive partial match)
GET /v1/users?email=john
// Matches: "John", "Johnny", "johnson", "McJohn", etc.

// Find records with multiple values (use multiple parameters)
GET /v1/users?email=laptop&email=phone&email=tablet
// Matches records containing "laptop", "phone", or "tablet" anywhere in the field

// Find records without this field
GET /v1/users?email=null

fullname Filter

Type: String
Description: A string value to represent the fullname of the user
Location: Query Parameter

Usage:

Non-Array Property (Case-Insensitive Partial Matching):

Examples:

// Find records with "john" in the field (case-insensitive partial match)
GET /v1/users?fullname=john
// Matches: "John", "Johnny", "johnson", "McJohn", etc.

// Find records with multiple values (use multiple parameters)
GET /v1/users?fullname=laptop&fullname=phone&fullname=tablet
// Matches records containing "laptop", "phone", or "tablet" anywhere in the field

// Find records without this field
GET /v1/users?fullname=null

roleId Filter

Type: String
Description: A string value to represent the roleId of the user.
Location: Query Parameter

Usage:

Non-Array Property (Case-Insensitive Partial Matching):

Examples:

// Find records with "john" in the field (case-insensitive partial match)
GET /v1/users?roleId=john
// Matches: "John", "Johnny", "johnson", "McJohn", etc.

// Find records with multiple values (use multiple parameters)
GET /v1/users?roleId=laptop&roleId=phone&roleId=tablet
// Matches records containing "laptop", "phone", or "tablet" anywhere in the field

// Find records without this field
GET /v1/users?roleId=null

Parameter Transformations

Some parameters are post-processed using transform scripts after being read from the request but before validation or workflow execution. Only parameters with a transform script are listed below.

No parameters are transformed in this API.

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the listUsers Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Select Clause

Specifies which fields will be selected from the main data object during a get or list operation. Leave blank to select all properties. This applies only to get and list type APIs.",

``

Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({isActive:true}), {"path":"services[0].businessLogic[6].whereClause.fullWhereClause"})

List Options

Defines list-specific options including filtering logic, default sorting, and result customization for APIs that return multiple records.

List Sort By Sort order definitions for the result set. Multiple fields can be provided with direction (asc/desc).

[ id asc ]

List Group By Grouping definitions for the result set. This is typically used for visual or report-based grouping.

The list is not grouped.

setAsRead: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed.

No setAsread field-value pair is configured.

Permission Filter Optional filter that applies permission constraints dynamically based on session or object roles. So that the list items are filtered by the user’s OBAC or ABAC permissions.

Permission filter is not active at the moment. Follow Mindbricks updates to be able to use it.

Pagination Options

Contains settings to configure pagination behavior for list APIs. Includes options like page size, offset, cursor support, and total count inclusion.

Business Logic Workflow

[1] Step : startBusinessApi

Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Reads request and Redis parameters, applies defaults, and writes them to context for downstream processing.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Transforms and normalizes parameters, derives dependent values, and reshapes inputs for the main list query.


[4] Step : checkParameters

Executes validation logic on required and custom parameters, enforcing business rules and cross-field consistency.


[5] Step : checkBasicAuth

Performs role-based access checks and applies dynamic membership or session-based restrictions.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildWhereClause

Constructs the main query WHERE clause and applies optional filters or scoped access controls.

You can use the following settings to change some behavior of this step. whereClause

[7] Step : mainListOperation

Executes the paginated database query, retrieves the list, and stores results in context for enrichment.

You can use the following settings to change some behavior of this step. selectClause, listOptions, paginationOptions

[8] Step : buildOutput

Assembles the list response, sanitizes sensitive fields, applies transformations, and injects extra context if needed.


[9] Step : sendResponse

Sends the paginated list to the client through the controller.


[10] Step : raiseApiEvent

Triggers optional post-workflow events, such as Kafka messages, logs, or system notifications.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The listUsers api has 3 filter parameters available for filtering list results. See the Filter Parameters section above for detailed usage examples.

Filter Parameter Type Array Property Description
email String No A string value to represent the user’s email.
fullname String No A string value to represent the fullname of the user
roleId String No A string value to represent the roleId of the user.

REST Request

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

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

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the users object in the respones. However, some properties may be omitted based on the object’s internal logic.

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

Business API Design Specification - Search Users

Business API Design Specification - Search Users

A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic.

While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized.

This document provides an in-depth explanation of the architectural design of the searchUsers Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side.

Main Data Object and CRUD Operation

The searchUsers Business API is designed to handle a list operation on the User data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

The list of users is filtered by the tenantId.

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The searchUsers Business API includes a REST controller that can be triggered via the following route:

/v1/searchusers

By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the Parameters section.

gRPC Controller

The searchUsers Business API includes a gRPC controller that can be triggered via the following function:

searchUsers()

By calling this gRPC endpoint using a gRPC client, you can execute the Business API. Note that all parameters must be provided as function arguments, regardless of their HTTP location configuration, which is relevant only for the REST controller.

MCP Tool

REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This searchUsers Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The searchUsers Business API has 2 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client.

Business API parameters can be:

Regular Parameters

Name Type Required Default Location Data Path
keyword String Yes - query keyword
Description: -

Filter Parameters

The searchUsers api supports 1 optional filter parameter for filtering list results using URL query parameters. These parameters are only available for list type APIs.

roleId Filter

Type: String
Description: A string value to represent the roleId of the user.
Location: Query Parameter

Usage:

Non-Array Property (Case-Insensitive Partial Matching):

Examples:

// Find records with "john" in the field (case-insensitive partial match)
GET /v1/searchusers?roleId=john
// Matches: "John", "Johnny", "johnson", "McJohn", etc.

// Find records with multiple values (use multiple parameters)
GET /v1/searchusers?roleId=laptop&roleId=phone&roleId=tablet
// Matches records containing "laptop", "phone", or "tablet" anywhere in the field

// Find records without this field
GET /v1/searchusers?roleId=null

Parameter Transformations

Some parameters are post-processed using transform scripts after being read from the request but before validation or workflow execution. Only parameters with a transform script are listed below.

No parameters are transformed in this API.

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the searchUsers Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Select Clause

Specifies which fields will be selected from the main data object during a get or list operation. Leave blank to select all properties. This applies only to get and list type APIs.",

``

Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({isActive:true}), {"path":"services[0].businessLogic[7].whereClause.fullWhereClause"})

List Options

Defines list-specific options including filtering logic, default sorting, and result customization for APIs that return multiple records.

List Sort By Sort order definitions for the result set. Multiple fields can be provided with direction (asc/desc).

[ id asc ]

List Group By Grouping definitions for the result set. This is typically used for visual or report-based grouping.

The list is not grouped.

setAsRead: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed.

No setAsread field-value pair is configured.

Permission Filter Optional filter that applies permission constraints dynamically based on session or object roles. So that the list items are filtered by the user’s OBAC or ABAC permissions.

Permission filter is not active at the moment. Follow Mindbricks updates to be able to use it.

Pagination Options

Contains settings to configure pagination behavior for list APIs. Includes options like page size, offset, cursor support, and total count inclusion.

Business Logic Workflow

[1] Step : startBusinessApi

Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Reads request and Redis parameters, applies defaults, and writes them to context for downstream processing.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Transforms and normalizes parameters, derives dependent values, and reshapes inputs for the main list query.


[4] Step : checkParameters

Executes validation logic on required and custom parameters, enforcing business rules and cross-field consistency.


[5] Step : checkBasicAuth

Performs role-based access checks and applies dynamic membership or session-based restrictions.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildWhereClause

Constructs the main query WHERE clause and applies optional filters or scoped access controls.

You can use the following settings to change some behavior of this step. whereClause

[7] Step : mainListOperation

Executes the paginated database query, retrieves the list, and stores results in context for enrichment.

You can use the following settings to change some behavior of this step. selectClause, listOptions, paginationOptions

[8] Step : buildOutput

Assembles the list response, sanitizes sensitive fields, applies transformations, and injects extra context if needed.


[9] Step : sendResponse

Sends the paginated list to the client through the controller.


[10] Step : raiseApiEvent

Triggers optional post-workflow events, such as Kafka messages, logs, or system notifications.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The searchUsers api has got 1 regular client parameter

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

The searchUsers api has 1 filter parameter available for filtering list results. See the Filter Parameters section above for detailed usage examples.

Filter Parameter Type Array Property Description
roleId String No A string value to represent the roleId of the user.

REST Request

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

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

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the users object in the respones. However, some properties may be omitted based on the object’s internal logic.

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

Business API Design Specification - Update Userrole

Business API Design Specification - Update Userrole

A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic.

While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized.

This document provides an in-depth explanation of the architectural design of the updateUserRole Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side.

Main Data Object and CRUD Operation

The updateUserRole Business API is designed to handle a update operation on the User data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

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

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The updateUserRole Business API includes a REST controller that can be triggered via the following route:

/v1/userrole/:userId

By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the Parameters section.

gRPC Controller

The updateUserRole Business API includes a gRPC controller that can be triggered via the following function:

updateUserRole()

By calling this gRPC endpoint using a gRPC client, you can execute the Business API. Note that all parameters must be provided as function arguments, regardless of their HTTP location configuration, which is relevant only for the REST controller.

MCP Tool

REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This updateUserRole Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The updateUserRole Business API has 2 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client.

Business API parameters can be:

Regular Parameters

Name Type Required Default Location Data Path
userId ID Yes - urlpath userId
Description: This id paremeter is used to select the required data object that will be updated
roleId String Yes - body roleId
Description: The new roleId of the user to be updated

Parameter Transformations

Some parameters are post-processed using transform scripts after being read from the request but before validation or workflow execution. Only parameters with a transform script are listed below.

No parameters are transformed in this API.

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the updateUserRole Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({$and:[{id:this.userId},{isActive:true}]}), {"path":"services[0].businessLogic[8].whereClause.fullWhereClause"})

Data Clause

Defines custom field-value assignments used to modify or augment the default payload for create and update operations. These settings override values derived from the session or parameters if explicitly provided.", Note that a default data clause is always prepared by Mindbricks using data property settings, however any property in the data clause can be override by Data Clause Settings.

An update data clause populates all update-allowed properties of a data object, however the null properties (that are not provided by client) are ignored in db layer.

Custom Data Clause Override

{
    roleId: runMScript(() => (this.roleId), {"path":"services[0].businessLogic[8].dataClause.customData[0].value"}),
   
}

Actual Data Clause

The business api will use the following data clause. Note that any calculated value will be added to the data clause in the api manager.

{
  // roleId parameter is closed to update by client request 
  // include it in data clause unless you are sure 
  roleId: runMScript(() => (this.roleId), {"path":"services[0].businessLogic[8].dataClause.customData[0].value"}),
}

Business Logic Workflow

[1] Step : startBusinessApi

Manager initializes context, prepares request and session objects, and sets up internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Manager reads parameters from the request or Redis, applies defaults, and writes them into context for downstream milestones.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Manager executes parameter transform scripts and derives any helper values or reshaped payloads into the context.


[4] Step : checkParameters

Manager validates required parameters, checks ID formats (UUID/ObjectId), and ensures all preconditions for update are met.


[5] Step : checkBasicAuth

Manager performs login verification, role, and permission checks, enforcing tenant and access rules before update.

You can use the following settings to change some behavior of this step. authOptions

[6] Action : setRolesOrder

Action Type: CreateObjectAction

Sets the hiyerarchy of the roles to check user permissions on other users

class Api {
  async setRolesOrder() {
    // Construct base object
    const obj = {};

    // Merge dynamic object
    Object.assign(
      obj,
      runMScript(
        () => ({
          superAdmin: 20,
          saasAdmin: 19,
          admin: 18,
          tenantOwner: 17,
          tenantAdmin: 16,
          saasUser: 15,
          tenantUser: 0,
          user: 0,
        }),
        {
          path: "services[0].businessLogic[8].actions.createObjectActions[0].mergeObject",
        },
      ),
    );

    return obj;
  }
}

[7] Action : preventHigherRoleSet

Action Type: ValidationAction

Prevents to set a user’s role as higher than or equal to the setter role

class Api {
  async preventHigherRoleSet() {
    const isValid = runMScript(
      () => (this._r[this.session.roleId] ?? 0) > (this._r[this.roleId] ?? 0),
      {
        path: "services[0].businessLogic[8].actions.validationActions[0].validationScript",
      },
    );

    if (!isValid) {
      throw new BadRequestError("AHigherRoleCantBeAssigned");
    }
    return isValid;
  }
}

[8] Step : buildWhereClause

Manager constructs the WHERE clause used to identify the record to update, applying ownership and parent checks if necessary.

You can use the following settings to change some behavior of this step. whereClause

[9] Step : fetchInstance

Manager fetches the existing record from the database and writes it to the context for validation or enrichment.


[10] Action : protectHigherRole

Action Type: ValidationAction

Prevents the update of a higher or equal user role

class Api {
  async protectHigherRole() {
    const isValid = runMScript(
      () =>
        (this._r[this.session.roleId] ?? 0) > (this._r[this.user.roleId] ?? 0),
      {
        path: "services[0].businessLogic[8].actions.validationActions[1].validationScript",
      },
    );

    if (!isValid) {
      throw new BadRequestError("AHigherUserRoleCantBeChanged");
    }
    return isValid;
  }
}

[11] Step : checkInstance

Manager performs instance-level validations, including ownership, existence, lock status, or other pre-update checks.


[12] Step : buildDataClause

Manager prepares the data clause for the update, applying transformations or enhancements before persisting.

You can use the following settings to change some behavior of this step. dataClause

[13] Step : mainUpdateOperation

Manager executes the update operation with the WHERE and data clauses. Database-level events are raised if configured.


[14] Step : buildOutput

Manager assembles the response object from the update result, masking fields or injecting additional metadata.


[15] Step : sendResponse

Manager sends the response back to the controller for delivery to the client.


[16] Step : raiseApiEvent

Manager triggers API-level events, sending relevant messages to Kafka or other integrations if configured.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The updateUserRole api has got 2 regular client parameters

Parameter Type Required Population
userId ID true request.params?.[“userId”]
roleId String true request.body?.[“roleId”]

REST Request

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

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

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the user object in the respones. However, some properties may be omitted based on the object’s internal logic.

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

Business API Design Specification - Update Userpassword

Business API Design Specification - Update Userpassword

A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic.

While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized.

This document provides an in-depth explanation of the architectural design of the updateUserPassword Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side.

Main Data Object and CRUD Operation

The updateUserPassword Business API is designed to handle a update operation on the User data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

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

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The updateUserPassword Business API includes a REST controller that can be triggered via the following route:

/v1/userpassword/:userId

By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the Parameters section.

gRPC Controller

The updateUserPassword Business API includes a gRPC controller that can be triggered via the following function:

updateUserPassword()

By calling this gRPC endpoint using a gRPC client, you can execute the Business API. Note that all parameters must be provided as function arguments, regardless of their HTTP location configuration, which is relevant only for the REST controller.

MCP Tool

REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This updateUserPassword Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The updateUserPassword Business API has 3 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client.

Business API parameters can be:

Regular Parameters

Name Type Required Default Location Data Path
userId ID Yes - urlpath userId
Description: This id paremeter is used to select the required data object that will be updated
oldPassword String Yes - body oldPassword
Description: The old password of the user that will be overridden bu the new one. Send for double check.
newPassword String Yes - body newPassword
Description: The new password of the user to be updated

Parameter Transformations

Some parameters are post-processed using transform scripts after being read from the request but before validation or workflow execution. Only parameters with a transform script are listed below.

this.newPassword = 
  runMScript(() => (this.newPassword ? this.hashString(this.newPassword) : null), {"path":"services[0].businessLogic[9].customParameters[1].transform"})

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the updateUserPassword Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({$and:[{id:this.userId},{isActive:true}]}), {"path":"services[0].businessLogic[9].whereClause.fullWhereClause"})

Data Clause

Defines custom field-value assignments used to modify or augment the default payload for create and update operations. These settings override values derived from the session or parameters if explicitly provided.", Note that a default data clause is always prepared by Mindbricks using data property settings, however any property in the data clause can be override by Data Clause Settings.

An update data clause populates all update-allowed properties of a data object, however the null properties (that are not provided by client) are ignored in db layer.

Custom Data Clause Override

{
    password: runMScript(() => (this.newPassword), {"path":"services[0].businessLogic[9].dataClause.customData[0].value"}),
   
}

Actual Data Clause

The business api will use the following data clause. Note that any calculated value will be added to the data clause in the api manager.

{
  // password parameter is closed to update by client request 
  // include it in data clause unless you are sure 
  password: runMScript(() => (this.newPassword), {"path":"services[0].businessLogic[9].dataClause.customData[0].value"}),
}

Business Logic Workflow

[1] Step : startBusinessApi

Manager initializes context, prepares request and session objects, and sets up internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Manager reads parameters from the request or Redis, applies defaults, and writes them into context for downstream milestones.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Manager executes parameter transform scripts and derives any helper values or reshaped payloads into the context.


[4] Step : checkParameters

Manager validates required parameters, checks ID formats (UUID/ObjectId), and ensures all preconditions for update are met.


[5] Step : checkBasicAuth

Manager performs login verification, role, and permission checks, enforcing tenant and access rules before update.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildWhereClause

Manager constructs the WHERE clause used to identify the record to update, applying ownership and parent checks if necessary.

You can use the following settings to change some behavior of this step. whereClause

[7] Step : fetchInstance

Manager fetches the existing record from the database and writes it to the context for validation or enrichment.


[8] Step : checkInstance

Manager performs instance-level validations, including ownership, existence, lock status, or other pre-update checks.


[9] Action : checkOldPassword

Action Type: ValidationAction

Check if the current password mathces the old password. It is done after the instance is fetched.

class Api {
  async checkOldPassword() {
    if (this.checkAbsolute()) return true;

    const isValid = runMScript(
      () => this.hashCompare(this.oldPassword, this.user.password),
      {
        path: "services[0].businessLogic[9].actions.validationActions[0].validationScript",
      },
    );

    if (!isValid) {
      throw new ForbiddenError("TheOldPasswordDoesNotMatch");
    }
    return isValid;
  }
}

[10] Step : buildDataClause

Manager prepares the data clause for the update, applying transformations or enhancements before persisting.

You can use the following settings to change some behavior of this step. dataClause

[11] Step : mainUpdateOperation

Manager executes the update operation with the WHERE and data clauses. Database-level events are raised if configured.


[12] Step : buildOutput

Manager assembles the response object from the update result, masking fields or injecting additional metadata.


[13] Step : sendResponse

Manager sends the response back to the controller for delivery to the client.


[14] Step : raiseApiEvent

Manager triggers API-level events, sending relevant messages to Kafka or other integrations if configured.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The updateUserPassword api has got 3 regular client parameters

Parameter Type Required Population
userId ID true request.params?.[“userId”]
oldPassword String true request.body?.[“oldPassword”]
newPassword String true request.body?.[“newPassword”]

REST Request

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

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

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the user object in the respones. However, some properties may be omitted based on the object’s internal logic.

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

Business API Design Specification - Update Userpasswordbyadmin

Business API Design Specification - Update Userpasswordbyadmin

A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic.

While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized.

This document provides an in-depth explanation of the architectural design of the updateUserPasswordByAdmin Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side.

Main Data Object and CRUD Operation

The updateUserPasswordByAdmin Business API is designed to handle a update operation on the User data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

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

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The updateUserPasswordByAdmin Business API includes a REST controller that can be triggered via the following route:

/v1/userpasswordbyadmin/:userId

By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the Parameters section.

gRPC Controller

The updateUserPasswordByAdmin Business API includes a gRPC controller that can be triggered via the following function:

updateUserPasswordByAdmin()

By calling this gRPC endpoint using a gRPC client, you can execute the Business API. Note that all parameters must be provided as function arguments, regardless of their HTTP location configuration, which is relevant only for the REST controller.

MCP Tool

REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This updateUserPasswordByAdmin Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The updateUserPasswordByAdmin Business API has 2 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client.

Business API parameters can be:

Regular Parameters

Name Type Required Default Location Data Path
userId ID Yes - urlpath userId
Description: This id paremeter is used to select the required data object that will be updated
password String Yes - body password
Description: The new password of the user to be updated

Parameter Transformations

Some parameters are post-processed using transform scripts after being read from the request but before validation or workflow execution. Only parameters with a transform script are listed below.

this.password = 
  runMScript(() => (this.password ? this.hashString(this.password) : null), {"path":"services[0].businessLogic[10].customParameters[0].transform"})

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the updateUserPasswordByAdmin Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({$and:[{id:this.userId},{isActive:true}]}), {"path":"services[0].businessLogic[10].whereClause.fullWhereClause"})

Data Clause

Defines custom field-value assignments used to modify or augment the default payload for create and update operations. These settings override values derived from the session or parameters if explicitly provided.", Note that a default data clause is always prepared by Mindbricks using data property settings, however any property in the data clause can be override by Data Clause Settings.

An update data clause populates all update-allowed properties of a data object, however the null properties (that are not provided by client) are ignored in db layer.

Custom Data Clause Override

{
    password: runMScript(() => (this.password), {"path":"services[0].businessLogic[10].dataClause.customData[0].value"}),
   
}

Actual Data Clause

The business api will use the following data clause. Note that any calculated value will be added to the data clause in the api manager.

{
  // password parameter is closed to update by client request 
  // include it in data clause unless you are sure 
  password: runMScript(() => (this.password), {"path":"services[0].businessLogic[10].dataClause.customData[0].value"}),
}

Business Logic Workflow

[1] Step : startBusinessApi

Manager initializes context, prepares request and session objects, and sets up internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Manager reads parameters from the request or Redis, applies defaults, and writes them into context for downstream milestones.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Manager executes parameter transform scripts and derives any helper values or reshaped payloads into the context.


[4] Step : checkParameters

Manager validates required parameters, checks ID formats (UUID/ObjectId), and ensures all preconditions for update are met.


[5] Step : checkBasicAuth

Manager performs login verification, role, and permission checks, enforcing tenant and access rules before update.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildWhereClause

Manager constructs the WHERE clause used to identify the record to update, applying ownership and parent checks if necessary.

You can use the following settings to change some behavior of this step. whereClause

[7] Step : fetchInstance

Manager fetches the existing record from the database and writes it to the context for validation or enrichment.


[8] Step : checkInstance

Manager performs instance-level validations, including ownership, existence, lock status, or other pre-update checks.


[9] Action : setRolesOrder

Action Type: CreateObjectAction

Sets the hiyerarchy of the roles to check user permissions on other users

class Api {
  async setRolesOrder() {
    // Construct base object
    const obj = {};

    // Merge dynamic object
    Object.assign(
      obj,
      runMScript(
        () => ({
          superAdmin: 20,
          saasAdmin: 19,
          admin: 18,
          tenantOwner: 17,
          tenantAdmin: 16,
          saasUser: 15,
          tenantUser: 14,
          user: 13,
        }),
        {
          path: "services[0].businessLogic[10].actions.createObjectActions[0].mergeObject",
        },
      ),
    );

    return obj;
  }
}

[10] Action : protectHigherRole

Action Type: ValidationAction

Prevents the update of a higher or equal user role

class Api {
  async protectHigherRole() {
    const isValid = runMScript(
      () =>
        (this._r[this.session.roleId] ?? 0) > (this._r[this.user.roleId] ?? 0),
      {
        path: "services[0].businessLogic[10].actions.validationActions[0].validationScript",
      },
    );

    if (!isValid) {
      throw new BadRequestError("AHigherUserCantBeUpdated");
    }
    return isValid;
  }
}

[11] Step : buildDataClause

Manager prepares the data clause for the update, applying transformations or enhancements before persisting.

You can use the following settings to change some behavior of this step. dataClause

[12] Step : mainUpdateOperation

Manager executes the update operation with the WHERE and data clauses. Database-level events are raised if configured.


[13] Step : buildOutput

Manager assembles the response object from the update result, masking fields or injecting additional metadata.


[14] Step : sendResponse

Manager sends the response back to the controller for delivery to the client.


[15] Step : raiseApiEvent

Manager triggers API-level events, sending relevant messages to Kafka or other integrations if configured.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The updateUserPasswordByAdmin api has got 2 regular client parameters

Parameter Type Required Population
userId ID true request.params?.[“userId”]
password String true request.body?.[“password”]

REST Request

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

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

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the user object in the respones. However, some properties may be omitted based on the object’s internal logic.

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

Business API Design Specification - Get Briefuser

Business API Design Specification - Get Briefuser

A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic.

While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized.

This document provides an in-depth explanation of the architectural design of the getBriefUser Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side.

Main Data Object and CRUD Operation

The getBriefUser Business API is designed to handle a get operation on the User data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

This route is used by public to get simple user profile information.

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The getBriefUser Business API includes a REST controller that can be triggered via the following route:

/v1/briefuser/:userId

By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the Parameters section.

gRPC Controller

The getBriefUser Business API includes a gRPC controller that can be triggered via the following function:

getBriefUser()

By calling this gRPC endpoint using a gRPC client, you can execute the Business API. Note that all parameters must be provided as function arguments, regardless of their HTTP location configuration, which is relevant only for the REST controller.

MCP Tool

REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This getBriefUser Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The getBriefUser Business API has 1 parameter that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client.

Business API parameters can be:

Regular Parameters

Name Type Required Default Location Data Path
userId ID Yes - urlpath userId
Description: This id paremeter is used to query the required data object.

Parameter Transformations

Some parameters are post-processed using transform scripts after being read from the request but before validation or workflow execution. Only parameters with a transform script are listed below.

No parameters are transformed in this API.

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the getBriefUser Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API is public and can be accessed without login (loginRequired = false).


Ownership Checks


Role and Permission Settings


Select Clause

Specifies which fields will be selected from the main data object during a get or list operation. Leave blank to select all properties. This applies only to get and list type APIs.",

id,fullname,avatar

Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({$and:[{id:this.userId},{isActive:true}]}), {"path":"services[0].businessLogic[11].whereClause.fullWhereClause"})

Get Options

Use these options to set get specific settings.

setAsRead: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed.

No setAsread field-value pair is configured.

Business Logic Workflow

[1] Step : startBusinessApi

Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Extracts parameters from request and Redis, applies defaults, and writes them to context.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Executes parameter transformation scripts, applies type coercion, merges derived values, and reshapes inputs for downstream milestones.


[4] Step : checkParameters

Validates required and custom parameters, enforcing business-specific rules and constraints.


[5] Step : checkBasicAuth

Performs login, role, and permission checks, and applies dynamic object-level access rules.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildWhereClause

Builds the WHERE clause for fetching the object and applies additional scoped filters if configured.

You can use the following settings to change some behavior of this step. whereClause

[7] Step : mainGetOperation

Executes the database fetch, retrieves the object, and stores it in context for enrichment or further checks.

You can use the following settings to change some behavior of this step. selectClause, getOptions

[8] Step : checkInstance

Performs instance-level validations, such as ownership, existence, or access conditions.


[9] Step : buildOutput

Assembles the response from the object, applies masking, formatting, and injects additional metadata if needed.


[10] Step : sendResponse

Delivers the response to the controller for client delivery.


[11] Step : raiseApiEvent

Triggers optional API-level events after workflow completion, sending messages to integrations like Kafka if configured.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The getBriefUser api has got 1 regular client parameter

Parameter Type Required Population
userId ID true request.params?.[“userId”]

REST Request

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

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

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the user object in the respones. However, some properties may be omitted based on the object’s internal logic.

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

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

Business API Design Specification - Stream Test

Business API Design Specification - Stream Test

A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic.

While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized.

This document provides an in-depth explanation of the architectural design of the streamTest Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side.

Main Data Object and CRUD Operation

The streamTest Business API is designed to handle a get operation on the User data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

Test API for iterator action streaming via SSE.

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The streamTest Business API includes a REST controller that can be triggered via the following route:

/v1/streamtest/:userId

By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the Parameters section.

MCP Tool

REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This streamTest Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The streamTest Business API has 1 parameter that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client.

Business API parameters can be:

Regular Parameters

Name Type Required Default Location Data Path
userId ID Yes - urlpath userId
Description: This id paremeter is used to query the required data object.

Parameter Transformations

Some parameters are post-processed using transform scripts after being read from the request but before validation or workflow execution. Only parameters with a transform script are listed below.

No parameters are transformed in this API.

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the streamTest Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Select Clause

Specifies which fields will be selected from the main data object during a get or list operation. Leave blank to select all properties. This applies only to get and list type APIs.",

``

Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({$and:[{id:this.userId},{isActive:true}]}), {"path":"services[0].businessLogic[12].whereClause.fullWhereClause"})

Get Options

Use these options to set get specific settings.

setAsRead: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed.

No setAsread field-value pair is configured.

Business Logic Workflow

[1] Step : startBusinessApi

Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Extracts parameters from request and Redis, applies defaults, and writes them to context.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Executes parameter transformation scripts, applies type coercion, merges derived values, and reshapes inputs for downstream milestones.


[4] Step : checkParameters

Validates required and custom parameters, enforcing business-specific rules and constraints.


[5] Step : checkBasicAuth

Performs login, role, and permission checks, and applies dynamic object-level access rules.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildWhereClause

Builds the WHERE clause for fetching the object and applies additional scoped filters if configured.

You can use the following settings to change some behavior of this step. whereClause

[7] Step : mainGetOperation

Executes the database fetch, retrieves the object, and stores it in context for enrichment or further checks.

You can use the following settings to change some behavior of this step. selectClause, getOptions

[8] Step : checkInstance

Performs instance-level validations, such as ownership, existence, or access conditions.


[9] Step : buildOutput

Assembles the response from the object, applies masking, formatting, and injects additional metadata if needed.


[10] Step : sendResponse

Delivers the response to the controller for client delivery.


[11] Step : raiseApiEvent

Triggers optional API-level events after workflow completion, sending messages to integrations like Kafka if configured.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The streamTest api has got 1 regular client parameter

Parameter Type Required Population
userId ID true request.params?.[“userId”]

REST Request

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

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

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the user object in the respones. However, some properties may be omitted based on the object’s internal logic.

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

Business API Design Specification - Register User

Business API Design Specification - Register User

A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic.

While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized.

This document provides an in-depth explanation of the architectural design of the registerUser Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side.

Main Data Object and CRUD Operation

The registerUser Business API is designed to handle a create operation on the User data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

This api is used by public users to register themselves

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The registerUser Business API includes a REST controller that can be triggered via the following route:

/v1/registeruser

By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the Parameters section.

gRPC Controller

The registerUser Business API includes a gRPC controller that can be triggered via the following function:

registerUser()

By calling this gRPC endpoint using a gRPC client, you can execute the Business API. Note that all parameters must be provided as function arguments, regardless of their HTTP location configuration, which is relevant only for the REST controller.

MCP Tool

REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This registerUser Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The registerUser Business API has 6 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client.

Business API parameters can be:

Regular Parameters

Name Type Required Default Location Data Path
userId ID No - body userId
Description: This id paremeter is used to create the data object with a given specific id. Leave null for automatic id.
avatar String No - body avatar
Description: The avatar url of the user. If not sent, a default random one will be generated.
socialCode String No - body socialCode
Description: Send this social code if it is sent to you after a social login authetication of an unregistred user. The users profile data will be complemented from the autheticated social profile using this code. If you provide the social code there is no need to give full profile data of the user, just give the ones that are not included in social profiles.
password String Yes - body password
Description: The password defined by the the user that is being registered.
fullname String Yes - body fullname
Description: The fullname defined by the the user that is being registered.
email String Yes - body email
Description: The email defined by the the user that is being registered.

Parameter Transformations

Some parameters are post-processed using transform scripts after being read from the request but before validation or workflow execution. Only parameters with a transform script are listed below.

this.avatar = 
  runMScript(() => (this.socialProfile?.avatar ?? (this.avatar ? this.avatar : `https://gravatar.com/avatar/${LIB.common.md5(this.email ?? 'nullValue')}?s=200&d=identicon`)), {"path":"services[0].businessLogic[13].customParameters[0].transform"})
this.password = 
  runMScript(() => (this.socialProfile ? this.password ?? LIB.common.randomCode() : this.password), {"path":"services[0].businessLogic[13].customParameters[2].transform"})
this.fullname = 
  runMScript(() => (this.socialProfile?.fullname ?? this.fullname), {"path":"services[0].businessLogic[13].customParameters[3].transform"})
this.email = 
  runMScript(() => (this.socialProfile?.email ?? this.email), {"path":"services[0].businessLogic[13].customParameters[4].transform"})

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the registerUser Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API is public and can be accessed without login (loginRequired = false).


Ownership Checks


Role and Permission Settings


Data Clause

Defines custom field-value assignments used to modify or augment the default payload for create and update operations. These settings override values derived from the session or parameters if explicitly provided.", Note that a default data clause is always prepared by Mindbricks using data property settings, however any property in the data clause can be override by Data Clause Settings.

Custom Data Clause Override

{
    emailVerified: runMScript(() => (this.socialProfile?.emailVerified ?? false), {"path":"services[0].businessLogic[13].dataClause.customData[0].value"}),
    roleId: runMScript(() => (this.socialProfile?.roleId ?? 'user'), {"path":"services[0].businessLogic[13].dataClause.customData[1].value"}),
   
}

Actual Data Clause

The business api will use the following data clause. Note that any calculated value will be added to the data clause in the api manager.

{
  id: this.userId,
  email: this.email,
  password: this.hashString(this.password),
  fullname: this.fullname,
  avatar: this.avatar,
  emailVerified: runMScript(() => (this.socialProfile?.emailVerified ?? false), {"path":"services[0].businessLogic[13].dataClause.customData[0].value"}),
  roleId: runMScript(() => (this.socialProfile?.roleId ?? 'user'), {"path":"services[0].businessLogic[13].dataClause.customData[1].value"}),
  isActive: true,
  _archivedAt: null,
}

Business Logic Workflow

[1] Step : startBusinessApi

Manager initializes context, populates session and request objects, prepares internal structures for parameter handling and workflow execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Manager reads input parameters, normalizes missing values, applies default type casting, and stores them in the API context.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Manager transforms parameters, computes derived values, flattens or remaps arrays/objects, and adjusts formats for downstream processing.


[4] Step : checkParameters

Manager executes built-in validations: required field checks, type enforcement, and basic business rules. Prevents operation if validation fails.


[5] Action : validateEmail

Action Type: ValidationAction

Validates that the provided email address has a valid format

class Api {
  async validateEmail() {
    const isValid = runMScript(
      () => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(this.email),
      {
        path: "services[0].businessLogic[13].actions.validationActions[0].validationScript",
      },
    );

    if (!isValid) {
      throw new BadRequestError("InvalidEmailFormat");
    }
    return isValid;
  }
}

[6] Action : fetchArchivedUser

Action Type: FetchObjectAction

Check and get if any deleted user(in 30 days) exists with the same identifier

class Api {
  async fetchArchivedUser() {
    // Fetch Object on childObject user

    const userQuery = runMScript(
      () => ({
        $and: [
          { email: this.email, isActive: false },
          {
            _archivedAt: {
              $gte: new Date(Date.now() - 30 * 24 * 60 * 60 * 1000),
            },
          },
        ],
      }),
      {
        path: "services[0].businessLogic[13].actions.fetchObjectActions[0].whereClause",
      },
    );

    const { convertUserQueryToSequelizeQuery } = require("common");
    const scriptQuery = convertUserQueryToSequelizeQuery(userQuery);

    // get object from db
    const data = await getUserByQuery(scriptQuery);

    return data
      ? {
          id: data["id"],
        }
      : null;
  }
}

[7] Action : checkArchivedUser

Action Type: ValidationAction

Prevents re-register of a user when their profile is still in 30days archive

class Api {
  async checkArchivedUser() {
    const isError = runMScript(() => this.archivedUser?.email != null, {
      path: "services[0].businessLogic[13].actions.validationActions[1].validationScript",
    });

    if (isError) {
      throw new BadRequestError("YourProfileIsArchivedPleaseLoginToRestore");
    }
    return isError;
  }
}

[8] Step : checkBasicAuth

Manager performs authentication and authorization checks: verifies session, user roles, permissions, and tenant restrictions.

You can use the following settings to change some behavior of this step. authOptions

[9] Step : buildDataClause

Manager constructs the final data object for creation, fills auto-generated fields (IDs, timestamps, owner fields), and ensures schema consistency.

You can use the following settings to change some behavior of this step. dataClause

[10] Step : mainCreateOperation

Manager executes the database insert operation, updates indexes/caches, and triggers internal post-processing like linked default records.


[11] Step : buildOutput

Manager shapes the response: masks sensitive fields, resolves linked references, and formats output according to API contract.


[12] Action : writeVerificationNeedsToResponse

Action Type: AddToResponseAction

Set if email or mobile verification needed

class Api {
  async writeVerificationNeedsToResponse() {
    try {
      this.output["emailVerificationNeeded"] = runMScript(() => false, {
        path: "services[0].businessLogic[13].actions.addToResponseActions[0].context[0].contextValue",
      });

      this.output["mobileVerificationNeeded"] = runMScript(() => false, {
        path: "services[0].businessLogic[13].actions.addToResponseActions[0].context[1].contextValue",
      });

      return true;
    } catch (error) {
      console.error("AddToResponseAction error:", error);
      throw error;
    }
  }
}

[13] Action : autoLoginAfterRegister

Action Type: FunctionCallAction

If no email or mobile verification is needed after registration, automatically create a login session and return the access token in the registration response. This provides a seamless register-and-login experience.

class Api {
  async autoLoginAfterRegister() {
    try {
      return await runMScript(
        () =>
          (async () =>
            await (async () => {
              try {
                if (
                  this.output.emailVerificationNeeded ||
                  this.output.mobileVerificationNeeded
                )
                  return;
                const identifier = this.output[this.dataName]?.email;
                if (!identifier) return;
                const { createSessionManager } = require("sessionLayer");
                const sm = createSessionManager();
                await sm.setLoginToRequest(this.request, null, {
                  userField: "email",
                  subjectClaim: identifier,
                });
                this.output.accessToken = sm.accessToken;
                this.output.autoLoginSession = sm.session;
                this.request.autoLoginToken = sm.accessToken;
                console.log(
                  "Auto-login after registration successful for:",
                  identifier,
                );
              } catch (autoLoginErr) {
                console.log(
                  "Auto-login after registration failed:",
                  autoLoginErr.message,
                );
              }
            })())(),
        {
          path: "services[0].businessLogic[13].actions.functionCallActions[0].callScript",
        },
      );
    } catch (err) {
      console.error("Error in FunctionCallAction autoLoginAfterRegister:", err);
      throw err;
    }
  }
}

[14] Step : sendResponse

Manager sends the response to the client and finalizes internal tasks like flushing logs or updating session state.


[15] Step : raiseApiEvent

Manager triggers API-level events (Kafka, WebSocket, async workflows) as the final internal step.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The registerUser api has got 4 regular client parameters

Parameter Type Required Population
avatar String false request.body?.[“avatar”]
password String true request.body?.[“password”]
fullname String true request.body?.[“fullname”]
email String true request.body?.[“email”]

REST Request

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

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

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the user object in the respones. However, some properties may be omitted based on the object’s internal logic.

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

Business API Design Specification - Get Useravatarsfile

Business API Design Specification - Get Useravatarsfile

A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic.

While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized.

This document provides an in-depth explanation of the architectural design of the getUserAvatarsFile Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side.

Main Data Object and CRUD Operation

The getUserAvatarsFile Business API is designed to handle a get operation on the UserAvatarsFile data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The getUserAvatarsFile Business API includes a REST controller that can be triggered via the following route:

/v1/useravatarsfiles/:userAvatarsFileId

By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the Parameters section.

MCP Tool

REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This getUserAvatarsFile Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The getUserAvatarsFile Business API has 1 parameter that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client.

Business API parameters can be:

Regular Parameters

Name Type Required Default Location Data Path
userAvatarsFileId ID Yes - urlpath userAvatarsFileId
Description: This id paremeter is used to query the required data object.

Parameter Transformations

Some parameters are post-processed using transform scripts after being read from the request but before validation or workflow execution. Only parameters with a transform script are listed below.

No parameters are transformed in this API.

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the getUserAvatarsFile Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Select Clause

Specifies which fields will be selected from the main data object during a get or list operation. Leave blank to select all properties. This applies only to get and list type APIs.",

``

Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({id:this.userAvatarsFileId}), {"path":"services[0].businessLogic[14].whereClause.fullWhereClause"})

Get Options

Use these options to set get specific settings.

setAsRead: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed.

No setAsread field-value pair is configured.

Business Logic Workflow

[1] Step : startBusinessApi

Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Extracts parameters from request and Redis, applies defaults, and writes them to context.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Executes parameter transformation scripts, applies type coercion, merges derived values, and reshapes inputs for downstream milestones.


[4] Step : checkParameters

Validates required and custom parameters, enforcing business-specific rules and constraints.


[5] Step : checkBasicAuth

Performs login, role, and permission checks, and applies dynamic object-level access rules.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildWhereClause

Builds the WHERE clause for fetching the object and applies additional scoped filters if configured.

You can use the following settings to change some behavior of this step. whereClause

[7] Step : mainGetOperation

Executes the database fetch, retrieves the object, and stores it in context for enrichment or further checks.

You can use the following settings to change some behavior of this step. selectClause, getOptions

[8] Step : checkInstance

Performs instance-level validations, such as ownership, existence, or access conditions.


[9] Step : buildOutput

Assembles the response from the object, applies masking, formatting, and injects additional metadata if needed.


[10] Step : sendResponse

Delivers the response to the controller for client delivery.


[11] Step : raiseApiEvent

Triggers optional API-level events after workflow completion, sending messages to integrations like Kafka if configured.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The getUserAvatarsFile api has got 1 regular client parameter

Parameter Type Required Population
userAvatarsFileId ID true request.params?.[“userAvatarsFileId”]

REST Request

To access the api you can use the REST controller with the path GET /v1/useravatarsfiles/:userAvatarsFileId

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

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the userAvatarsFile object in the respones. However, some properties may be omitted based on the object’s internal logic.

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "userAvatarsFile",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"userAvatarsFile": {
		"id": "ID",
		"fileName": "String",
		"mimeType": "String",
		"fileSize": "Integer",
		"accessKey": "String",
		"ownerId": "ID",
		"fileData": "Blob",
		"metadata": "Object",
		"userId": "ID",
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"isActive": true
	}
}

Business API Design Specification - List Useravatarsfiles

Business API Design Specification - List Useravatarsfiles

A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic.

While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized.

This document provides an in-depth explanation of the architectural design of the listUserAvatarsFiles Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side.

Main Data Object and CRUD Operation

The listUserAvatarsFiles Business API is designed to handle a list operation on the UserAvatarsFile data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The listUserAvatarsFiles Business API includes a REST controller that can be triggered via the following route:

/v1/useravatarsfiles

By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the Parameters section.

MCP Tool

REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This listUserAvatarsFiles Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The listUserAvatarsFiles Business API has 3 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client.

Business API parameters can be:

Filter Parameters

The listUserAvatarsFiles api supports 3 optional filter parameters for filtering list results using URL query parameters. These parameters are only available for list type APIs.

mimeType Filter

Type: String
Description: MIME type of the uploaded file (e.g., image/png, application/pdf).
Location: Query Parameter

Usage:

Non-Array Property (Case-Insensitive Partial Matching):

Examples:

// Find records with "john" in the field (case-insensitive partial match)
GET /v1/useravatarsfiles?mimeType=john
// Matches: "John", "Johnny", "johnson", "McJohn", etc.

// Find records with multiple values (use multiple parameters)
GET /v1/useravatarsfiles?mimeType=laptop&mimeType=phone&mimeType=tablet
// Matches records containing "laptop", "phone", or "tablet" anywhere in the field

// Find records without this field
GET /v1/useravatarsfiles?mimeType=null

ownerId Filter

Type: ID
Description: ID of the user who uploaded the file (from session).
Location: Query Parameter

Usage:

Non-Array Property:

Examples:

// Get records with a specific ID
GET /v1/useravatarsfiles?ownerId=550e8400-e29b-41d4-a716-446655440000

// Get records with multiple IDs (use multiple parameters)
GET /v1/useravatarsfiles?ownerId=550e8400-e29b-41d4-a716-446655440000&ownerId=660e8400-e29b-41d4-a716-446655440001

// Get records without this field
GET /v1/useravatarsfiles?ownerId=null

userId Filter

Type: ID
Description: Reference to the owner user record.
Location: Query Parameter

Usage:

Non-Array Property:

Examples:

// Get records with a specific ID
GET /v1/useravatarsfiles?userId=550e8400-e29b-41d4-a716-446655440000

// Get records with multiple IDs (use multiple parameters)
GET /v1/useravatarsfiles?userId=550e8400-e29b-41d4-a716-446655440000&userId=660e8400-e29b-41d4-a716-446655440001

// Get records without this field
GET /v1/useravatarsfiles?userId=null

Parameter Transformations

Some parameters are post-processed using transform scripts after being read from the request but before validation or workflow execution. Only parameters with a transform script are listed below.

No parameters are transformed in this API.

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the listUserAvatarsFiles Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Select Clause

Specifies which fields will be selected from the main data object during a get or list operation. Leave blank to select all properties. This applies only to get and list type APIs.",

``

Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

null

List Options

Defines list-specific options including filtering logic, default sorting, and result customization for APIs that return multiple records.

List Sort By Sort order definitions for the result set. Multiple fields can be provided with direction (asc/desc).

Specific sort order is not configure, natural order (ascending id) will be used.

List Group By Grouping definitions for the result set. This is typically used for visual or report-based grouping.

The list is not grouped.

setAsRead: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed.

No setAsread field-value pair is configured.

Permission Filter Optional filter that applies permission constraints dynamically based on session or object roles. So that the list items are filtered by the user’s OBAC or ABAC permissions.

Permission filter is not active at the moment. Follow Mindbricks updates to be able to use it.

Pagination Options

Contains settings to configure pagination behavior for list APIs. Includes options like page size, offset, cursor support, and total count inclusion.

Business Logic Workflow

[1] Step : startBusinessApi

Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Reads request and Redis parameters, applies defaults, and writes them to context for downstream processing.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Transforms and normalizes parameters, derives dependent values, and reshapes inputs for the main list query.


[4] Step : checkParameters

Executes validation logic on required and custom parameters, enforcing business rules and cross-field consistency.


[5] Step : checkBasicAuth

Performs role-based access checks and applies dynamic membership or session-based restrictions.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildWhereClause

Constructs the main query WHERE clause and applies optional filters or scoped access controls.

You can use the following settings to change some behavior of this step. whereClause

[7] Step : mainListOperation

Executes the paginated database query, retrieves the list, and stores results in context for enrichment.

You can use the following settings to change some behavior of this step. selectClause, listOptions, paginationOptions

[8] Step : buildOutput

Assembles the list response, sanitizes sensitive fields, applies transformations, and injects extra context if needed.


[9] Step : sendResponse

Sends the paginated list to the client through the controller.


[10] Step : raiseApiEvent

Triggers optional post-workflow events, such as Kafka messages, logs, or system notifications.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The listUserAvatarsFiles api has 3 filter parameters available for filtering list results. See the Filter Parameters section above for detailed usage examples.

Filter Parameter Type Array Property Description
mimeType String No MIME type of the uploaded file (e.g., image/png, application/pdf).
ownerId ID No ID of the user who uploaded the file (from session).
userId ID No Reference to the owner user record.

REST Request

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

  axios({
    method: 'GET',
    url: '/v1/useravatarsfiles',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section for usage examples)
        // mimeType: '<value>' // Filter by mimeType
        // ownerId: '<value>' // Filter by ownerId
        // userId: '<value>' // Filter by userId
            }
  });

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the userAvatarsFiles object in the respones. However, some properties may be omitted based on the object’s internal logic.

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "userAvatarsFiles",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"userAvatarsFiles": [
		{
			"id": "ID",
			"fileName": "String",
			"mimeType": "String",
			"fileSize": "Integer",
			"accessKey": "String",
			"ownerId": "ID",
			"fileData": "Blob",
			"metadata": "Object",
			"userId": "ID",
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID",
			"isActive": true
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Business API Design Specification - Delete Useravatarsfile

Business API Design Specification - Delete Useravatarsfile

A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic.

While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized.

This document provides an in-depth explanation of the architectural design of the deleteUserAvatarsFile Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side.

Main Data Object and CRUD Operation

The deleteUserAvatarsFile Business API is designed to handle a delete operation on the UserAvatarsFile data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The deleteUserAvatarsFile Business API includes a REST controller that can be triggered via the following route:

/v1/useravatarsfiles/:userAvatarsFileId

By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the Parameters section.

MCP Tool

REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This deleteUserAvatarsFile Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The deleteUserAvatarsFile Business API has 1 parameter that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client.

Business API parameters can be:

Regular Parameters

Name Type Required Default Location Data Path
userAvatarsFileId ID Yes - urlpath userAvatarsFileId
Description: This id paremeter is used to select the required data object that will be deleted

Parameter Transformations

Some parameters are post-processed using transform scripts after being read from the request but before validation or workflow execution. Only parameters with a transform script are listed below.

No parameters are transformed in this API.

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the deleteUserAvatarsFile Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({id:this.userAvatarsFileId}), {"path":"services[0].businessLogic[16].whereClause.fullWhereClause"})

Delete Options

Use these options to set delete specific settings.

useSoftDelete: If true, the record will be marked as deleted (isActive: false) instead of removed. The implementation depends on the data object’s soft delete configuration.

Business Logic Workflow

[1] Step : startBusinessApi

Manager initializes context, prepares request/session objects, and sets up internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Manager reads and normalizes parameters, applies defaults, and stores them in the context for downstream steps.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Manager executes parameter transform scripts, computes derived values, and remaps objects or arrays as needed for later processing.


[4] Step : checkParameters

Manager runs built-in validations including required field checks, type enforcement, and deletion preconditions. Stops execution if validation fails.


[5] Step : checkBasicAuth

Manager validates session, user roles, permissions, and tenant-specific access rules to enforce basic auth restrictions.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildWhereClause

Manager generates the query conditions, applies ownership and parent checks, and ensures the clause is correct for the delete operation.

You can use the following settings to change some behavior of this step. whereClause

[7] Step : fetchInstance

Manager fetches the target record, applies filters from WHERE clause, and writes the instance to the context for further checks.


[8] Step : checkInstance

Manager performs object-level validations such as lock status, soft-delete eligibility, and multi-step approval enforcement.


[9] Step : mainDeleteOperation

Manager executes the delete query, updates related indexes/caches, and handles soft/hard delete logic according to configuration.

You can use the following settings to change some behavior of this step. deleteOptions

[10] Step : buildOutput

Manager shapes the response payload, masks sensitive fields, and formats related cleanup results for output.


[11] Step : sendResponse

Manager delivers the response to the client and finalizes any temporary internal structures.


[12] Step : raiseApiEvent

Manager triggers asynchronous API events, notifies queues or streams, and performs final cleanup for the workflow.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The deleteUserAvatarsFile api has got 1 regular client parameter

Parameter Type Required Population
userAvatarsFileId ID true request.params?.[“userAvatarsFileId”]

REST Request

To access the api you can use the REST controller with the path DELETE /v1/useravatarsfiles/:userAvatarsFileId

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

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the userAvatarsFile object in the respones. However, some properties may be omitted based on the object’s internal logic.

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "userAvatarsFile",
	"method": "DELETE",
	"action": "delete",
	"appVersion": "Version",
	"rowCount": 1,
	"userAvatarsFile": {
		"id": "ID",
		"fileName": "String",
		"mimeType": "String",
		"fileSize": "Integer",
		"accessKey": "String",
		"ownerId": "ID",
		"fileData": "Blob",
		"metadata": "Object",
		"userId": "ID",
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"isActive": false
	}
}

Database Buckets

Database Bucket Design Specification - userAvatars

Database Bucket Design Specification - userAvatars

This document provides a detailed architectural overview of the userAvatars database bucket within the auth service. It covers the bucket’s storage configuration, authorization model, endpoints, and optional owner DataObject pairing.

Bucket Overview

Description: User profile avatar images stored in the database.

A database bucket stores files as BYTEA columns in PostgreSQL. It is suited for small files such as icons, avatars, documents, and secret files.

Authorization

The bucket uses a layered authorization model for both read and write operations:

Read Access

Write Access

Key-Based Access

Owner DataObject

This bucket is paired with an owner DataObject for relational file management. Each uploaded file is linked to a record in the owner DataObject via a foreign key, enabling structured file ownership and access patterns.

REST Endpoints

The following endpoints are auto-generated for this bucket:

Method Path Description Auth
POST /bucket/userAvatars/upload Upload a file Authenticated
GET /bucket/userAvatars/download/:id Download a file by ID public
GET /bucket/userAvatars/download/key/:accessKey Download via access key Public
GET /bucket/userAvatars/meta/:id Get file metadata public
DELETE /bucket/userAvatars/:id Delete a file Authenticated

Upload Request

POST /bucket/userAvatars/upload
Content-Type: multipart/form-data

file: <binary file data>

The upload response returns the file metadata including the generated id and accessKey.

Download Response

The download endpoint returns the raw file bytes with the appropriate Content-Type header set from the stored MIME type.

Auto-Generated DataObject: userAvatarsFile

The bucket automatically generates a userAvatarsFile DataObject with metadata properties:

Property Type Description
id ID Unique file identifier (UUID)
fileName String Original file name
mimeType String MIME type of the file
fileSize Integer File size in bytes
accessKey String 12-character random access key for shareable links
createdAt Date Upload timestamp
ownerId ID User ID of uploader (from session)

Standard CRUD APIs are generated for the metadata object, allowing listing, filtering, and management of file records independently of the binary content.


This document was generated from the database bucket configuration and should be kept in sync with design changes.


Gameplay Service

Service Design Specification

Service Design Specification

wechess-gameplay-service documentation Version: 1.0.74

Scope

This document provides a structured architectural overview of the gameplay 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.

Gameplay Service Settings

Service for managing real-time chess games, matchmaking, move history, and private invitations, including lifecycle management (mutual game-save/resume, admin termination), supporting both guest and registered users. Enables API access for reviewing games, enforcing moderation actions, and tracking game results.

Service Overview

This service is configured to listen for HTTP requests on port 3000, 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 wechess-gameplay-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 wechess-gameplay-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
chessGame No description accessPrivate
chessGameMove Represents a single move in a chess game (FIDE-compliant SAN/LAN representation, timestamp, player, time, move number). accessPrivate
chessGameInvitation An invitation for a private chess game between two players; status tracked; expires at set time or when accepted/declined. accessPrivate
customBoard No description accessPrivate
boardTheme No description accessPrivate
userPreference No description accessPrivate
gameHubMessage Auto-generated message DataObject for the gameHub RealtimeHub. Stores all messages with typed content payloads. accessPrivate
gameHubModeration Auto-generated moderation DataObject for the gameHub RealtimeHub. Stores block and silence actions for room-level user moderation. accessPrivate

chessGame Data Object

Object Overview

Description: No description provided.

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
playerWhiteId ID Yes User ID of the player assigned White (guest or registered); references auth:user.id.
playerBlackId ID No -
createdById ID Yes ID of the user who created the game (can be a guest or registered user).
status Enum Yes Lifecycle status: pending, active, paused, completed, terminated
mode Enum Yes Game mode: public (matchmaking), private (invitation-based)
invitationCode String No -
currentFEN String Yes Current board state in FEN notation for restoration/resume.
gameType Enum Yes Game type: timed, untimed, blitz, rapid
saveStatus Enum Yes Game mutual-saving: notSaveable, requested, paused (both agreed)
saveRequestWhite Boolean No Whether white has requested save/resume; mutual save when both true.
saveRequestBlack Boolean No Whether black has requested save/resume; mutual save when both true.
movedAt Date No Timestamp of last move (heartbeat/game activity).
result Enum No Game result/outcome: whiteWin, blackWin, draw, aborted
terminatedById ID No ID of administrator who forced terminated the game (if applicable).
reportStatus Enum No Moderation/review status: none, reported, underReview
guestPlayerWhite Boolean No True if white is a guest (not a registered user); needed to distinguish guest/registered in history.
guestPlayerBlack Boolean No True if black is a guest (not a registered user); needed to distinguish guest/registered in history.
initialFEN String No The starting FEN position when the game was created. Used to identify custom games.

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

playerWhiteId createdById mode invitationCode gameType initialFEN

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

playerWhiteId playerBlackId createdById status mode invitationCode currentFEN gameType saveStatus saveRequestWhite saveRequestBlack movedAt result terminatedById reportStatus guestPlayerWhite guestPlayerBlack initialFEN

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

playerWhiteId playerBlackId createdById status mode invitationCode currentFEN gameType saveStatus saveRequestWhite saveRequestBlack movedAt result terminatedById reportStatus guestPlayerWhite guestPlayerBlack initialFEN

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

playerWhiteId playerBlackId createdById status mode invitationCode movedAt result

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

mode invitationCode

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

playerWhiteId playerBlackId createdById terminatedById

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

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

Filter Properties

status invitationCode

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.

chessGameMove Data Object

Object Overview

Description: Represents a single move in a chess game (FIDE-compliant SAN/LAN representation, timestamp, player, time, move number).

This object represents a core data structure within the service and acts as the blueprint for database interaction, API generation, and business logic enforcement. It is defined using the ObjectSettings pattern, which governs its behavior, access control, caching strategy, and integration points with other systems such as Stripe and Redis.

Core Configuration

Composite Indexes

The index also defines a conflict resolution strategy for duplicate key violations.

When a new record would violate this composite index, the following action will be taken:

On Duplicate: throwError

An error will be thrown, preventing the insertion of conflicting data.

Properties Schema

Display Label Property: moveNotation — This property is the default display label for records of this data object. Relation dropdowns and record references in the frontend will show the value of this property as the human-readable label.

Property Type Required Description
gameId ID Yes Reference to the chessGame this move belongs to.
moveNumber Integer Yes Move number (starting from 1 in each game).
moveNotation String Yes Chess move in either Standard Algebraic or Long Algebraic Notation (SAN/LAN).
moveTime Integer No Time in milliseconds since the previous move (for time control, etc.).
movedById ID Yes User ID of the player who made the move (guest/registered); references auth:user.id.
moveTimestamp Date Yes Timestamp when move was made.

Default Values

Default values are automatically assigned to properties when a new object is created, if no value is provided in the request body. Since default values are applied on db level, they should be literal values, not expressions.If you want to use expressions, you can use transposed parameters in any business API to set default values dynamically.

Constant Properties

gameId moveNumber moveNotation moveTime movedById moveTimestamp

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

gameId moveNumber moveNotation moveTime movedById moveTimestamp

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

gameId moveNumber moveNotation movedById moveTimestamp

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

gameId moveNumber moveTimestamp

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

gameId moveNumber

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

gameId movedById

Mindbricks supports relations between data objects, allowing you to define how objects are linked together. You can define relations in the data object properties, which will be used to create foreign key constraints in the database. For complex joins operations, Mindbricks supportsa BFF pattern, where you can view dynamic and static views based on Elastic Search Indexes. Use db level relations for simple one-to-one or one-to-many relationships, and use BFF views for complex joins that require multiple data objects to be joined together.

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

On Delete: Set Null Required: Yes

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

On Delete: Set Null Required: No

Filter Properties

gameId

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.

chessGameInvitation Data Object

Object Overview

Description: An invitation for a private chess game between two players; status tracked; expires at set time or when accepted/declined.

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
gameId ID Yes Game this invitation is linked to.
senderId ID Yes -
recipientId ID Yes -
status Enum Yes -
expiresAt Date Yes Expiration date/time for the invitation.

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

gameId

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

gameId senderId recipientId status expiresAt

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

gameId senderId recipientId status expiresAt

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

gameId senderId recipientId expiresAt

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

gameId

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

gameId senderId recipientId

Mindbricks supports relations between data objects, allowing you to define how objects are linked together. You can define relations in the data object properties, which will be used to create foreign key constraints in the database. For complex joins operations, Mindbricks supportsa BFF pattern, where you can view dynamic and static views based on Elastic Search Indexes. Use db level relations for simple one-to-one or one-to-many relationships, and use BFF views for complex joins that require multiple data objects to be joined together.

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

On Delete: Set Null Required: Yes

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

On Delete: Set Null Required: No

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

On Delete: Set Null Required: No

Filter Properties

senderId recipientId status

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

customBoard Data Object

Object Overview

Description: No description provided.

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

Display Label Property: name — This property is the default display label for records of this data object. Relation dropdowns and record references in the frontend will show the value of this property as the human-readable label.

Property Type Required Description
name String Yes Name of the custom board position
fen String Yes FEN string representing the board position
description Text No Optional description of the custom board
isPublished Boolean Yes -
category Enum Yes -
createdById ID Yes -

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

name fen description isPublished category createdById

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

name fen description isPublished category createdById

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 isPublished category createdById

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

createdById

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

isPublished category createdById

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.

boardTheme Data Object

Object Overview

Description: No description provided.

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

Display Label Property: name — This property is the default display label for records of this data object. Relation dropdowns and record references in the frontend will show the value of this property as the human-readable label.

Property Type Required Description
name String Yes Theme display name
lightSquare String Yes Hex color for light squares
darkSquare String Yes Hex color for dark squares
isPublished Boolean No Whether the theme is publicly visible
createdById ID Yes User who created this theme

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

createdById

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

name lightSquare darkSquare isPublished createdById

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

name lightSquare darkSquare isPublished createdById

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 isPublished createdById

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

createdById

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

isPublished

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.

userPreference Data Object

Object Overview

Description: No description provided.

This object represents a core data structure within the service and acts as the blueprint for database interaction, API generation, and business logic enforcement. It is defined using the ObjectSettings pattern, which governs its behavior, access control, caching strategy, and integration points with other systems such as Stripe and Redis.

Core Configuration

Properties Schema

Property Type Required Description
userId ID Yes The user this preferences record belongs to
activeThemeId String No ID of the currently selected board theme (preset ID or custom theme ID)
soundEnabled Boolean No Whether game sounds are enabled
showAnimations Boolean No Whether board animations are shown
boardOrientation Enum No Default board orientation preference
premoveEnabled Boolean No Whether premove feature is enabled

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

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

userId activeThemeId soundEnabled showAnimations boardOrientation premoveEnabled

An update crud API created with the option Auto Params enabled will automatically update these properties with the provided values in the request body. If you want to update any property in your own business logic not by user input, you can set the Allow Auto Update option to false. These properties will be added to the update API’s body parameters and can be updated by the user if any value is provided in the request body.

Enum Properties

Enum properties are defined with a set of allowed values, ensuring that only valid options can be assigned to them. The enum options value will be stored as strings in the database, but when a data object is created an addtional property with the same name plus an idx suffix will be created, which will hold the index of the selected enum option. You can use the index property to sort by the enum value or when your enum options represent a sequence of values.

Elastic Search Indexing

userId activeThemeId soundEnabled showAnimations boardOrientation premoveEnabled

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

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

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.

Relation Properties

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

gameHubMessage Data Object

Object Overview

Description: Auto-generated message DataObject for the gameHub RealtimeHub. Stores all messages with typed content payloads.

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
roomId ID Yes Reference to the room this message belongs to
senderId ID No Reference to the user who sent this message
senderName String No Display name of the sender (denormalized from user profile at send time)
senderAvatar String No Avatar URL of the sender (denormalized from user profile at send time)
messageType Enum Yes Content type discriminator for this message
content Object Yes Type-specific content payload (structure depends on messageType)
timestamp No Message creation time
status Enum No Message moderation status

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

roomId senderId senderName senderAvatar messageType timestamp

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

roomId senderId senderName senderAvatar messageType content timestamp status

An update crud API created with the option Auto Params enabled will automatically update these properties with the provided values in the request body. If you want to update any property in your own business logic not by user input, you can set the Allow Auto Update option to false. These properties will be added to the update API’s body parameters and can be updated by the user if any value is provided in the request body.

Enum Properties

Enum properties are defined with a set of allowed values, ensuring that only valid options can be assigned to them. The enum options value will be stored as strings in the database, but when a data object is created an addtional property with the same name plus an idx suffix will be created, which will hold the index of the selected enum option. You can use the index property to sort by the enum value or when your enum options represent a sequence of values.

Elastic Search Indexing

roomId senderId senderName senderAvatar messageType content timestamp status

Properties that are indexed in Elastic Search will be searchable via the Elastic Search API. While all properties are stored in the elastic search index of the data object, only those marked for Elastic Search indexing will be available for search queries.

Database Indexing

roomId senderId senderName senderAvatar messageType content timestamp status

Properties that are indexed in the database will be optimized for query performance, allowing for faster data retrieval. Make a property indexed in the database if you want to use it frequently in query filters or sorting.

Secondary Key Properties

roomId

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

senderId

Session data properties are used to store data that is specific to the user session, allowing for personalized experiences and temporary data storage. If a property is configured as session data, it will be automatically mapped to the related field in the user session during CRUD operations. Note that session data properties can not be mutated by the user, but only by the system.

Filter Properties

roomId senderId senderName senderAvatar messageType content timestamp status

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

gameHubModeration Data Object

Object Overview

Description: Auto-generated moderation DataObject for the gameHub RealtimeHub. Stores block and silence actions for room-level user moderation.

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
roomId ID Yes Reference to the room where the moderation action applies
userId ID Yes The user who is blocked or silenced
action Enum Yes Moderation action type
reason Text No Optional reason for the moderation action
duration Integer No Duration in seconds. 0 means permanent
expiresAt No Expiry timestamp. Null means permanent
issuedBy ID No The moderator who issued the action

Default Values

Default values are automatically assigned to properties when a new object is created, if no value is provided in the request body. Since default values are applied on db level, they should be literal values, not expressions.If you want to use expressions, you can use transposed parameters in any business API to set default values dynamically.

Constant Properties

roomId userId action duration expiresAt issuedBy

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

roomId userId action reason duration expiresAt issuedBy

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

roomId userId action reason duration expiresAt issuedBy

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

roomId userId action reason duration expiresAt issuedBy

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

roomId userId

Secondary key properties are used to create an additional indexed identifiers for the data object, allowing for alternative access patterns. Different than normal indexed properties, secondary keys will act as primary keys and Mindbricks will provide automatic secondary key db utility functions to access the data object by the secondary key.

Relation Properties

roomId

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

issuedBy

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

roomId userId action reason duration expiresAt issuedBy

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

gameplay has got 28 Business APIs to manage its internal and crud logic. For the details of each business API refer to its chapter.

Realtime Hubs

gameplay has 1 Realtime Hub configured. Each hub provides bidirectional communication powered by Socket.IO with room-based messaging, built-in and custom message types, and auto-generated REST endpoints.

Hub Name Namespace Room DataObject Roles
gameHub /hub/gameHub chessGame player

For detailed documentation on each hub, refer to:

Service Library

Functions

processGameResult.js

const { interserviceCall } = require("serviceCommon");

/**
 * Mindbricks interservice calls return the same envelope as REST (e.g. { playerStats: {...} }).
 * Unwrap so we read id, eloRating, wins, etc. from the actual row.
 */
function unwrapPlayerStats(res) {
  if (res == null || typeof res !== "object") return null;
  const inner = res.playerStats;
  if (inner && typeof inner === "object" && inner.id) return inner;
  if (res.id && res.userId) return res;
  return null;
}

/**
 * Processes a completed/terminated chess game result:
 * - Computes ELO changes for both players
 * - Calls leaderboard service to update playerStats for registered (non-guest) players
 * - Calls leaderboard service to update leaderboardEntry eloRating and rank
 *
 * @param {object} context - The API context (this)
 */
module.exports = async function processGameResult(context) {
  const game = context.chessGame;
  const updatedFields = context;

  const status = updatedFields.status || game.status;
  const result = updatedFields.result || game.result;

  if (!["completed", "terminated"].includes(status) || !result) {
    return null;
  }

  if (result === "aborted") {
    return null;
  }

  const playerWhiteId = game.playerWhiteId;
  const playerBlackId = game.playerBlackId;
  const isWhiteGuest = game.guestPlayerWhite === true;
  const isBlackGuest = game.guestPlayerBlack === true;

  let whiteOutcome;
  let blackOutcome;
  if (result === "whiteWin") {
    whiteOutcome = "win";
    blackOutcome = "loss";
  } else if (result === "blackWin") {
    whiteOutcome = "loss";
    blackOutcome = "win";
  } else if (result === "draw") {
    whiteOutcome = "draw";
    blackOutcome = "draw";
  } else {
    return null;
  }

  let whiteStats = null;
  let blackStats = null;

  if (!isWhiteGuest && playerWhiteId) {
    try {
      const raw = await interserviceCall("leaderboard", "getPlayerStats", { userId: playerWhiteId });
      whiteStats = unwrapPlayerStats(raw);
    } catch (e) {
      /* player may not have stats yet */
    }
  }
  if (!isBlackGuest && playerBlackId) {
    try {
      const raw = await interserviceCall("leaderboard", "getPlayerStats", { userId: playerBlackId });
      blackStats = unwrapPlayerStats(raw);
    } catch (e) {
      /* player may not have stats yet */
    }
  }

  const whiteElo = whiteStats ? (Number(whiteStats.eloRating) || 1200) : 1200;
  const blackElo = blackStats ? (Number(blackStats.eloRating) || 1200) : 1200;

  const K = 32;
  const expectedWhite = 1 / (1 + Math.pow(10, (blackElo - whiteElo) / 400));
  const expectedBlack = 1 / (1 + Math.pow(10, (whiteElo - blackElo) / 400));

  let actualWhite;
  let actualBlack;
  if (result === "whiteWin") {
    actualWhite = 1;
    actualBlack = 0;
  } else if (result === "blackWin") {
    actualWhite = 0;
    actualBlack = 1;
  } else {
    actualWhite = 0.5;
    actualBlack = 0.5;
  }

  const newWhiteElo = Math.round(whiteElo + K * (actualWhite - expectedWhite));
  const newBlackElo = Math.round(blackElo + K * (actualBlack - expectedBlack));

  const now = new Date().toISOString();

  function buildUpdatePayload(stats, outcome, newElo) {
    const wins = (stats ? stats.wins : 0) + (outcome === "win" ? 1 : 0);
    const losses = (stats ? stats.losses : 0) + (outcome === "loss" ? 1 : 0);
    const draws = (stats ? stats.draws : 0) + (outcome === "draw" ? 1 : 0);
    const totalGames = wins + losses + draws;
    let streak = stats ? stats.streak : 0;
    if (outcome === "win") streak = streak > 0 ? streak + 1 : 1;
    else if (outcome === "loss") streak = streak < 0 ? streak - 1 : -1;
    else streak = 0;
    return { eloRating: newElo, totalGames, wins, losses, draws, streak, lastGameAt: now };
  }

  if (!isWhiteGuest && playerWhiteId && whiteStats) {
    try {
      const payload = buildUpdatePayload(whiteStats, whiteOutcome, newWhiteElo);
      await interserviceCall("leaderboard", "updatePlayerStats", { id: whiteStats.id, ...payload });
    } catch (e) {
      console.error("Failed to update white player stats:", e.message);
    }
  }

  if (!isBlackGuest && playerBlackId && blackStats) {
    try {
      const payload = buildUpdatePayload(blackStats, blackOutcome, newBlackElo);
      await interserviceCall("leaderboard", "updatePlayerStats", { id: blackStats.id, ...payload });
    } catch (e) {
      console.error("Failed to update black player stats:", e.message);
    }
  }

  return { whiteElo: newWhiteElo, blackElo: newBlackElo, result };
};

This document was generated from the service architecture definition and should be kept in sync with implementation changes.


REST API GUIDE

REST API GUIDE

wechess-gameplay-service

Version: 1.0.74

Service for managing real-time chess games, matchmaking, move history, and private invitations, including lifecycle management (mutual game-save/resume, admin termination), supporting both guest and registered users. Enables API access for reviewing games, enforcing moderation actions, and tracking game results.

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 Gameplay Service’s REST API. This document is designed to provide a comprehensive guide to interfacing with our Gameplay Service exclusively through RESTful API endpoints.

Intended Audience

This documentation is intended for developers and integrators who are looking to interact with the Gameplay Service via HTTP requests for purposes such as creating, updating, deleting and querying Gameplay 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 Gameplay 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 Gameplay 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 wechess-access-token
Cookie wechess-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 Gameplay 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 Gameplay service.

This service is configured to listen for HTTP requests on port 3000, 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 Gameplay 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 Gameplay 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 Gameplay 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 Gameplay 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

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

ChessGame resource

ChessGame Resource Properties

Name Type Required Default Definition
playerWhiteId ID User ID of the player assigned White (guest or registered); references auth:user.id.
playerBlackId ID **
createdById ID ID of the user who created the game (can be a guest or registered user).
status Enum Lifecycle status: pending, active, paused, completed, terminated
mode Enum Game mode: public (matchmaking), private (invitation-based)
invitationCode String **
currentFEN String Current board state in FEN notation for restoration/resume.
gameType Enum Game type: timed, untimed, blitz, rapid
saveStatus Enum Game mutual-saving: notSaveable, requested, paused (both agreed)
saveRequestWhite Boolean Whether white has requested save/resume; mutual save when both true.
saveRequestBlack Boolean Whether black has requested save/resume; mutual save when both true.
movedAt Date Timestamp of last move (heartbeat/game activity).
result Enum Game result/outcome: whiteWin, blackWin, draw, aborted
terminatedById ID ID of administrator who forced terminated the game (if applicable).
reportStatus Enum Moderation/review status: none, reported, underReview
guestPlayerWhite Boolean True if white is a guest (not a registered user); needed to distinguish guest/registered in history.
guestPlayerBlack Boolean True if black is a guest (not a registered user); needed to distinguish guest/registered in history.
initialFEN String The starting FEN position when the game was created. Used to identify custom games.

Enum Properties

Enum properties are represented as strings in the database. The values are mapped to their corresponding names in the application layer.

status Enum Property

Property Definition : Lifecycle status: pending, active, paused, completed, terminatedEnum Options

Name Value Index
pending "pending"" 0
active "active"" 1
paused "paused"" 2
completed "completed"" 3
terminated "terminated"" 4
mode Enum Property

Property Definition : Game mode: public (matchmaking), private (invitation-based)Enum Options

Name Value Index
public "public"" 0
private "private"" 1
gameType Enum Property

Property Definition : Game type: timed, untimed, blitz, rapidEnum Options

Name Value Index
timed "timed"" 0
untimed "untimed"" 1
blitz "blitz"" 2
rapid "rapid"" 3
saveStatus Enum Property

Property Definition : Game mutual-saving: notSaveable, requested, paused (both agreed)Enum Options

Name Value Index
notSaveable "notSaveable"" 0
requested "requested"" 1
paused "paused"" 2
result Enum Property

Property Definition : Game result/outcome: whiteWin, blackWin, draw, abortedEnum Options

Name Value Index
whiteWin "whiteWin"" 0
blackWin "blackWin"" 1
draw "draw"" 2
aborted "aborted"" 3
reportStatus Enum Property

Property Definition : Moderation/review status: none, reported, underReviewEnum Options

Name Value Index
none "none"" 0
reported "reported"" 1
underReview "underReview"" 2

ChessGameMove resource

Resource Definition : Represents a single move in a chess game (FIDE-compliant SAN/LAN representation, timestamp, player, time, move number). ChessGameMove Resource Properties

Name Type Required Default Definition
gameId ID Reference to the chessGame this move belongs to.
moveNumber Integer Move number (starting from 1 in each game).
moveNotation String Chess move in either Standard Algebraic or Long Algebraic Notation (SAN/LAN).
moveTime Integer Time in milliseconds since the previous move (for time control, etc.).
movedById ID User ID of the player who made the move (guest/registered); references auth:user.id.
moveTimestamp Date Timestamp when move was made.

ChessGameInvitation resource

Resource Definition : An invitation for a private chess game between two players; status tracked; expires at set time or when accepted/declined. ChessGameInvitation Resource Properties

Name Type Required Default Definition
gameId ID Game this invitation is linked to.
senderId ID **
recipientId ID **
status Enum **
expiresAt Date Expiration date/time for the invitation.

Enum Properties

Enum properties are represented as strings in the database. The values are mapped to their corresponding names in the application layer.

status Enum Property

Enum Options

Name Value Index
pending "pending"" 0
accepted "accepted"" 1
declined "declined"" 2
cancelled "cancelled"" 3

CustomBoard resource

CustomBoard Resource Properties

Name Type Required Default Definition
name String Name of the custom board position
fen String FEN string representing the board position
description Text Optional description of the custom board
isPublished Boolean **
category Enum **
createdById ID **

Enum Properties

Enum properties are represented as strings in the database. The values are mapped to their corresponding names in the application layer.

category Enum Property

Enum Options

Name Value Index
endgame "endgame"" 0
opening "opening"" 1
puzzle "puzzle"" 2
custom "custom"" 3

BoardTheme resource

BoardTheme Resource Properties

Name Type Required Default Definition
name String Theme display name
lightSquare String Hex color for light squares
darkSquare String Hex color for dark squares
isPublished Boolean Whether the theme is publicly visible
createdById ID User who created this theme

UserPreference resource

UserPreference Resource Properties

Name Type Required Default Definition
userId ID The user this preferences record belongs to
activeThemeId String ID of the currently selected board theme (preset ID or custom theme ID)
soundEnabled Boolean Whether game sounds are enabled
showAnimations Boolean Whether board animations are shown
boardOrientation Enum Default board orientation preference
premoveEnabled Boolean Whether premove feature is enabled

Enum Properties

Enum properties are represented as strings in the database. The values are mapped to their corresponding names in the application layer.

boardOrientation Enum Property

Property Definition : Default board orientation preferenceEnum Options

Name Value Index
auto "auto"" 0
white "white"" 1
black "black"" 2

GameHubMessage resource

Resource Definition : Auto-generated message DataObject for the gameHub RealtimeHub. Stores all messages with typed content payloads. GameHubMessage Resource Properties

Name Type Required Default Definition
roomId ID Reference to the room this message belongs to
senderId ID Reference to the user who sent this message
senderName String Display name of the sender (denormalized from user profile at send time)
senderAvatar String Avatar URL of the sender (denormalized from user profile at send time)
messageType Enum Content type discriminator for this message
content Object Type-specific content payload (structure depends on messageType)
timestamp Message creation time
status Enum Message moderation status

Enum Properties

Enum properties are represented as strings in the database. The values are mapped to their corresponding names in the application layer.

messageType Enum Property

Property Definition : Content type discriminator for this messageEnum Options

Name Value Index
text "text"" 0
system "system"" 1
chessMove "chessMove"" 2
drawOffer "drawOffer"" 3
drawAccepted "drawAccepted"" 4
drawDeclined "drawDeclined"" 5
resignation "resignation"" 6
saveRequest "saveRequest"" 7
saveAccepted "saveAccepted"" 8
saveDeclined "saveDeclined"" 9
resumeRequest "resumeRequest"" 10
resumeAccepted "resumeAccepted"" 11
resumeDeclined "resumeDeclined"" 12
status Enum Property

Property Definition : Message moderation statusEnum Options

Name Value Index
pending "pending"" 0
approved "approved"" 1
rejected "rejected"" 2

GameHubModeration resource

Resource Definition : Auto-generated moderation DataObject for the gameHub RealtimeHub. Stores block and silence actions for room-level user moderation. GameHubModeration Resource Properties

Name Type Required Default Definition
roomId ID Reference to the room where the moderation action applies
userId ID The user who is blocked or silenced
action Enum Moderation action type
reason Text Optional reason for the moderation action
duration Integer Duration in seconds. 0 means permanent
expiresAt Expiry timestamp. Null means permanent
issuedBy ID The moderator who issued the action

Enum Properties

Enum properties are represented as strings in the database. The values are mapped to their corresponding names in the application layer.

action Enum Property

Property Definition : Moderation action typeEnum Options

Name Value Index
blocked "blocked"" 0
silenced "silenced"" 1

Business Api

Create Game API

[Default create API] — This is the designated default create API for the chessGame data object. Frontend generators and AI agents should use this API for standard CRUD operations. Starts a new chess game session (public or private). Sets up all initial state, assigns player roles, and sets mode.

API Frontend Description By The Backend Architect

Called when matchmaking or private game is created. Invited/private games have invitationCode. Only logged-in users (guest or registered) can create games. Raise event for gameCreated for notification/bff.

Rest Route

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

/v1/game

Rest Request Parameters

The createGame api has got 18 regular request parameters

Parameter Type Required Population
playerWhiteId ID true request.body?.[“playerWhiteId”]
playerBlackId ID false request.body?.[“playerBlackId”]
createdById ID true request.body?.[“createdById”]
status Enum true request.body?.[“status”]
mode Enum true request.body?.[“mode”]
invitationCode String false request.body?.[“invitationCode”]
currentFEN String true request.body?.[“currentFEN”]
gameType Enum true request.body?.[“gameType”]
saveStatus Enum true request.body?.[“saveStatus”]
saveRequestWhite Boolean false request.body?.[“saveRequestWhite”]
saveRequestBlack Boolean false request.body?.[“saveRequestBlack”]
movedAt Date false request.body?.[“movedAt”]
result Enum false request.body?.[“result”]
terminatedById ID false request.body?.[“terminatedById”]
reportStatus Enum false request.body?.[“reportStatus”]
guestPlayerWhite Boolean false request.body?.[“guestPlayerWhite”]
guestPlayerBlack Boolean false request.body?.[“guestPlayerBlack”]
initialFEN String false request.body?.[“initialFEN”]
playerWhiteId : User ID of the player assigned White (guest or registered); references auth:user.id.
playerBlackId :
createdById : ID of the user who created the game (can be a guest or registered user).
status : Lifecycle status: pending, active, paused, completed, terminated
mode : Game mode: public (matchmaking), private (invitation-based)
invitationCode :
currentFEN : Current board state in FEN notation for restoration/resume.
gameType : Game type: timed, untimed, blitz, rapid
saveStatus : Game mutual-saving: notSaveable, requested, paused (both agreed)
saveRequestWhite : Whether white has requested save/resume; mutual save when both true.
saveRequestBlack : Whether black has requested save/resume; mutual save when both true.
movedAt : Timestamp of last move (heartbeat/game activity).
result : Game result/outcome: whiteWin, blackWin, draw, aborted
terminatedById : ID of administrator who forced terminated the game (if applicable).
reportStatus : Moderation/review status: none, reported, underReview
guestPlayerWhite : True if white is a guest (not a registered user); needed to distinguish guest/registered in history.
guestPlayerBlack : True if black is a guest (not a registered user); needed to distinguish guest/registered in history.
initialFEN : The starting FEN position when the game was created. Used to identify custom games.

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

  axios({
    method: 'POST',
    url: '/v1/game',
    data: {
            playerWhiteId:"ID",  
            playerBlackId:"ID",  
            createdById:"ID",  
            status:"Enum",  
            mode:"Enum",  
            invitationCode:"String",  
            currentFEN:"String",  
            gameType:"Enum",  
            saveStatus:"Enum",  
            saveRequestWhite:"Boolean",  
            saveRequestBlack:"Boolean",  
            movedAt:"Date",  
            result:"Enum",  
            terminatedById:"ID",  
            reportStatus:"Enum",  
            guestPlayerWhite:"Boolean",  
            guestPlayerBlack:"Boolean",  
            initialFEN:"String",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "chessGame",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"chessGame": {
		"id": "ID",
		"playerWhiteId": "ID",
		"playerBlackId": "ID",
		"createdById": "ID",
		"status": "Enum",
		"status_idx": "Integer",
		"mode": "Enum",
		"mode_idx": "Integer",
		"invitationCode": "String",
		"currentFEN": "String",
		"gameType": "Enum",
		"gameType_idx": "Integer",
		"saveStatus": "Enum",
		"saveStatus_idx": "Integer",
		"saveRequestWhite": "Boolean",
		"saveRequestBlack": "Boolean",
		"movedAt": "Date",
		"result": "Enum",
		"result_idx": "Integer",
		"terminatedById": "ID",
		"reportStatus": "Enum",
		"reportStatus_idx": "Integer",
		"guestPlayerWhite": "Boolean",
		"guestPlayerBlack": "Boolean",
		"initialFEN": "String",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Update Game API

[Default update API] — This is the designated default update API for the chessGame data object. Frontend generators and AI agents should use this API for standard CRUD operations. Updates chess game state including board position, status, save flags etc. Auth: only participants or admin.

API Frontend Description By The Backend Architect

Used for updating board state, status, mutual saving, etc. Most fields are read-only after game completion/termination except by admin. Raise event for gameUpdated for notification/bff.

Rest Route

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

/v1/game/:chessGameId

Rest Request Parameters

The updateGame api has got 13 regular request parameters

Parameter Type Required Population
chessGameId ID true request.params?.[“chessGameId”]
playerBlackId ID request.body?.[“playerBlackId”]
status Enum false request.body?.[“status”]
currentFEN String false request.body?.[“currentFEN”]
saveStatus Enum false request.body?.[“saveStatus”]
saveRequestWhite Boolean false request.body?.[“saveRequestWhite”]
saveRequestBlack Boolean false request.body?.[“saveRequestBlack”]
movedAt Date false request.body?.[“movedAt”]
result Enum false request.body?.[“result”]
terminatedById ID false request.body?.[“terminatedById”]
reportStatus Enum false request.body?.[“reportStatus”]
guestPlayerWhite Boolean false request.body?.[“guestPlayerWhite”]
guestPlayerBlack Boolean false request.body?.[“guestPlayerBlack”]
chessGameId : This id paremeter is used to select the required data object that will be updated
playerBlackId :
status : Lifecycle status: pending, active, paused, completed, terminated
currentFEN : Current board state in FEN notation for restoration/resume.
saveStatus : Game mutual-saving: notSaveable, requested, paused (both agreed)
saveRequestWhite : Whether white has requested save/resume; mutual save when both true.
saveRequestBlack : Whether black has requested save/resume; mutual save when both true.
movedAt : Timestamp of last move (heartbeat/game activity).
result : Game result/outcome: whiteWin, blackWin, draw, aborted
terminatedById : ID of administrator who forced terminated the game (if applicable).
reportStatus : Moderation/review status: none, reported, underReview
guestPlayerWhite : True if white is a guest (not a registered user); needed to distinguish guest/registered in history.
guestPlayerBlack : True if black is a guest (not a registered user); needed to distinguish guest/registered in history.

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

  axios({
    method: 'PATCH',
    url: `/v1/game/${chessGameId}`,
    data: {
            playerBlackId:"ID",  
            status:"Enum",  
            currentFEN:"String",  
            saveStatus:"Enum",  
            saveRequestWhite:"Boolean",  
            saveRequestBlack:"Boolean",  
            movedAt:"Date",  
            result:"Enum",  
            terminatedById:"ID",  
            reportStatus:"Enum",  
            guestPlayerWhite:"Boolean",  
            guestPlayerBlack:"Boolean",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "chessGame",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"chessGame": {
		"id": "ID",
		"playerWhiteId": "ID",
		"playerBlackId": "ID",
		"createdById": "ID",
		"status": "Enum",
		"status_idx": "Integer",
		"mode": "Enum",
		"mode_idx": "Integer",
		"invitationCode": "String",
		"currentFEN": "String",
		"gameType": "Enum",
		"gameType_idx": "Integer",
		"saveStatus": "Enum",
		"saveStatus_idx": "Integer",
		"saveRequestWhite": "Boolean",
		"saveRequestBlack": "Boolean",
		"movedAt": "Date",
		"result": "Enum",
		"result_idx": "Integer",
		"terminatedById": "ID",
		"reportStatus": "Enum",
		"reportStatus_idx": "Integer",
		"guestPlayerWhite": "Boolean",
		"guestPlayerBlack": "Boolean",
		"initialFEN": "String",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Delete Game API

[Default delete API] — This is the designated default delete API for the chessGame data object. Frontend generators and AI agents should use this API for standard CRUD operations. Deletes a chess game (soft-delete). Only allowed for admins or system cleanup.

API Frontend Description By The Backend Architect

Hard deletion not recommended; soft-deletion disables user/game access. Used for moderation/cleanup only. Regular users cannot delete games. Raise event for gameDeleted for moderation/audit.

Rest Route

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

/v1/game/:chessGameId

Rest Request Parameters

The deleteGame api has got 1 regular request parameter

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

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

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "chessGame",
	"method": "DELETE",
	"action": "delete",
	"appVersion": "Version",
	"rowCount": 1,
	"chessGame": {
		"id": "ID",
		"playerWhiteId": "ID",
		"playerBlackId": "ID",
		"createdById": "ID",
		"status": "Enum",
		"status_idx": "Integer",
		"mode": "Enum",
		"mode_idx": "Integer",
		"invitationCode": "String",
		"currentFEN": "String",
		"gameType": "Enum",
		"gameType_idx": "Integer",
		"saveStatus": "Enum",
		"saveStatus_idx": "Integer",
		"saveRequestWhite": "Boolean",
		"saveRequestBlack": "Boolean",
		"movedAt": "Date",
		"result": "Enum",
		"result_idx": "Integer",
		"terminatedById": "ID",
		"reportStatus": "Enum",
		"reportStatus_idx": "Integer",
		"guestPlayerWhite": "Boolean",
		"guestPlayerBlack": "Boolean",
		"initialFEN": "String",
		"isActive": false,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Get Game API

[Default get API] — This is the designated default get API for the chessGame data object. Frontend generators and AI agents should use this API for standard CRUD operations. Fetch a single chess game by ID. Only participants, admin, or invitation recipient may access.

API Frontend Description By The Backend Architect

Retrieve all game details and limited move history for preview/study. If user is not participant, must check invitation. Raise event for gameFetched.

Rest Route

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

/v1/game/:chessGameId

Rest Request Parameters

The getGame api has got 1 regular request parameter

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

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

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "chessGame",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"chessGame": {
		"id": "ID",
		"playerWhiteId": "ID",
		"playerBlackId": "ID",
		"createdById": "ID",
		"status": "Enum",
		"status_idx": "Integer",
		"mode": "Enum",
		"mode_idx": "Integer",
		"invitationCode": "String",
		"currentFEN": "String",
		"gameType": "Enum",
		"gameType_idx": "Integer",
		"saveStatus": "Enum",
		"saveStatus_idx": "Integer",
		"saveRequestWhite": "Boolean",
		"saveRequestBlack": "Boolean",
		"movedAt": "Date",
		"result": "Enum",
		"result_idx": "Integer",
		"terminatedById": "ID",
		"reportStatus": "Enum",
		"reportStatus_idx": "Integer",
		"guestPlayerWhite": "Boolean",
		"guestPlayerBlack": "Boolean",
		"initialFEN": "String",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"moves": [
			{
				"moveNumber": "Integer",
				"moveNotation": "String",
				"moveTime": "Integer",
				"movedById": "ID",
				"moveTimestamp": "Date"
			},
			{},
			{}
		]
	}
}

List Games API

[Default list API] — This is the designated default list API for the chessGame data object. Frontend generators and AI agents should use this API for standard CRUD operations. List chess games by participant or admin query. Supports filtering by status, participants, mode, etc.

API Frontend Description By The Backend Architect

Used for history browsing, admin review, or finding ongoing/mutually saved games. Raise event for gameListFetched for audit/UX.

Rest Route

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

/v1/games

Rest Request Parameters

Filter Parameters

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

status (Enum): Lifecycle status: pending, active, paused, completed, terminated

invitationCode (String): Filter by invitationCode

REST Request To access the api you can use the REST controller with the path GET /v1/games

  axios({
    method: 'GET',
    url: '/v1/games',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section above)
        // status: '<value>' // Filter by status
        // invitationCode: '<value>' // Filter by invitationCode
            }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "chessGames",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"chessGames": [
		{
			"id": "ID",
			"playerWhiteId": "ID",
			"playerBlackId": "ID",
			"createdById": "ID",
			"status": "Enum",
			"status_idx": "Integer",
			"mode": "Enum",
			"mode_idx": "Integer",
			"invitationCode": "String",
			"currentFEN": "String",
			"gameType": "Enum",
			"gameType_idx": "Integer",
			"saveStatus": "Enum",
			"saveStatus_idx": "Integer",
			"saveRequestWhite": "Boolean",
			"saveRequestBlack": "Boolean",
			"movedAt": "Date",
			"result": "Enum",
			"result_idx": "Integer",
			"terminatedById": "ID",
			"reportStatus": "Enum",
			"reportStatus_idx": "Integer",
			"guestPlayerWhite": "Boolean",
			"guestPlayerBlack": "Boolean",
			"initialFEN": "String",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID"
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Create Gamemove API

[Default create API] — This is the designated default create API for the chessGameMove data object. Frontend generators and AI agents should use this API for standard CRUD operations. Record a move in an ongoing chess game. Only participants or admin can add moves.

API Frontend Description By The Backend Architect

Called in-order for each legitimate move. Ensures move sequence is preserved. Move time and timestamp acquired on submit. Raises event for moveAdded.

Rest Route

The createGameMove API REST controller can be triggered via the following route:

/v1/gamemove

Rest Request Parameters

The createGameMove api has got 6 regular request parameters

Parameter Type Required Population
gameId ID true request.body?.[“gameId”]
moveNumber Integer true request.body?.[“moveNumber”]
moveNotation String true request.body?.[“moveNotation”]
moveTime Integer false request.body?.[“moveTime”]
movedById ID true request.body?.[“movedById”]
moveTimestamp Date true request.body?.[“moveTimestamp”]
gameId : Reference to the chessGame this move belongs to.
moveNumber : Move number (starting from 1 in each game).
moveNotation : Chess move in either Standard Algebraic or Long Algebraic Notation (SAN/LAN).
moveTime : Time in milliseconds since the previous move (for time control, etc.).
movedById : User ID of the player who made the move (guest/registered); references auth:user.id.
moveTimestamp : Timestamp when move was made.

REST Request To access the api you can use the REST controller with the path POST /v1/gamemove

  axios({
    method: 'POST',
    url: '/v1/gamemove',
    data: {
            gameId:"ID",  
            moveNumber:"Integer",  
            moveNotation:"String",  
            moveTime:"Integer",  
            movedById:"ID",  
            moveTimestamp:"Date",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "chessGameMove",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"chessGameMove": {
		"id": "ID",
		"gameId": "ID",
		"moveNumber": "Integer",
		"moveNotation": "String",
		"moveTime": "Integer",
		"movedById": "ID",
		"moveTimestamp": "Date",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

List Gamemoves API

[Default list API] — This is the designated default list API for the chessGameMove data object. Frontend generators and AI agents should use this API for standard CRUD operations. List moves for a given game. Only participants or admin can view.

API Frontend Description By The Backend Architect

Used for reviewing game history/study. Returns moves ordered by moveNumber asc.

Rest Route

The listGameMoves API REST controller can be triggered via the following route:

/v1/gamemoves

Rest Request Parameters

Filter Parameters

The listGameMoves api supports 1 optional filter parameter for filtering list results:

gameId (ID): Reference to the chessGame this move belongs to.

REST Request To access the api you can use the REST controller with the path GET /v1/gamemoves

  axios({
    method: 'GET',
    url: '/v1/gamemoves',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section above)
        // gameId: '<value>' // Filter by gameId
            }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "chessGameMoves",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"chessGameMoves": [
		{
			"id": "ID",
			"gameId": "ID",
			"moveNumber": "Integer",
			"moveNotation": "String",
			"moveTime": "Integer",
			"movedById": "ID",
			"moveTimestamp": "Date",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID"
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Create Gameinvitation API

[Default create API] — This is the designated default create API for the chessGameInvitation data object. Frontend generators and AI agents should use this API for standard CRUD operations. Send an invitation for a private chess game to a user (guest or registered).

API Frontend Description By The Backend Architect

Used for starting private games. Invitation auto-invalidates on expiry. Raise event for invitationSent for notification.

Rest Route

The createGameInvitation API REST controller can be triggered via the following route:

/v1/gameinvitation

Rest Request Parameters

The createGameInvitation api has got 5 regular request parameters

Parameter Type Required Population
gameId ID true request.body?.[“gameId”]
senderId ID true request.body?.[“senderId”]
recipientId ID true request.body?.[“recipientId”]
status Enum true request.body?.[“status”]
expiresAt Date true request.body?.[“expiresAt”]
gameId : Game this invitation is linked to.
senderId :
recipientId :
status :
expiresAt : Expiration date/time for the invitation.

REST Request To access the api you can use the REST controller with the path POST /v1/gameinvitation

  axios({
    method: 'POST',
    url: '/v1/gameinvitation',
    data: {
            gameId:"ID",  
            senderId:"ID",  
            recipientId:"ID",  
            status:"Enum",  
            expiresAt:"Date",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "chessGameInvitation",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"chessGameInvitation": {
		"id": "ID",
		"gameId": "ID",
		"senderId": "ID",
		"recipientId": "ID",
		"status": "Enum",
		"status_idx": "Integer",
		"expiresAt": "Date",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Update Gameinvitation API

[Default update API] — This is the designated default update API for the chessGameInvitation data object. Frontend generators and AI agents should use this API for standard CRUD operations. Update the status or expiry of a game invitation (accept, decline, cancel, expire). Only sender, recipient, or admin can change status.

API Frontend Description By The Backend Architect

Used for invitation workflow (accept, decline, cancel); handled securely as only involved users or admin can update. Event is raised for notification.

Rest Route

The updateGameInvitation API REST controller can be triggered via the following route:

/v1/gameinvitation/:chessGameInvitationId

Rest Request Parameters

The updateGameInvitation api has got 5 regular request parameters

Parameter Type Required Population
chessGameInvitationId ID true request.params?.[“chessGameInvitationId”]
senderId ID request.body?.[“senderId”]
recipientId ID request.body?.[“recipientId”]
status Enum request.body?.[“status”]
expiresAt Date false request.body?.[“expiresAt”]
chessGameInvitationId : This id paremeter is used to select the required data object that will be updated
senderId :
recipientId :
status :
expiresAt : Expiration date/time for the invitation.

REST Request To access the api you can use the REST controller with the path PATCH /v1/gameinvitation/:chessGameInvitationId

  axios({
    method: 'PATCH',
    url: `/v1/gameinvitation/${chessGameInvitationId}`,
    data: {
            senderId:"ID",  
            recipientId:"ID",  
            status:"Enum",  
            expiresAt:"Date",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "chessGameInvitation",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"chessGameInvitation": {
		"id": "ID",
		"gameId": "ID",
		"senderId": "ID",
		"recipientId": "ID",
		"status": "Enum",
		"status_idx": "Integer",
		"expiresAt": "Date",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Delete Gameinvitation API

Delete a game invitation (soft-deletes); only admin may do this for moderation/cleanup.

API Frontend Description By The Backend Architect

Not available to normal users. Moderation purposes only. Raise event for invitationRemoved for mods.

Rest Route

The deleteGameInvitation API REST controller can be triggered via the following route:

/v1/gameinvitation/:chessGameInvitationId

Rest Request Parameters

The deleteGameInvitation api has got 1 regular request parameter

Parameter Type Required Population
chessGameInvitationId ID true request.params?.[“chessGameInvitationId”]
chessGameInvitationId : 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/gameinvitation/:chessGameInvitationId

  axios({
    method: 'DELETE',
    url: `/v1/gameinvitation/${chessGameInvitationId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "chessGameInvitation",
	"method": "DELETE",
	"action": "delete",
	"appVersion": "Version",
	"rowCount": 1,
	"chessGameInvitation": {
		"id": "ID",
		"gameId": "ID",
		"senderId": "ID",
		"recipientId": "ID",
		"status": "Enum",
		"status_idx": "Integer",
		"expiresAt": "Date",
		"isActive": false,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

List Gameinvitations API

[Default list API] — This is the designated default list API for the chessGameInvitation data object. Frontend generators and AI agents should use this API for standard CRUD operations. List game invitations. Supports filtering by recipientId, senderId, status, gameId.

API Frontend Description By The Backend Architect

Used to show pending invitations to a user, or to list all invitations for a game.

Rest Route

The listGameInvitations API REST controller can be triggered via the following route:

/v1/gameinvitations

Rest Request Parameters

Filter Parameters

The listGameInvitations api supports 3 optional filter parameters for filtering list results:

senderId (ID): Filter by senderId

recipientId (ID): Filter by recipientId

status (Enum): Filter by status

REST Request To access the api you can use the REST controller with the path GET /v1/gameinvitations

  axios({
    method: 'GET',
    url: '/v1/gameinvitations',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section above)
        // senderId: '<value>' // Filter by senderId
        // recipientId: '<value>' // Filter by recipientId
        // status: '<value>' // Filter by status
            }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "chessGameInvitations",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"chessGameInvitations": [
		{
			"id": "ID",
			"gameId": "ID",
			"senderId": "ID",
			"recipientId": "ID",
			"status": "Enum",
			"status_idx": "Integer",
			"expiresAt": "Date",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID"
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Create Customboard API

[Default create API] — This is the designated default create API for the customBoard data object. Frontend generators and AI agents should use this API for standard CRUD operations. Create a new custom chess board position. Any logged-in user can create boards.

API Frontend Description By The Backend Architect

Called when a user saves a custom board position from the board editor. createdById is auto-set from session.

Rest Route

The createCustomBoard API REST controller can be triggered via the following route:

/v1/customboards

Rest Request Parameters

The createCustomBoard api has got 6 regular request parameters

Parameter Type Required Population
name String true request.body?.[“name”]
fen String true request.body?.[“fen”]
description Text false request.body?.[“description”]
isPublished Boolean true request.body?.[“isPublished”]
category Enum true request.body?.[“category”]
createdById ID true request.body?.[“createdById”]
name : Name of the custom board position
fen : FEN string representing the board position
description : Optional description of the custom board
isPublished :
category :
createdById :

REST Request To access the api you can use the REST controller with the path POST /v1/customboards

  axios({
    method: 'POST',
    url: '/v1/customboards',
    data: {
            name:"String",  
            fen:"String",  
            description:"Text",  
            isPublished:"Boolean",  
            category:"Enum",  
            createdById:"ID",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "customBoard",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"customBoard": {
		"id": "ID",
		"name": "String",
		"fen": "String",
		"description": "Text",
		"isPublished": "Boolean",
		"category": "Enum",
		"category_idx": "Integer",
		"createdById": "ID",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

List Customboards API

[Default list API] — This is the designated default list API for the customBoard data object. Frontend generators and AI agents should use this API for standard CRUD operations. List custom board positions. Supports filtering by isPublished, category, and createdById.

API Frontend Description By The Backend Architect

Used to browse published community boards or user’s own boards. Filter by isPublished=true for public boards.

Rest Route

The listCustomBoards API REST controller can be triggered via the following route:

/v1/customboards

Rest Request Parameters

Filter Parameters

The listCustomBoards api supports 3 optional filter parameters for filtering list results:

isPublished (Boolean): Filter by isPublished

category (Enum): Filter by category

createdById (ID): Filter by createdById

REST Request To access the api you can use the REST controller with the path GET /v1/customboards

  axios({
    method: 'GET',
    url: '/v1/customboards',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section above)
        // isPublished: '<value>' // Filter by isPublished
        // category: '<value>' // Filter by category
        // createdById: '<value>' // Filter by createdById
            }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "customBoards",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"customBoards": [
		{
			"id": "ID",
			"name": "String",
			"fen": "String",
			"description": "Text",
			"isPublished": "Boolean",
			"category": "Enum",
			"category_idx": "Integer",
			"createdById": "ID",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID"
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Get Customboard API

[Default get API] — This is the designated default get API for the customBoard data object. Frontend generators and AI agents should use this API for standard CRUD operations. Fetch a single custom board position by ID.

API Frontend Description By The Backend Architect

Used to load a specific custom board for editing or playing.

Rest Route

The getCustomBoard API REST controller can be triggered via the following route:

/v1/customboards/:customBoardId

Rest Request Parameters

The getCustomBoard api has got 1 regular request parameter

Parameter Type Required Population
customBoardId ID true request.params?.[“customBoardId”]
customBoardId : 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/customboards/:customBoardId

  axios({
    method: 'GET',
    url: `/v1/customboards/${customBoardId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "customBoard",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"customBoard": {
		"id": "ID",
		"name": "String",
		"fen": "String",
		"description": "Text",
		"isPublished": "Boolean",
		"category": "Enum",
		"category_idx": "Integer",
		"createdById": "ID",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Update Customboard API

[Default update API] — This is the designated default update API for the customBoard data object. Frontend generators and AI agents should use this API for standard CRUD operations. Update a custom board position. Only the creator can update their own boards.

API Frontend Description By The Backend Architect

Used to edit board name, description, FEN, category, or publish/unpublish.

Rest Route

The updateCustomBoard API REST controller can be triggered via the following route:

/v1/customboards/:customBoardId

Rest Request Parameters

The updateCustomBoard api has got 7 regular request parameters

Parameter Type Required Population
customBoardId ID true request.params?.[“customBoardId”]
name String false request.body?.[“name”]
fen String false request.body?.[“fen”]
description Text false request.body?.[“description”]
isPublished Boolean request.body?.[“isPublished”]
category Enum request.body?.[“category”]
createdById ID request.body?.[“createdById”]
customBoardId : This id paremeter is used to select the required data object that will be updated
name : Name of the custom board position
fen : FEN string representing the board position
description : Optional description of the custom board
isPublished :
category :
createdById :

REST Request To access the api you can use the REST controller with the path PATCH /v1/customboards/:customBoardId

  axios({
    method: 'PATCH',
    url: `/v1/customboards/${customBoardId}`,
    data: {
            name:"String",  
            fen:"String",  
            description:"Text",  
            isPublished:"Boolean",  
            category:"Enum",  
            createdById:"ID",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "customBoard",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"customBoard": {
		"id": "ID",
		"name": "String",
		"fen": "String",
		"description": "Text",
		"isPublished": "Boolean",
		"category": "Enum",
		"category_idx": "Integer",
		"createdById": "ID",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Delete Customboard API

[Default delete API] — This is the designated default delete API for the customBoard data object. Frontend generators and AI agents should use this API for standard CRUD operations. Delete a custom board position (soft-delete). Only creator or admin can delete.

API Frontend Description By The Backend Architect

Used to remove a custom board. Soft-deletes so data can be recovered if needed.

Rest Route

The deleteCustomBoard API REST controller can be triggered via the following route:

/v1/customboards/:customBoardId

Rest Request Parameters

The deleteCustomBoard api has got 1 regular request parameter

Parameter Type Required Population
customBoardId ID true request.params?.[“customBoardId”]
customBoardId : 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/customboards/:customBoardId

  axios({
    method: 'DELETE',
    url: `/v1/customboards/${customBoardId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "customBoard",
	"method": "DELETE",
	"action": "delete",
	"appVersion": "Version",
	"rowCount": 1,
	"customBoard": {
		"id": "ID",
		"name": "String",
		"fen": "String",
		"description": "Text",
		"isPublished": "Boolean",
		"category": "Enum",
		"category_idx": "Integer",
		"createdById": "ID",
		"isActive": false,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Create Boardtheme API

[Default create API] — This is the designated default create API for the boardTheme data object. Frontend generators and AI agents should use this API for standard CRUD operations. Create a custom board color theme.

API Frontend Description By The Backend Architect

Called when user saves a new custom theme from the themes picker.

Rest Route

The createBoardTheme API REST controller can be triggered via the following route:

/v1/boardthemes

Rest Request Parameters

The createBoardTheme api has got 4 regular request parameters

Parameter Type Required Population
name String true request.body?.[“name”]
lightSquare String true request.body?.[“lightSquare”]
darkSquare String true request.body?.[“darkSquare”]
createdById ID true request.body?.[“createdById”]
name : Theme display name
lightSquare : Hex color for light squares
darkSquare : Hex color for dark squares
createdById : User who created this theme

REST Request To access the api you can use the REST controller with the path POST /v1/boardthemes

  axios({
    method: 'POST',
    url: '/v1/boardthemes',
    data: {
            name:"String",  
            lightSquare:"String",  
            darkSquare:"String",  
            createdById:"ID",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "boardTheme",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"boardTheme": {
		"id": "ID",
		"name": "String",
		"lightSquare": "String",
		"darkSquare": "String",
		"isPublished": "Boolean",
		"createdById": "ID",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

List Boardthemes API

[Default list API] — This is the designated default list API for the boardTheme data object. Frontend generators and AI agents should use this API for standard CRUD operations. List board themes. Filter by isPublished for community themes or createdById for user’s own.

API Frontend Description By The Backend Architect

Used to load user’s custom themes and community-published themes.

Rest Route

The listBoardThemes API REST controller can be triggered via the following route:

/v1/boardthemes

Rest Request Parameters

Filter Parameters

The listBoardThemes api supports 1 optional filter parameter for filtering list results:

isPublished (Boolean): Whether the theme is publicly visible

REST Request To access the api you can use the REST controller with the path GET /v1/boardthemes

  axios({
    method: 'GET',
    url: '/v1/boardthemes',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section above)
        // isPublished: '<value>' // Filter by isPublished
            }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "boardThemes",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"boardThemes": [
		{
			"id": "ID",
			"name": "String",
			"lightSquare": "String",
			"darkSquare": "String",
			"isPublished": "Boolean",
			"createdById": "ID",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID"
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Update Boardtheme API

[Default update API] — This is the designated default update API for the boardTheme data object. Frontend generators and AI agents should use this API for standard CRUD operations. Update a custom board theme. Only creator can update.

API Frontend Description By The Backend Architect

Used to edit theme colors/name or publish/unpublish.

Rest Route

The updateBoardTheme API REST controller can be triggered via the following route:

/v1/boardthemes/:boardThemeId

Rest Request Parameters

The updateBoardTheme api has got 5 regular request parameters

Parameter Type Required Population
boardThemeId ID true request.params?.[“boardThemeId”]
name String false request.body?.[“name”]
lightSquare String false request.body?.[“lightSquare”]
darkSquare String false request.body?.[“darkSquare”]
isPublished Boolean false request.body?.[“isPublished”]
boardThemeId : This id paremeter is used to select the required data object that will be updated
name : Theme display name
lightSquare : Hex color for light squares
darkSquare : Hex color for dark squares
isPublished : Whether the theme is publicly visible

REST Request To access the api you can use the REST controller with the path PATCH /v1/boardthemes/:boardThemeId

  axios({
    method: 'PATCH',
    url: `/v1/boardthemes/${boardThemeId}`,
    data: {
            name:"String",  
            lightSquare:"String",  
            darkSquare:"String",  
            isPublished:"Boolean",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "boardTheme",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"boardTheme": {
		"id": "ID",
		"name": "String",
		"lightSquare": "String",
		"darkSquare": "String",
		"isPublished": "Boolean",
		"createdById": "ID",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Delete Boardtheme API

[Default delete API] — This is the designated default delete API for the boardTheme data object. Frontend generators and AI agents should use this API for standard CRUD operations. Delete a custom board theme (soft-delete). Only creator can delete.

API Frontend Description By The Backend Architect

Used to remove user’s custom theme.

Rest Route

The deleteBoardTheme API REST controller can be triggered via the following route:

/v1/boardthemes/:boardThemeId

Rest Request Parameters

The deleteBoardTheme api has got 1 regular request parameter

Parameter Type Required Population
boardThemeId ID true request.params?.[“boardThemeId”]
boardThemeId : 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/boardthemes/:boardThemeId

  axios({
    method: 'DELETE',
    url: `/v1/boardthemes/${boardThemeId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "boardTheme",
	"method": "DELETE",
	"action": "delete",
	"appVersion": "Version",
	"rowCount": 1,
	"boardTheme": {
		"id": "ID",
		"name": "String",
		"lightSquare": "String",
		"darkSquare": "String",
		"isPublished": "Boolean",
		"createdById": "ID",
		"isActive": false,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Create Userpreference API

[Default create API] — This is the designated default create API for the userPreference data object. Frontend generators and AI agents should use this API for standard CRUD operations. Create user preferences record. One per user, auto-sets userId from session.

API Frontend Description By The Backend Architect

Called once when user first changes a preference. userId is auto-set.

Rest Route

The createUserPreference API REST controller can be triggered via the following route:

/v1/userpreferences

Rest Request Parameters

The createUserPreference api has got 6 regular request parameters

Parameter Type Required Population
userId ID true request.body?.[“userId”]
activeThemeId String false request.body?.[“activeThemeId”]
soundEnabled Boolean false request.body?.[“soundEnabled”]
showAnimations Boolean false request.body?.[“showAnimations”]
boardOrientation Enum false request.body?.[“boardOrientation”]
premoveEnabled Boolean false request.body?.[“premoveEnabled”]
userId : The user this preferences record belongs to
activeThemeId : ID of the currently selected board theme (preset ID or custom theme ID)
soundEnabled : Whether game sounds are enabled
showAnimations : Whether board animations are shown
boardOrientation : Default board orientation preference
premoveEnabled : Whether premove feature is enabled

REST Request To access the api you can use the REST controller with the path POST /v1/userpreferences

  axios({
    method: 'POST',
    url: '/v1/userpreferences',
    data: {
            userId:"ID",  
            activeThemeId:"String",  
            soundEnabled:"Boolean",  
            showAnimations:"Boolean",  
            boardOrientation:"Enum",  
            premoveEnabled:"Boolean",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "userPreference",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"userPreference": {
		"id": "ID",
		"userId": "ID",
		"activeThemeId": "String",
		"soundEnabled": "Boolean",
		"showAnimations": "Boolean",
		"boardOrientation": "Enum",
		"boardOrientation_idx": "Integer",
		"premoveEnabled": "Boolean",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Update Userpreference API

[Default update API] — This is the designated default update API for the userPreference data object. Frontend generators and AI agents should use this API for standard CRUD operations. Update user preferences. Only the owner can update their own preferences.

API Frontend Description By The Backend Architect

Called when user changes theme, sound, animation, or other settings.

Rest Route

The updateUserPreference API REST controller can be triggered via the following route:

/v1/userpreferences/:userPreferenceId

Rest Request Parameters

The updateUserPreference api has got 6 regular request parameters

Parameter Type Required Population
userPreferenceId ID true request.params?.[“userPreferenceId”]
activeThemeId String false request.body?.[“activeThemeId”]
soundEnabled Boolean false request.body?.[“soundEnabled”]
showAnimations Boolean false request.body?.[“showAnimations”]
boardOrientation Enum false request.body?.[“boardOrientation”]
premoveEnabled Boolean false request.body?.[“premoveEnabled”]
userPreferenceId : This id paremeter is used to select the required data object that will be updated
activeThemeId : ID of the currently selected board theme (preset ID or custom theme ID)
soundEnabled : Whether game sounds are enabled
showAnimations : Whether board animations are shown
boardOrientation : Default board orientation preference
premoveEnabled : Whether premove feature is enabled

REST Request To access the api you can use the REST controller with the path PATCH /v1/userpreferences/:userPreferenceId

  axios({
    method: 'PATCH',
    url: `/v1/userpreferences/${userPreferenceId}`,
    data: {
            activeThemeId:"String",  
            soundEnabled:"Boolean",  
            showAnimations:"Boolean",  
            boardOrientation:"Enum",  
            premoveEnabled:"Boolean",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "userPreference",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"userPreference": {
		"id": "ID",
		"userId": "ID",
		"activeThemeId": "String",
		"soundEnabled": "Boolean",
		"showAnimations": "Boolean",
		"boardOrientation": "Enum",
		"boardOrientation_idx": "Integer",
		"premoveEnabled": "Boolean",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Get Userpreference API

[Default get API] — This is the designated default get API for the userPreference data object. Frontend generators and AI agents should use this API for standard CRUD operations. Get a user’s preferences by ID.

API Frontend Description By The Backend Architect

Called on app load to restore user’s preferences.

Rest Route

The getUserPreference API REST controller can be triggered via the following route:

/v1/userpreferences/:userPreferenceId

Rest Request Parameters

The getUserPreference api has got 1 regular request parameter

Parameter Type Required Population
userPreferenceId ID true request.params?.[“userPreferenceId”]
userPreferenceId : 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/userpreferences/:userPreferenceId

  axios({
    method: 'GET',
    url: `/v1/userpreferences/${userPreferenceId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "userPreference",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"userPreference": {
		"id": "ID",
		"userId": "ID",
		"activeThemeId": "String",
		"soundEnabled": "Boolean",
		"showAnimations": "Boolean",
		"boardOrientation": "Enum",
		"boardOrientation_idx": "Integer",
		"premoveEnabled": "Boolean",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

List Userpreferences API

[Default list API] — This is the designated default list API for the userPreference data object. Frontend generators and AI agents should use this API for standard CRUD operations. List user preferences. Filter by userId to get a specific user’s preferences.

API Frontend Description By The Backend Architect

Used to find user’s preference record by userId filter.

Rest Route

The listUserPreferences API REST controller can be triggered via the following route:

/v1/userpreferences

Rest Request Parameters The listUserPreferences api has got no request parameters.

REST Request To access the api you can use the REST controller with the path GET /v1/userpreferences

  axios({
    method: 'GET',
    url: '/v1/userpreferences',
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "userPreferences",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"userPreferences": [
		{
			"id": "ID",
			"userId": "ID",
			"activeThemeId": "String",
			"soundEnabled": "Boolean",
			"showAnimations": "Boolean",
			"boardOrientation": "Enum",
			"boardOrientation_idx": "Integer",
			"premoveEnabled": "Boolean",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID"
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

List Gamehubmessages API

[Default list API] — This is the designated default list API for the gameHubMessage data object. Frontend generators and AI agents should use this API for standard CRUD operations. List messages in a gameHub hub room. Accessible by admins and room participants.

Rest Route

The listGameHubMessages API REST controller can be triggered via the following route:

/v1/v1/gameHub-messages

Rest Request Parameters

Filter Parameters

The listGameHubMessages api supports 8 optional filter parameters for filtering list results:

roomId (ID): Reference to the room this message belongs to

senderId (ID): Reference to the user who sent this message

senderName (String): Display name of the sender (denormalized from user profile at send time)

senderAvatar (String): Avatar URL of the sender (denormalized from user profile at send time)

messageType (Enum): Content type discriminator for this message

content (Object): Type-specific content payload (structure depends on messageType)

timestamp (String): Message creation time

status (Enum): Message moderation status

REST Request To access the api you can use the REST controller with the path GET /v1/v1/gameHub-messages

  axios({
    method: 'GET',
    url: '/v1/v1/gameHub-messages',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section above)
        // roomId: '<value>' // Filter by roomId
        // senderId: '<value>' // Filter by senderId
        // senderName: '<value>' // Filter by senderName
        // senderAvatar: '<value>' // Filter by senderAvatar
        // messageType: '<value>' // Filter by messageType
        // content: '<value>' // Filter by content
        // timestamp: '<value>' // Filter by timestamp
        // status: '<value>' // Filter by status
            }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "gameHubMessages",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"gameHubMessages": [
		{
			"id": "ID",
			"roomId": "ID",
			"senderId": "ID",
			"senderName": "String",
			"senderAvatar": "String",
			"messageType": "Enum",
			"messageType_idx": "Integer",
			"content": "Object",
			"timestamp": null,
			"status": "Enum",
			"status_idx": "Integer",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID"
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Get Gamehubmessage API

[Default get API] — This is the designated default get API for the gameHubMessage data object. Frontend generators and AI agents should use this API for standard CRUD operations. Get a single gameHub hub message by ID.

Rest Route

The getGameHubMessage API REST controller can be triggered via the following route:

/v1/v1/gameHub-messages/:id

Rest Request Parameters

The getGameHubMessage api has got 2 regular request parameters

Parameter Type Required Population
gameHubMessageId ID true request.params?.[“gameHubMessageId”]
id String true request.params?.[“id”]
gameHubMessageId : 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/v1/gameHub-messages/:id

  axios({
    method: 'GET',
    url: `/v1/v1/gameHub-messages/${id}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "gameHubMessage",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"gameHubMessage": {
		"id": "ID",
		"roomId": "ID",
		"senderId": "ID",
		"senderName": "String",
		"senderAvatar": "String",
		"messageType": "Enum",
		"messageType_idx": "Integer",
		"content": "Object",
		"timestamp": null,
		"status": "Enum",
		"status_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Delete Gamehubmessage API

[Default delete API] — This is the designated default delete API for the gameHubMessage data object. Frontend generators and AI agents should use this API for standard CRUD operations. Delete a gameHub hub message. Admins can delete any message; users can delete their own.

Rest Route

The deleteGameHubMessage API REST controller can be triggered via the following route:

/v1/v1/gameHub-messages/:id

Rest Request Parameters

The deleteGameHubMessage api has got 2 regular request parameters

Parameter Type Required Population
gameHubMessageId ID true request.params?.[“gameHubMessageId”]
id String true request.params?.[“id”]
gameHubMessageId : This id paremeter is used to select the required data object that will be deleted
id : This parameter will be used to select the data object that want to be deleted

REST Request To access the api you can use the REST controller with the path DELETE /v1/v1/gameHub-messages/:id

  axios({
    method: 'DELETE',
    url: `/v1/v1/gameHub-messages/${id}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "gameHubMessage",
	"method": "DELETE",
	"action": "delete",
	"appVersion": "Version",
	"rowCount": 1,
	"gameHubMessage": {
		"id": "ID",
		"roomId": "ID",
		"senderId": "ID",
		"senderName": "String",
		"senderAvatar": "String",
		"messageType": "Enum",
		"messageType_idx": "Integer",
		"content": "Object",
		"timestamp": null,
		"status": "Enum",
		"status_idx": "Integer",
		"isActive": false,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Update Gamehubmessage API

[Default update API] — This is the designated default update API for the gameHubMessage data object. Frontend generators and AI agents should use this API for standard CRUD operations. Update a gameHub hub message content. Only the message sender or admins can edit.

Rest Route

The updateGameHubMessage API REST controller can be triggered via the following route:

/v1/v1/gameHub-messages/:id

Rest Request Parameters

The updateGameHubMessage api has got 4 regular request parameters

Parameter Type Required Population
gameHubMessageId ID true request.params?.[“gameHubMessageId”]
content Object false request.body?.[“content”]
status Enum false request.body?.[“status”]
id String true request.params?.[“id”]
gameHubMessageId : This id paremeter is used to select the required data object that will be updated
content : Type-specific content payload (structure depends on messageType)
status : Message moderation status
id : This parameter will be used to select the data object that want to be updated

REST Request To access the api you can use the REST controller with the path PATCH /v1/v1/gameHub-messages/:id

  axios({
    method: 'PATCH',
    url: `/v1/v1/gameHub-messages/${id}`,
    data: {
            content:"Object",  
            status:"Enum",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "gameHubMessage",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"gameHubMessage": {
		"id": "ID",
		"roomId": "ID",
		"senderId": "ID",
		"senderName": "String",
		"senderAvatar": "String",
		"messageType": "Enum",
		"messageType_idx": "Integer",
		"content": "Object",
		"timestamp": null,
		"status": "Enum",
		"status_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Authentication Specific Routes

Common Routes

Route: currentuser

Route Definition: Retrieves the currently authenticated user’s session information.

Route Type: sessionInfo

Access Route: GET /currentuser

Parameters

This route does not require any request parameters.

Behavior

// Sample GET /currentuser call
axios.get("/currentuser", {
  headers: {
    "Authorization": "Bearer your-jwt-token"
  }
});

Success Response Returns the session object, including user-related data and token information.

{
  "sessionId": "9cf23fa8-07d4-4e7c-80a6-ec6d6ac96bb9",
  "userId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38",
  "email": "user@example.com",
  "fullname": "John Doe",
  "roleId": "user",
  "tenantId": "abc123",
  "accessToken": "jwt-token-string",
  ...
}

Error Response 401 Unauthorized: No active session found.

{
  "status": "ERR",
  "message": "No login found"
}

Notes

Route: permissions

*Route Definition*: Retrieves all effective permission records assigned to the currently authenticated user.

*Route Type*: permissionFetch

Access Route: GET /permissions

Parameters

This route does not require any request parameters.

Behavior

// Sample GET /permissions call
axios.get("/permissions", {
  headers: {
    "Authorization": "Bearer your-jwt-token"
  }
});

Success Response

Returns an array of permission objects.

[
  {
    "id": "perm1",
    "permissionName": "adminPanel.access",
    "roleId": "admin",
    "subjectUserId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38",
    "subjectUserGroupId": null,
    "objectId": null,
    "canDo": true,
    "tenantCodename": "store123"
  },
  {
    "id": "perm2",
    "permissionName": "orders.manage",
    "roleId": null,
    "subjectUserId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38",
    "subjectUserGroupId": null,
    "objectId": null,
    "canDo": true,
    "tenantCodename": "store123"
  }
]

Each object reflects a single permission grant, aligned with the givenPermissions model:

Error Responses

{
  "status": "ERR",
  "message": "No login found"
}

Notes

Tip: Applications can cache permission results client-side or server-side, but should occasionally refresh by calling this endpoint, especially after login or permission-changing operations.

Route: permissions/:permissionName

Route Definition: Checks whether the current user has access to a specific permission, and provides a list of scoped object exceptions or inclusions.

Route Type: permissionScopeCheck

Access Route: GET /permissions/:permissionName

Parameters

Parameter Type Required Population
permissionName String Yes request.params.permissionName

Behavior

// Sample GET /permissions/orders.manage
axios.get("/permissions/orders.manage", {
  headers: {
    "Authorization": "Bearer your-jwt-token"
  }
});

Success Response

{
  "canDo": true,
  "exceptions": [
    "a1f2e3d4-xxxx-yyyy-zzzz-object1",
    "b2c3d4e5-xxxx-yyyy-zzzz-object2"
  ]
}

Copyright

All sources, documents and other digital materials are copyright of .

About Us

For more information please visit our website: .

. .


EVENT GUIDE

EVENT GUIDE

wechess-gameplay-service

Service for managing real-time chess games, matchmaking, move history, and private invitations, including lifecycle management (mutual game-save/resume, admin termination), supporting both guest and registered users. Enables API access for reviewing games, enforcing moderation actions, and tracking game results.

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 Gameplay Service Event descriptions. This guide is dedicated to detailing how to subscribe to and listen for state changes within the Gameplay Service, offering an exclusive focus on event subscription mechanisms.

Intended Audience

This documentation is aimed at developers and integrators looking to monitor Gameplay Service state changes. It is especially relevant for those wishing to implement or enhance business logic based on interactions with Gameplay 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 Gameplay 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 chessGame-created

Event topic: wechess-gameplay-service-dbevent-chessgame-created

This event is triggered upon the creation of a chessGame data object in the database. The event payload encompasses the newly created data, encapsulated within the root of the paylod.

Event payload:

{"id":"ID","playerWhiteId":"ID","playerBlackId":"ID","createdById":"ID","status":"Enum","status_idx":"Integer","mode":"Enum","mode_idx":"Integer","invitationCode":"String","currentFEN":"String","gameType":"Enum","gameType_idx":"Integer","saveStatus":"Enum","saveStatus_idx":"Integer","saveRequestWhite":"Boolean","saveRequestBlack":"Boolean","movedAt":"Date","result":"Enum","result_idx":"Integer","terminatedById":"ID","reportStatus":"Enum","reportStatus_idx":"Integer","guestPlayerWhite":"Boolean","guestPlayerBlack":"Boolean","initialFEN":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

DbEvent chessGame-updated

Event topic: wechess-gameplay-service-dbevent-chessgame-updated

Activation of this event follows the update of a chessGame data object. The payload contains the updated information under the chessGame attribute, along with the original data prior to update, labeled as old_chessGame and also you can find the old and new versions of updated-only portion of the data…

Event payload:

{
old_chessGame:{"id":"ID","playerWhiteId":"ID","playerBlackId":"ID","createdById":"ID","status":"Enum","status_idx":"Integer","mode":"Enum","mode_idx":"Integer","invitationCode":"String","currentFEN":"String","gameType":"Enum","gameType_idx":"Integer","saveStatus":"Enum","saveStatus_idx":"Integer","saveRequestWhite":"Boolean","saveRequestBlack":"Boolean","movedAt":"Date","result":"Enum","result_idx":"Integer","terminatedById":"ID","reportStatus":"Enum","reportStatus_idx":"Integer","guestPlayerWhite":"Boolean","guestPlayerBlack":"Boolean","initialFEN":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},
chessGame:{"id":"ID","playerWhiteId":"ID","playerBlackId":"ID","createdById":"ID","status":"Enum","status_idx":"Integer","mode":"Enum","mode_idx":"Integer","invitationCode":"String","currentFEN":"String","gameType":"Enum","gameType_idx":"Integer","saveStatus":"Enum","saveStatus_idx":"Integer","saveRequestWhite":"Boolean","saveRequestBlack":"Boolean","movedAt":"Date","result":"Enum","result_idx":"Integer","terminatedById":"ID","reportStatus":"Enum","reportStatus_idx":"Integer","guestPlayerWhite":"Boolean","guestPlayerBlack":"Boolean","initialFEN":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},
oldDataValues,
newDataValues
}

DbEvent chessGame-deleted

Event topic: wechess-gameplay-service-dbevent-chessgame-deleted

This event announces the deletion of a chessGame 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","playerWhiteId":"ID","playerBlackId":"ID","createdById":"ID","status":"Enum","status_idx":"Integer","mode":"Enum","mode_idx":"Integer","invitationCode":"String","currentFEN":"String","gameType":"Enum","gameType_idx":"Integer","saveStatus":"Enum","saveStatus_idx":"Integer","saveRequestWhite":"Boolean","saveRequestBlack":"Boolean","movedAt":"Date","result":"Enum","result_idx":"Integer","terminatedById":"ID","reportStatus":"Enum","reportStatus_idx":"Integer","guestPlayerWhite":"Boolean","guestPlayerBlack":"Boolean","initialFEN":"String","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

DbEvent chessGameMove-created

Event topic: wechess-gameplay-service-dbevent-chessgamemove-created

This event is triggered upon the creation of a chessGameMove data object in the database. The event payload encompasses the newly created data, encapsulated within the root of the paylod.

Event payload:

{"id":"ID","gameId":"ID","moveNumber":"Integer","moveNotation":"String","moveTime":"Integer","movedById":"ID","moveTimestamp":"Date","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

DbEvent chessGameMove-updated

Event topic: wechess-gameplay-service-dbevent-chessgamemove-updated

Activation of this event follows the update of a chessGameMove data object. The payload contains the updated information under the chessGameMove attribute, along with the original data prior to update, labeled as old_chessGameMove and also you can find the old and new versions of updated-only portion of the data…

Event payload:

{
old_chessGameMove:{"id":"ID","gameId":"ID","moveNumber":"Integer","moveNotation":"String","moveTime":"Integer","movedById":"ID","moveTimestamp":"Date","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},
chessGameMove:{"id":"ID","gameId":"ID","moveNumber":"Integer","moveNotation":"String","moveTime":"Integer","movedById":"ID","moveTimestamp":"Date","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},
oldDataValues,
newDataValues
}

DbEvent chessGameMove-deleted

Event topic: wechess-gameplay-service-dbevent-chessgamemove-deleted

This event announces the deletion of a chessGameMove 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","gameId":"ID","moveNumber":"Integer","moveNotation":"String","moveTime":"Integer","movedById":"ID","moveTimestamp":"Date","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

DbEvent chessGameInvitation-created

Event topic: wechess-gameplay-service-dbevent-chessgameinvitation-created

This event is triggered upon the creation of a chessGameInvitation data object in the database. The event payload encompasses the newly created data, encapsulated within the root of the paylod.

Event payload:

{"id":"ID","gameId":"ID","senderId":"ID","recipientId":"ID","status":"Enum","status_idx":"Integer","expiresAt":"Date","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

DbEvent chessGameInvitation-updated

Event topic: wechess-gameplay-service-dbevent-chessgameinvitation-updated

Activation of this event follows the update of a chessGameInvitation data object. The payload contains the updated information under the chessGameInvitation attribute, along with the original data prior to update, labeled as old_chessGameInvitation and also you can find the old and new versions of updated-only portion of the data…

Event payload:

{
old_chessGameInvitation:{"id":"ID","gameId":"ID","senderId":"ID","recipientId":"ID","status":"Enum","status_idx":"Integer","expiresAt":"Date","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},
chessGameInvitation:{"id":"ID","gameId":"ID","senderId":"ID","recipientId":"ID","status":"Enum","status_idx":"Integer","expiresAt":"Date","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},
oldDataValues,
newDataValues
}

DbEvent chessGameInvitation-deleted

Event topic: wechess-gameplay-service-dbevent-chessgameinvitation-deleted

This event announces the deletion of a chessGameInvitation 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","gameId":"ID","senderId":"ID","recipientId":"ID","status":"Enum","status_idx":"Integer","expiresAt":"Date","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

DbEvent customBoard-created

Event topic: wechess-gameplay-service-dbevent-customboard-created

This event is triggered upon the creation of a customBoard data object in the database. The event payload encompasses the newly created data, encapsulated within the root of the paylod.

Event payload:

{"id":"ID","name":"String","fen":"String","description":"Text","isPublished":"Boolean","category":"Enum","category_idx":"Integer","createdById":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

DbEvent customBoard-updated

Event topic: wechess-gameplay-service-dbevent-customboard-updated

Activation of this event follows the update of a customBoard data object. The payload contains the updated information under the customBoard attribute, along with the original data prior to update, labeled as old_customBoard and also you can find the old and new versions of updated-only portion of the data…

Event payload:

{
old_customBoard:{"id":"ID","name":"String","fen":"String","description":"Text","isPublished":"Boolean","category":"Enum","category_idx":"Integer","createdById":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},
customBoard:{"id":"ID","name":"String","fen":"String","description":"Text","isPublished":"Boolean","category":"Enum","category_idx":"Integer","createdById":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},
oldDataValues,
newDataValues
}

DbEvent customBoard-deleted

Event topic: wechess-gameplay-service-dbevent-customboard-deleted

This event announces the deletion of a customBoard 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","name":"String","fen":"String","description":"Text","isPublished":"Boolean","category":"Enum","category_idx":"Integer","createdById":"ID","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

DbEvent boardTheme-created

Event topic: wechess-gameplay-service-dbevent-boardtheme-created

This event is triggered upon the creation of a boardTheme data object in the database. The event payload encompasses the newly created data, encapsulated within the root of the paylod.

Event payload:

{"id":"ID","name":"String","lightSquare":"String","darkSquare":"String","isPublished":"Boolean","createdById":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

DbEvent boardTheme-updated

Event topic: wechess-gameplay-service-dbevent-boardtheme-updated

Activation of this event follows the update of a boardTheme data object. The payload contains the updated information under the boardTheme attribute, along with the original data prior to update, labeled as old_boardTheme and also you can find the old and new versions of updated-only portion of the data…

Event payload:

{
old_boardTheme:{"id":"ID","name":"String","lightSquare":"String","darkSquare":"String","isPublished":"Boolean","createdById":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},
boardTheme:{"id":"ID","name":"String","lightSquare":"String","darkSquare":"String","isPublished":"Boolean","createdById":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},
oldDataValues,
newDataValues
}

DbEvent boardTheme-deleted

Event topic: wechess-gameplay-service-dbevent-boardtheme-deleted

This event announces the deletion of a boardTheme 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","name":"String","lightSquare":"String","darkSquare":"String","isPublished":"Boolean","createdById":"ID","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

DbEvent userPreference-created

Event topic: wechess-gameplay-service-dbevent-userpreference-created

This event is triggered upon the creation of a userPreference 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","activeThemeId":"String","soundEnabled":"Boolean","showAnimations":"Boolean","boardOrientation":"Enum","boardOrientation_idx":"Integer","premoveEnabled":"Boolean","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

DbEvent userPreference-updated

Event topic: wechess-gameplay-service-dbevent-userpreference-updated

Activation of this event follows the update of a userPreference data object. The payload contains the updated information under the userPreference attribute, along with the original data prior to update, labeled as old_userPreference and also you can find the old and new versions of updated-only portion of the data…

Event payload:

{
old_userPreference:{"id":"ID","userId":"ID","activeThemeId":"String","soundEnabled":"Boolean","showAnimations":"Boolean","boardOrientation":"Enum","boardOrientation_idx":"Integer","premoveEnabled":"Boolean","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},
userPreference:{"id":"ID","userId":"ID","activeThemeId":"String","soundEnabled":"Boolean","showAnimations":"Boolean","boardOrientation":"Enum","boardOrientation_idx":"Integer","premoveEnabled":"Boolean","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},
oldDataValues,
newDataValues
}

DbEvent userPreference-deleted

Event topic: wechess-gameplay-service-dbevent-userpreference-deleted

This event announces the deletion of a userPreference 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","activeThemeId":"String","soundEnabled":"Boolean","showAnimations":"Boolean","boardOrientation":"Enum","boardOrientation_idx":"Integer","premoveEnabled":"Boolean","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

DbEvent gameHubMessage-created

Event topic: wechess-gameplay-service-dbevent-gamehubmessage-created

This event is triggered upon the creation of a gameHubMessage data object in the database. The event payload encompasses the newly created data, encapsulated within the root of the paylod.

Event payload:

{"id":"ID","roomId":"ID","senderId":"ID","senderName":"String","senderAvatar":"String","messageType":"Enum","messageType_idx":"Integer","content":"Object","timestamp":null,"status":"Enum","status_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

DbEvent gameHubMessage-updated

Event topic: wechess-gameplay-service-dbevent-gamehubmessage-updated

Activation of this event follows the update of a gameHubMessage data object. The payload contains the updated information under the gameHubMessage attribute, along with the original data prior to update, labeled as old_gameHubMessage and also you can find the old and new versions of updated-only portion of the data…

Event payload:

{
old_gameHubMessage:{"id":"ID","roomId":"ID","senderId":"ID","senderName":"String","senderAvatar":"String","messageType":"Enum","messageType_idx":"Integer","content":"Object","timestamp":null,"status":"Enum","status_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},
gameHubMessage:{"id":"ID","roomId":"ID","senderId":"ID","senderName":"String","senderAvatar":"String","messageType":"Enum","messageType_idx":"Integer","content":"Object","timestamp":null,"status":"Enum","status_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},
oldDataValues,
newDataValues
}

DbEvent gameHubMessage-deleted

Event topic: wechess-gameplay-service-dbevent-gamehubmessage-deleted

This event announces the deletion of a gameHubMessage 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","roomId":"ID","senderId":"ID","senderName":"String","senderAvatar":"String","messageType":"Enum","messageType_idx":"Integer","content":"Object","timestamp":null,"status":"Enum","status_idx":"Integer","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

DbEvent gameHubModeration-created

Event topic: wechess-gameplay-service-dbevent-gamehubmoderation-created

This event is triggered upon the creation of a gameHubModeration data object in the database. The event payload encompasses the newly created data, encapsulated within the root of the paylod.

Event payload:

{"id":"ID","roomId":"ID","userId":"ID","action":"Enum","action_idx":"Integer","reason":"Text","duration":"Integer","expiresAt":null,"issuedBy":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

DbEvent gameHubModeration-updated

Event topic: wechess-gameplay-service-dbevent-gamehubmoderation-updated

Activation of this event follows the update of a gameHubModeration data object. The payload contains the updated information under the gameHubModeration attribute, along with the original data prior to update, labeled as old_gameHubModeration and also you can find the old and new versions of updated-only portion of the data…

Event payload:

{
old_gameHubModeration:{"id":"ID","roomId":"ID","userId":"ID","action":"Enum","action_idx":"Integer","reason":"Text","duration":"Integer","expiresAt":null,"issuedBy":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},
gameHubModeration:{"id":"ID","roomId":"ID","userId":"ID","action":"Enum","action_idx":"Integer","reason":"Text","duration":"Integer","expiresAt":null,"issuedBy":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},
oldDataValues,
newDataValues
}

DbEvent gameHubModeration-deleted

Event topic: wechess-gameplay-service-dbevent-gamehubmoderation-deleted

This event announces the deletion of a gameHubModeration 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","roomId":"ID","userId":"ID","action":"Enum","action_idx":"Integer","reason":"Text","duration":"Integer","expiresAt":null,"issuedBy":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":false}

ElasticSearch Index Events

Within the Gameplay 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 chessgame-created

Event topic: elastic-index-wechess_chessgame-created

Event payload:

{"id":"ID","playerWhiteId":"ID","playerBlackId":"ID","createdById":"ID","status":"Enum","status_idx":"Integer","mode":"Enum","mode_idx":"Integer","invitationCode":"String","currentFEN":"String","gameType":"Enum","gameType_idx":"Integer","saveStatus":"Enum","saveStatus_idx":"Integer","saveRequestWhite":"Boolean","saveRequestBlack":"Boolean","movedAt":"Date","result":"Enum","result_idx":"Integer","terminatedById":"ID","reportStatus":"Enum","reportStatus_idx":"Integer","guestPlayerWhite":"Boolean","guestPlayerBlack":"Boolean","initialFEN":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event chessgame-updated

Event topic: elastic-index-wechess_chessgame-created

Event payload:

{"id":"ID","playerWhiteId":"ID","playerBlackId":"ID","createdById":"ID","status":"Enum","status_idx":"Integer","mode":"Enum","mode_idx":"Integer","invitationCode":"String","currentFEN":"String","gameType":"Enum","gameType_idx":"Integer","saveStatus":"Enum","saveStatus_idx":"Integer","saveRequestWhite":"Boolean","saveRequestBlack":"Boolean","movedAt":"Date","result":"Enum","result_idx":"Integer","terminatedById":"ID","reportStatus":"Enum","reportStatus_idx":"Integer","guestPlayerWhite":"Boolean","guestPlayerBlack":"Boolean","initialFEN":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event chessgame-deleted

Event topic: elastic-index-wechess_chessgame-deleted

Event payload:

{"id":"ID","playerWhiteId":"ID","playerBlackId":"ID","createdById":"ID","status":"Enum","status_idx":"Integer","mode":"Enum","mode_idx":"Integer","invitationCode":"String","currentFEN":"String","gameType":"Enum","gameType_idx":"Integer","saveStatus":"Enum","saveStatus_idx":"Integer","saveRequestWhite":"Boolean","saveRequestBlack":"Boolean","movedAt":"Date","result":"Enum","result_idx":"Integer","terminatedById":"ID","reportStatus":"Enum","reportStatus_idx":"Integer","guestPlayerWhite":"Boolean","guestPlayerBlack":"Boolean","initialFEN":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event chessgame-extended

Event topic: elastic-index-wechess_chessgame-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 game-created

Event topic : wechess-gameplay-service-game-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 chessGame data object itself.

The following JSON included in the payload illustrates the fullest representation of the chessGame 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":"chessGame","method":"POST","action":"create","appVersion":"Version","rowCount":1,"chessGame":{"id":"ID","playerWhiteId":"ID","playerBlackId":"ID","createdById":"ID","status":"Enum","status_idx":"Integer","mode":"Enum","mode_idx":"Integer","invitationCode":"String","currentFEN":"String","gameType":"Enum","gameType_idx":"Integer","saveStatus":"Enum","saveStatus_idx":"Integer","saveRequestWhite":"Boolean","saveRequestBlack":"Boolean","movedAt":"Date","result":"Enum","result_idx":"Integer","terminatedById":"ID","reportStatus":"Enum","reportStatus_idx":"Integer","guestPlayerWhite":"Boolean","guestPlayerBlack":"Boolean","initialFEN":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event game-updated

Event topic : wechess-gameplay-service-game-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 chessGame data object itself.

The following JSON included in the payload illustrates the fullest representation of the chessGame 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":"chessGame","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"chessGame":{"id":"ID","playerWhiteId":"ID","playerBlackId":"ID","createdById":"ID","status":"Enum","status_idx":"Integer","mode":"Enum","mode_idx":"Integer","invitationCode":"String","currentFEN":"String","gameType":"Enum","gameType_idx":"Integer","saveStatus":"Enum","saveStatus_idx":"Integer","saveRequestWhite":"Boolean","saveRequestBlack":"Boolean","movedAt":"Date","result":"Enum","result_idx":"Integer","terminatedById":"ID","reportStatus":"Enum","reportStatus_idx":"Integer","guestPlayerWhite":"Boolean","guestPlayerBlack":"Boolean","initialFEN":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event game-deleted

Event topic : wechess-gameplay-service-game-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 chessGame data object itself.

The following JSON included in the payload illustrates the fullest representation of the chessGame 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":"chessGame","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"chessGame":{"id":"ID","playerWhiteId":"ID","playerBlackId":"ID","createdById":"ID","status":"Enum","status_idx":"Integer","mode":"Enum","mode_idx":"Integer","invitationCode":"String","currentFEN":"String","gameType":"Enum","gameType_idx":"Integer","saveStatus":"Enum","saveStatus_idx":"Integer","saveRequestWhite":"Boolean","saveRequestBlack":"Boolean","movedAt":"Date","result":"Enum","result_idx":"Integer","terminatedById":"ID","reportStatus":"Enum","reportStatus_idx":"Integer","guestPlayerWhite":"Boolean","guestPlayerBlack":"Boolean","initialFEN":"String","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event game-retrived

Event topic : wechess-gameplay-service-game-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 chessGame data object itself.

The following JSON included in the payload illustrates the fullest representation of the chessGame 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":"chessGame","method":"GET","action":"get","appVersion":"Version","rowCount":1,"chessGame":{"id":"ID","playerWhiteId":"ID","playerBlackId":"ID","createdById":"ID","status":"Enum","status_idx":"Integer","mode":"Enum","mode_idx":"Integer","invitationCode":"String","currentFEN":"String","gameType":"Enum","gameType_idx":"Integer","saveStatus":"Enum","saveStatus_idx":"Integer","saveRequestWhite":"Boolean","saveRequestBlack":"Boolean","movedAt":"Date","result":"Enum","result_idx":"Integer","terminatedById":"ID","reportStatus":"Enum","reportStatus_idx":"Integer","guestPlayerWhite":"Boolean","guestPlayerBlack":"Boolean","initialFEN":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","moves":[{"moveNumber":"Integer","moveNotation":"String","moveTime":"Integer","movedById":"ID","moveTimestamp":"Date"},{},{}]}}

Route Event games-listed

Event topic : wechess-gameplay-service-games-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 chessGames data object itself.

The following JSON included in the payload illustrates the fullest representation of the chessGames 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":"chessGames","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","chessGames":[{"id":"ID","playerWhiteId":"ID","playerBlackId":"ID","createdById":"ID","status":"Enum","status_idx":"Integer","mode":"Enum","mode_idx":"Integer","invitationCode":"String","currentFEN":"String","gameType":"Enum","gameType_idx":"Integer","saveStatus":"Enum","saveStatus_idx":"Integer","saveRequestWhite":"Boolean","saveRequestBlack":"Boolean","movedAt":"Date","result":"Enum","result_idx":"Integer","terminatedById":"ID","reportStatus":"Enum","reportStatus_idx":"Integer","guestPlayerWhite":"Boolean","guestPlayerBlack":"Boolean","initialFEN":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]}

Route Event gamemove-created

Event topic : wechess-gameplay-service-gamemove-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 chessGameMove data object itself.

The following JSON included in the payload illustrates the fullest representation of the chessGameMove 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":"chessGameMove","method":"POST","action":"create","appVersion":"Version","rowCount":1,"chessGameMove":{"id":"ID","gameId":"ID","moveNumber":"Integer","moveNotation":"String","moveTime":"Integer","movedById":"ID","moveTimestamp":"Date","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event gamemoves-listed

Event topic : wechess-gameplay-service-gamemoves-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 chessGameMoves data object itself.

The following JSON included in the payload illustrates the fullest representation of the chessGameMoves 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":"chessGameMoves","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","chessGameMoves":[{"id":"ID","gameId":"ID","moveNumber":"Integer","moveNotation":"String","moveTime":"Integer","movedById":"ID","moveTimestamp":"Date","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]}

Route Event gameinvitation-created

Event topic : wechess-gameplay-service-gameinvitation-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 chessGameInvitation data object itself.

The following JSON included in the payload illustrates the fullest representation of the chessGameInvitation 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":"chessGameInvitation","method":"POST","action":"create","appVersion":"Version","rowCount":1,"chessGameInvitation":{"id":"ID","gameId":"ID","senderId":"ID","recipientId":"ID","status":"Enum","status_idx":"Integer","expiresAt":"Date","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event gameinvitation-updated

Event topic : wechess-gameplay-service-gameinvitation-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 chessGameInvitation data object itself.

The following JSON included in the payload illustrates the fullest representation of the chessGameInvitation 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":"chessGameInvitation","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"chessGameInvitation":{"id":"ID","gameId":"ID","senderId":"ID","recipientId":"ID","status":"Enum","status_idx":"Integer","expiresAt":"Date","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event gameinvitation-deleted

Event topic : wechess-gameplay-service-gameinvitation-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 chessGameInvitation data object itself.

The following JSON included in the payload illustrates the fullest representation of the chessGameInvitation 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":"chessGameInvitation","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"chessGameInvitation":{"id":"ID","gameId":"ID","senderId":"ID","recipientId":"ID","status":"Enum","status_idx":"Integer","expiresAt":"Date","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event customboard-created

Event topic : wechess-gameplay-service-customboard-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 customBoard data object itself.

The following JSON included in the payload illustrates the fullest representation of the customBoard 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":"customBoard","method":"POST","action":"create","appVersion":"Version","rowCount":1,"customBoard":{"id":"ID","name":"String","fen":"String","description":"Text","isPublished":"Boolean","category":"Enum","category_idx":"Integer","createdById":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event customboard-updated

Event topic : wechess-gameplay-service-customboard-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 customBoard data object itself.

The following JSON included in the payload illustrates the fullest representation of the customBoard 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":"customBoard","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"customBoard":{"id":"ID","name":"String","fen":"String","description":"Text","isPublished":"Boolean","category":"Enum","category_idx":"Integer","createdById":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event customboard-deleted

Event topic : wechess-gameplay-service-customboard-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 customBoard data object itself.

The following JSON included in the payload illustrates the fullest representation of the customBoard 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":"customBoard","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"customBoard":{"id":"ID","name":"String","fen":"String","description":"Text","isPublished":"Boolean","category":"Enum","category_idx":"Integer","createdById":"ID","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event boardtheme-created

Event topic : wechess-gameplay-service-boardtheme-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 boardTheme data object itself.

The following JSON included in the payload illustrates the fullest representation of the boardTheme 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":"boardTheme","method":"POST","action":"create","appVersion":"Version","rowCount":1,"boardTheme":{"id":"ID","name":"String","lightSquare":"String","darkSquare":"String","isPublished":"Boolean","createdById":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event boardtheme-updated

Event topic : wechess-gameplay-service-boardtheme-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 boardTheme data object itself.

The following JSON included in the payload illustrates the fullest representation of the boardTheme 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":"boardTheme","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"boardTheme":{"id":"ID","name":"String","lightSquare":"String","darkSquare":"String","isPublished":"Boolean","createdById":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event boardtheme-deleted

Event topic : wechess-gameplay-service-boardtheme-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 boardTheme data object itself.

The following JSON included in the payload illustrates the fullest representation of the boardTheme 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":"boardTheme","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"boardTheme":{"id":"ID","name":"String","lightSquare":"String","darkSquare":"String","isPublished":"Boolean","createdById":"ID","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event gamehubmessage-deleted

Event topic : wechess-gameplay-service-gamehubmessage-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 gameHubMessage data object itself.

The following JSON included in the payload illustrates the fullest representation of the gameHubMessage 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":"gameHubMessage","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"gameHubMessage":{"id":"ID","roomId":"ID","senderId":"ID","senderName":"String","senderAvatar":"String","messageType":"Enum","messageType_idx":"Integer","content":"Object","timestamp":null,"status":"Enum","status_idx":"Integer","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event gamehubmessage-updated

Event topic : wechess-gameplay-service-gamehubmessage-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 gameHubMessage data object itself.

The following JSON included in the payload illustrates the fullest representation of the gameHubMessage 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":"gameHubMessage","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"gameHubMessage":{"id":"ID","roomId":"ID","senderId":"ID","senderName":"String","senderAvatar":"String","messageType":"Enum","messageType_idx":"Integer","content":"Object","timestamp":null,"status":"Enum","status_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Index Event chessgamemove-created

Event topic: elastic-index-wechess_chessgamemove-created

Event payload:

{"id":"ID","gameId":"ID","moveNumber":"Integer","moveNotation":"String","moveTime":"Integer","movedById":"ID","moveTimestamp":"Date","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event chessgamemove-updated

Event topic: elastic-index-wechess_chessgamemove-created

Event payload:

{"id":"ID","gameId":"ID","moveNumber":"Integer","moveNotation":"String","moveTime":"Integer","movedById":"ID","moveTimestamp":"Date","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event chessgamemove-deleted

Event topic: elastic-index-wechess_chessgamemove-deleted

Event payload:

{"id":"ID","gameId":"ID","moveNumber":"Integer","moveNotation":"String","moveTime":"Integer","movedById":"ID","moveTimestamp":"Date","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event chessgamemove-extended

Event topic: elastic-index-wechess_chessgamemove-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 game-created

Event topic : wechess-gameplay-service-game-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 chessGame data object itself.

The following JSON included in the payload illustrates the fullest representation of the chessGame 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":"chessGame","method":"POST","action":"create","appVersion":"Version","rowCount":1,"chessGame":{"id":"ID","playerWhiteId":"ID","playerBlackId":"ID","createdById":"ID","status":"Enum","status_idx":"Integer","mode":"Enum","mode_idx":"Integer","invitationCode":"String","currentFEN":"String","gameType":"Enum","gameType_idx":"Integer","saveStatus":"Enum","saveStatus_idx":"Integer","saveRequestWhite":"Boolean","saveRequestBlack":"Boolean","movedAt":"Date","result":"Enum","result_idx":"Integer","terminatedById":"ID","reportStatus":"Enum","reportStatus_idx":"Integer","guestPlayerWhite":"Boolean","guestPlayerBlack":"Boolean","initialFEN":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event game-updated

Event topic : wechess-gameplay-service-game-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 chessGame data object itself.

The following JSON included in the payload illustrates the fullest representation of the chessGame 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":"chessGame","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"chessGame":{"id":"ID","playerWhiteId":"ID","playerBlackId":"ID","createdById":"ID","status":"Enum","status_idx":"Integer","mode":"Enum","mode_idx":"Integer","invitationCode":"String","currentFEN":"String","gameType":"Enum","gameType_idx":"Integer","saveStatus":"Enum","saveStatus_idx":"Integer","saveRequestWhite":"Boolean","saveRequestBlack":"Boolean","movedAt":"Date","result":"Enum","result_idx":"Integer","terminatedById":"ID","reportStatus":"Enum","reportStatus_idx":"Integer","guestPlayerWhite":"Boolean","guestPlayerBlack":"Boolean","initialFEN":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event game-deleted

Event topic : wechess-gameplay-service-game-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 chessGame data object itself.

The following JSON included in the payload illustrates the fullest representation of the chessGame 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":"chessGame","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"chessGame":{"id":"ID","playerWhiteId":"ID","playerBlackId":"ID","createdById":"ID","status":"Enum","status_idx":"Integer","mode":"Enum","mode_idx":"Integer","invitationCode":"String","currentFEN":"String","gameType":"Enum","gameType_idx":"Integer","saveStatus":"Enum","saveStatus_idx":"Integer","saveRequestWhite":"Boolean","saveRequestBlack":"Boolean","movedAt":"Date","result":"Enum","result_idx":"Integer","terminatedById":"ID","reportStatus":"Enum","reportStatus_idx":"Integer","guestPlayerWhite":"Boolean","guestPlayerBlack":"Boolean","initialFEN":"String","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event game-retrived

Event topic : wechess-gameplay-service-game-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 chessGame data object itself.

The following JSON included in the payload illustrates the fullest representation of the chessGame 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":"chessGame","method":"GET","action":"get","appVersion":"Version","rowCount":1,"chessGame":{"id":"ID","playerWhiteId":"ID","playerBlackId":"ID","createdById":"ID","status":"Enum","status_idx":"Integer","mode":"Enum","mode_idx":"Integer","invitationCode":"String","currentFEN":"String","gameType":"Enum","gameType_idx":"Integer","saveStatus":"Enum","saveStatus_idx":"Integer","saveRequestWhite":"Boolean","saveRequestBlack":"Boolean","movedAt":"Date","result":"Enum","result_idx":"Integer","terminatedById":"ID","reportStatus":"Enum","reportStatus_idx":"Integer","guestPlayerWhite":"Boolean","guestPlayerBlack":"Boolean","initialFEN":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","moves":[{"moveNumber":"Integer","moveNotation":"String","moveTime":"Integer","movedById":"ID","moveTimestamp":"Date"},{},{}]}}

Route Event games-listed

Event topic : wechess-gameplay-service-games-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 chessGames data object itself.

The following JSON included in the payload illustrates the fullest representation of the chessGames 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":"chessGames","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","chessGames":[{"id":"ID","playerWhiteId":"ID","playerBlackId":"ID","createdById":"ID","status":"Enum","status_idx":"Integer","mode":"Enum","mode_idx":"Integer","invitationCode":"String","currentFEN":"String","gameType":"Enum","gameType_idx":"Integer","saveStatus":"Enum","saveStatus_idx":"Integer","saveRequestWhite":"Boolean","saveRequestBlack":"Boolean","movedAt":"Date","result":"Enum","result_idx":"Integer","terminatedById":"ID","reportStatus":"Enum","reportStatus_idx":"Integer","guestPlayerWhite":"Boolean","guestPlayerBlack":"Boolean","initialFEN":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]}

Route Event gamemove-created

Event topic : wechess-gameplay-service-gamemove-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 chessGameMove data object itself.

The following JSON included in the payload illustrates the fullest representation of the chessGameMove 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":"chessGameMove","method":"POST","action":"create","appVersion":"Version","rowCount":1,"chessGameMove":{"id":"ID","gameId":"ID","moveNumber":"Integer","moveNotation":"String","moveTime":"Integer","movedById":"ID","moveTimestamp":"Date","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event gamemoves-listed

Event topic : wechess-gameplay-service-gamemoves-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 chessGameMoves data object itself.

The following JSON included in the payload illustrates the fullest representation of the chessGameMoves 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":"chessGameMoves","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","chessGameMoves":[{"id":"ID","gameId":"ID","moveNumber":"Integer","moveNotation":"String","moveTime":"Integer","movedById":"ID","moveTimestamp":"Date","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]}

Route Event gameinvitation-created

Event topic : wechess-gameplay-service-gameinvitation-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 chessGameInvitation data object itself.

The following JSON included in the payload illustrates the fullest representation of the chessGameInvitation 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":"chessGameInvitation","method":"POST","action":"create","appVersion":"Version","rowCount":1,"chessGameInvitation":{"id":"ID","gameId":"ID","senderId":"ID","recipientId":"ID","status":"Enum","status_idx":"Integer","expiresAt":"Date","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event gameinvitation-updated

Event topic : wechess-gameplay-service-gameinvitation-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 chessGameInvitation data object itself.

The following JSON included in the payload illustrates the fullest representation of the chessGameInvitation 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":"chessGameInvitation","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"chessGameInvitation":{"id":"ID","gameId":"ID","senderId":"ID","recipientId":"ID","status":"Enum","status_idx":"Integer","expiresAt":"Date","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event gameinvitation-deleted

Event topic : wechess-gameplay-service-gameinvitation-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 chessGameInvitation data object itself.

The following JSON included in the payload illustrates the fullest representation of the chessGameInvitation 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":"chessGameInvitation","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"chessGameInvitation":{"id":"ID","gameId":"ID","senderId":"ID","recipientId":"ID","status":"Enum","status_idx":"Integer","expiresAt":"Date","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event customboard-created

Event topic : wechess-gameplay-service-customboard-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 customBoard data object itself.

The following JSON included in the payload illustrates the fullest representation of the customBoard 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":"customBoard","method":"POST","action":"create","appVersion":"Version","rowCount":1,"customBoard":{"id":"ID","name":"String","fen":"String","description":"Text","isPublished":"Boolean","category":"Enum","category_idx":"Integer","createdById":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event customboard-updated

Event topic : wechess-gameplay-service-customboard-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 customBoard data object itself.

The following JSON included in the payload illustrates the fullest representation of the customBoard 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":"customBoard","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"customBoard":{"id":"ID","name":"String","fen":"String","description":"Text","isPublished":"Boolean","category":"Enum","category_idx":"Integer","createdById":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event customboard-deleted

Event topic : wechess-gameplay-service-customboard-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 customBoard data object itself.

The following JSON included in the payload illustrates the fullest representation of the customBoard 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":"customBoard","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"customBoard":{"id":"ID","name":"String","fen":"String","description":"Text","isPublished":"Boolean","category":"Enum","category_idx":"Integer","createdById":"ID","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event boardtheme-created

Event topic : wechess-gameplay-service-boardtheme-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 boardTheme data object itself.

The following JSON included in the payload illustrates the fullest representation of the boardTheme 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":"boardTheme","method":"POST","action":"create","appVersion":"Version","rowCount":1,"boardTheme":{"id":"ID","name":"String","lightSquare":"String","darkSquare":"String","isPublished":"Boolean","createdById":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event boardtheme-updated

Event topic : wechess-gameplay-service-boardtheme-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 boardTheme data object itself.

The following JSON included in the payload illustrates the fullest representation of the boardTheme 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":"boardTheme","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"boardTheme":{"id":"ID","name":"String","lightSquare":"String","darkSquare":"String","isPublished":"Boolean","createdById":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event boardtheme-deleted

Event topic : wechess-gameplay-service-boardtheme-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 boardTheme data object itself.

The following JSON included in the payload illustrates the fullest representation of the boardTheme 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":"boardTheme","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"boardTheme":{"id":"ID","name":"String","lightSquare":"String","darkSquare":"String","isPublished":"Boolean","createdById":"ID","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event gamehubmessage-deleted

Event topic : wechess-gameplay-service-gamehubmessage-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 gameHubMessage data object itself.

The following JSON included in the payload illustrates the fullest representation of the gameHubMessage 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":"gameHubMessage","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"gameHubMessage":{"id":"ID","roomId":"ID","senderId":"ID","senderName":"String","senderAvatar":"String","messageType":"Enum","messageType_idx":"Integer","content":"Object","timestamp":null,"status":"Enum","status_idx":"Integer","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event gamehubmessage-updated

Event topic : wechess-gameplay-service-gamehubmessage-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 gameHubMessage data object itself.

The following JSON included in the payload illustrates the fullest representation of the gameHubMessage 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":"gameHubMessage","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"gameHubMessage":{"id":"ID","roomId":"ID","senderId":"ID","senderName":"String","senderAvatar":"String","messageType":"Enum","messageType_idx":"Integer","content":"Object","timestamp":null,"status":"Enum","status_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Index Event chessgameinvitation-created

Event topic: elastic-index-wechess_chessgameinvitation-created

Event payload:

{"id":"ID","gameId":"ID","senderId":"ID","recipientId":"ID","status":"Enum","status_idx":"Integer","expiresAt":"Date","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event chessgameinvitation-updated

Event topic: elastic-index-wechess_chessgameinvitation-created

Event payload:

{"id":"ID","gameId":"ID","senderId":"ID","recipientId":"ID","status":"Enum","status_idx":"Integer","expiresAt":"Date","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event chessgameinvitation-deleted

Event topic: elastic-index-wechess_chessgameinvitation-deleted

Event payload:

{"id":"ID","gameId":"ID","senderId":"ID","recipientId":"ID","status":"Enum","status_idx":"Integer","expiresAt":"Date","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event chessgameinvitation-extended

Event topic: elastic-index-wechess_chessgameinvitation-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 game-created

Event topic : wechess-gameplay-service-game-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 chessGame data object itself.

The following JSON included in the payload illustrates the fullest representation of the chessGame 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":"chessGame","method":"POST","action":"create","appVersion":"Version","rowCount":1,"chessGame":{"id":"ID","playerWhiteId":"ID","playerBlackId":"ID","createdById":"ID","status":"Enum","status_idx":"Integer","mode":"Enum","mode_idx":"Integer","invitationCode":"String","currentFEN":"String","gameType":"Enum","gameType_idx":"Integer","saveStatus":"Enum","saveStatus_idx":"Integer","saveRequestWhite":"Boolean","saveRequestBlack":"Boolean","movedAt":"Date","result":"Enum","result_idx":"Integer","terminatedById":"ID","reportStatus":"Enum","reportStatus_idx":"Integer","guestPlayerWhite":"Boolean","guestPlayerBlack":"Boolean","initialFEN":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event game-updated

Event topic : wechess-gameplay-service-game-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 chessGame data object itself.

The following JSON included in the payload illustrates the fullest representation of the chessGame 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":"chessGame","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"chessGame":{"id":"ID","playerWhiteId":"ID","playerBlackId":"ID","createdById":"ID","status":"Enum","status_idx":"Integer","mode":"Enum","mode_idx":"Integer","invitationCode":"String","currentFEN":"String","gameType":"Enum","gameType_idx":"Integer","saveStatus":"Enum","saveStatus_idx":"Integer","saveRequestWhite":"Boolean","saveRequestBlack":"Boolean","movedAt":"Date","result":"Enum","result_idx":"Integer","terminatedById":"ID","reportStatus":"Enum","reportStatus_idx":"Integer","guestPlayerWhite":"Boolean","guestPlayerBlack":"Boolean","initialFEN":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event game-deleted

Event topic : wechess-gameplay-service-game-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 chessGame data object itself.

The following JSON included in the payload illustrates the fullest representation of the chessGame 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":"chessGame","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"chessGame":{"id":"ID","playerWhiteId":"ID","playerBlackId":"ID","createdById":"ID","status":"Enum","status_idx":"Integer","mode":"Enum","mode_idx":"Integer","invitationCode":"String","currentFEN":"String","gameType":"Enum","gameType_idx":"Integer","saveStatus":"Enum","saveStatus_idx":"Integer","saveRequestWhite":"Boolean","saveRequestBlack":"Boolean","movedAt":"Date","result":"Enum","result_idx":"Integer","terminatedById":"ID","reportStatus":"Enum","reportStatus_idx":"Integer","guestPlayerWhite":"Boolean","guestPlayerBlack":"Boolean","initialFEN":"String","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event game-retrived

Event topic : wechess-gameplay-service-game-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 chessGame data object itself.

The following JSON included in the payload illustrates the fullest representation of the chessGame 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":"chessGame","method":"GET","action":"get","appVersion":"Version","rowCount":1,"chessGame":{"id":"ID","playerWhiteId":"ID","playerBlackId":"ID","createdById":"ID","status":"Enum","status_idx":"Integer","mode":"Enum","mode_idx":"Integer","invitationCode":"String","currentFEN":"String","gameType":"Enum","gameType_idx":"Integer","saveStatus":"Enum","saveStatus_idx":"Integer","saveRequestWhite":"Boolean","saveRequestBlack":"Boolean","movedAt":"Date","result":"Enum","result_idx":"Integer","terminatedById":"ID","reportStatus":"Enum","reportStatus_idx":"Integer","guestPlayerWhite":"Boolean","guestPlayerBlack":"Boolean","initialFEN":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","moves":[{"moveNumber":"Integer","moveNotation":"String","moveTime":"Integer","movedById":"ID","moveTimestamp":"Date"},{},{}]}}

Route Event games-listed

Event topic : wechess-gameplay-service-games-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 chessGames data object itself.

The following JSON included in the payload illustrates the fullest representation of the chessGames 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":"chessGames","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","chessGames":[{"id":"ID","playerWhiteId":"ID","playerBlackId":"ID","createdById":"ID","status":"Enum","status_idx":"Integer","mode":"Enum","mode_idx":"Integer","invitationCode":"String","currentFEN":"String","gameType":"Enum","gameType_idx":"Integer","saveStatus":"Enum","saveStatus_idx":"Integer","saveRequestWhite":"Boolean","saveRequestBlack":"Boolean","movedAt":"Date","result":"Enum","result_idx":"Integer","terminatedById":"ID","reportStatus":"Enum","reportStatus_idx":"Integer","guestPlayerWhite":"Boolean","guestPlayerBlack":"Boolean","initialFEN":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]}

Route Event gamemove-created

Event topic : wechess-gameplay-service-gamemove-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 chessGameMove data object itself.

The following JSON included in the payload illustrates the fullest representation of the chessGameMove 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":"chessGameMove","method":"POST","action":"create","appVersion":"Version","rowCount":1,"chessGameMove":{"id":"ID","gameId":"ID","moveNumber":"Integer","moveNotation":"String","moveTime":"Integer","movedById":"ID","moveTimestamp":"Date","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event gamemoves-listed

Event topic : wechess-gameplay-service-gamemoves-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 chessGameMoves data object itself.

The following JSON included in the payload illustrates the fullest representation of the chessGameMoves 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":"chessGameMoves","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","chessGameMoves":[{"id":"ID","gameId":"ID","moveNumber":"Integer","moveNotation":"String","moveTime":"Integer","movedById":"ID","moveTimestamp":"Date","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]}

Route Event gameinvitation-created

Event topic : wechess-gameplay-service-gameinvitation-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 chessGameInvitation data object itself.

The following JSON included in the payload illustrates the fullest representation of the chessGameInvitation 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":"chessGameInvitation","method":"POST","action":"create","appVersion":"Version","rowCount":1,"chessGameInvitation":{"id":"ID","gameId":"ID","senderId":"ID","recipientId":"ID","status":"Enum","status_idx":"Integer","expiresAt":"Date","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event gameinvitation-updated

Event topic : wechess-gameplay-service-gameinvitation-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 chessGameInvitation data object itself.

The following JSON included in the payload illustrates the fullest representation of the chessGameInvitation 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":"chessGameInvitation","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"chessGameInvitation":{"id":"ID","gameId":"ID","senderId":"ID","recipientId":"ID","status":"Enum","status_idx":"Integer","expiresAt":"Date","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event gameinvitation-deleted

Event topic : wechess-gameplay-service-gameinvitation-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 chessGameInvitation data object itself.

The following JSON included in the payload illustrates the fullest representation of the chessGameInvitation 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":"chessGameInvitation","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"chessGameInvitation":{"id":"ID","gameId":"ID","senderId":"ID","recipientId":"ID","status":"Enum","status_idx":"Integer","expiresAt":"Date","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event customboard-created

Event topic : wechess-gameplay-service-customboard-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 customBoard data object itself.

The following JSON included in the payload illustrates the fullest representation of the customBoard 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":"customBoard","method":"POST","action":"create","appVersion":"Version","rowCount":1,"customBoard":{"id":"ID","name":"String","fen":"String","description":"Text","isPublished":"Boolean","category":"Enum","category_idx":"Integer","createdById":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event customboard-updated

Event topic : wechess-gameplay-service-customboard-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 customBoard data object itself.

The following JSON included in the payload illustrates the fullest representation of the customBoard 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":"customBoard","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"customBoard":{"id":"ID","name":"String","fen":"String","description":"Text","isPublished":"Boolean","category":"Enum","category_idx":"Integer","createdById":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event customboard-deleted

Event topic : wechess-gameplay-service-customboard-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 customBoard data object itself.

The following JSON included in the payload illustrates the fullest representation of the customBoard 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":"customBoard","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"customBoard":{"id":"ID","name":"String","fen":"String","description":"Text","isPublished":"Boolean","category":"Enum","category_idx":"Integer","createdById":"ID","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event boardtheme-created

Event topic : wechess-gameplay-service-boardtheme-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 boardTheme data object itself.

The following JSON included in the payload illustrates the fullest representation of the boardTheme 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":"boardTheme","method":"POST","action":"create","appVersion":"Version","rowCount":1,"boardTheme":{"id":"ID","name":"String","lightSquare":"String","darkSquare":"String","isPublished":"Boolean","createdById":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event boardtheme-updated

Event topic : wechess-gameplay-service-boardtheme-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 boardTheme data object itself.

The following JSON included in the payload illustrates the fullest representation of the boardTheme 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":"boardTheme","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"boardTheme":{"id":"ID","name":"String","lightSquare":"String","darkSquare":"String","isPublished":"Boolean","createdById":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event boardtheme-deleted

Event topic : wechess-gameplay-service-boardtheme-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 boardTheme data object itself.

The following JSON included in the payload illustrates the fullest representation of the boardTheme 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":"boardTheme","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"boardTheme":{"id":"ID","name":"String","lightSquare":"String","darkSquare":"String","isPublished":"Boolean","createdById":"ID","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event gamehubmessage-deleted

Event topic : wechess-gameplay-service-gamehubmessage-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 gameHubMessage data object itself.

The following JSON included in the payload illustrates the fullest representation of the gameHubMessage 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":"gameHubMessage","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"gameHubMessage":{"id":"ID","roomId":"ID","senderId":"ID","senderName":"String","senderAvatar":"String","messageType":"Enum","messageType_idx":"Integer","content":"Object","timestamp":null,"status":"Enum","status_idx":"Integer","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event gamehubmessage-updated

Event topic : wechess-gameplay-service-gamehubmessage-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 gameHubMessage data object itself.

The following JSON included in the payload illustrates the fullest representation of the gameHubMessage 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":"gameHubMessage","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"gameHubMessage":{"id":"ID","roomId":"ID","senderId":"ID","senderName":"String","senderAvatar":"String","messageType":"Enum","messageType_idx":"Integer","content":"Object","timestamp":null,"status":"Enum","status_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Index Event customboard-created

Event topic: elastic-index-wechess_customboard-created

Event payload:

{"id":"ID","name":"String","fen":"String","description":"Text","isPublished":"Boolean","category":"Enum","category_idx":"Integer","createdById":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event customboard-updated

Event topic: elastic-index-wechess_customboard-created

Event payload:

{"id":"ID","name":"String","fen":"String","description":"Text","isPublished":"Boolean","category":"Enum","category_idx":"Integer","createdById":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event customboard-deleted

Event topic: elastic-index-wechess_customboard-deleted

Event payload:

{"id":"ID","name":"String","fen":"String","description":"Text","isPublished":"Boolean","category":"Enum","category_idx":"Integer","createdById":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event customboard-extended

Event topic: elastic-index-wechess_customboard-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 game-created

Event topic : wechess-gameplay-service-game-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 chessGame data object itself.

The following JSON included in the payload illustrates the fullest representation of the chessGame 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":"chessGame","method":"POST","action":"create","appVersion":"Version","rowCount":1,"chessGame":{"id":"ID","playerWhiteId":"ID","playerBlackId":"ID","createdById":"ID","status":"Enum","status_idx":"Integer","mode":"Enum","mode_idx":"Integer","invitationCode":"String","currentFEN":"String","gameType":"Enum","gameType_idx":"Integer","saveStatus":"Enum","saveStatus_idx":"Integer","saveRequestWhite":"Boolean","saveRequestBlack":"Boolean","movedAt":"Date","result":"Enum","result_idx":"Integer","terminatedById":"ID","reportStatus":"Enum","reportStatus_idx":"Integer","guestPlayerWhite":"Boolean","guestPlayerBlack":"Boolean","initialFEN":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event game-updated

Event topic : wechess-gameplay-service-game-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 chessGame data object itself.

The following JSON included in the payload illustrates the fullest representation of the chessGame 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":"chessGame","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"chessGame":{"id":"ID","playerWhiteId":"ID","playerBlackId":"ID","createdById":"ID","status":"Enum","status_idx":"Integer","mode":"Enum","mode_idx":"Integer","invitationCode":"String","currentFEN":"String","gameType":"Enum","gameType_idx":"Integer","saveStatus":"Enum","saveStatus_idx":"Integer","saveRequestWhite":"Boolean","saveRequestBlack":"Boolean","movedAt":"Date","result":"Enum","result_idx":"Integer","terminatedById":"ID","reportStatus":"Enum","reportStatus_idx":"Integer","guestPlayerWhite":"Boolean","guestPlayerBlack":"Boolean","initialFEN":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event game-deleted

Event topic : wechess-gameplay-service-game-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 chessGame data object itself.

The following JSON included in the payload illustrates the fullest representation of the chessGame 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":"chessGame","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"chessGame":{"id":"ID","playerWhiteId":"ID","playerBlackId":"ID","createdById":"ID","status":"Enum","status_idx":"Integer","mode":"Enum","mode_idx":"Integer","invitationCode":"String","currentFEN":"String","gameType":"Enum","gameType_idx":"Integer","saveStatus":"Enum","saveStatus_idx":"Integer","saveRequestWhite":"Boolean","saveRequestBlack":"Boolean","movedAt":"Date","result":"Enum","result_idx":"Integer","terminatedById":"ID","reportStatus":"Enum","reportStatus_idx":"Integer","guestPlayerWhite":"Boolean","guestPlayerBlack":"Boolean","initialFEN":"String","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event game-retrived

Event topic : wechess-gameplay-service-game-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 chessGame data object itself.

The following JSON included in the payload illustrates the fullest representation of the chessGame 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":"chessGame","method":"GET","action":"get","appVersion":"Version","rowCount":1,"chessGame":{"id":"ID","playerWhiteId":"ID","playerBlackId":"ID","createdById":"ID","status":"Enum","status_idx":"Integer","mode":"Enum","mode_idx":"Integer","invitationCode":"String","currentFEN":"String","gameType":"Enum","gameType_idx":"Integer","saveStatus":"Enum","saveStatus_idx":"Integer","saveRequestWhite":"Boolean","saveRequestBlack":"Boolean","movedAt":"Date","result":"Enum","result_idx":"Integer","terminatedById":"ID","reportStatus":"Enum","reportStatus_idx":"Integer","guestPlayerWhite":"Boolean","guestPlayerBlack":"Boolean","initialFEN":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","moves":[{"moveNumber":"Integer","moveNotation":"String","moveTime":"Integer","movedById":"ID","moveTimestamp":"Date"},{},{}]}}

Route Event games-listed

Event topic : wechess-gameplay-service-games-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 chessGames data object itself.

The following JSON included in the payload illustrates the fullest representation of the chessGames 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":"chessGames","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","chessGames":[{"id":"ID","playerWhiteId":"ID","playerBlackId":"ID","createdById":"ID","status":"Enum","status_idx":"Integer","mode":"Enum","mode_idx":"Integer","invitationCode":"String","currentFEN":"String","gameType":"Enum","gameType_idx":"Integer","saveStatus":"Enum","saveStatus_idx":"Integer","saveRequestWhite":"Boolean","saveRequestBlack":"Boolean","movedAt":"Date","result":"Enum","result_idx":"Integer","terminatedById":"ID","reportStatus":"Enum","reportStatus_idx":"Integer","guestPlayerWhite":"Boolean","guestPlayerBlack":"Boolean","initialFEN":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]}

Route Event gamemove-created

Event topic : wechess-gameplay-service-gamemove-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 chessGameMove data object itself.

The following JSON included in the payload illustrates the fullest representation of the chessGameMove 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":"chessGameMove","method":"POST","action":"create","appVersion":"Version","rowCount":1,"chessGameMove":{"id":"ID","gameId":"ID","moveNumber":"Integer","moveNotation":"String","moveTime":"Integer","movedById":"ID","moveTimestamp":"Date","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event gamemoves-listed

Event topic : wechess-gameplay-service-gamemoves-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 chessGameMoves data object itself.

The following JSON included in the payload illustrates the fullest representation of the chessGameMoves 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":"chessGameMoves","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","chessGameMoves":[{"id":"ID","gameId":"ID","moveNumber":"Integer","moveNotation":"String","moveTime":"Integer","movedById":"ID","moveTimestamp":"Date","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]}

Route Event gameinvitation-created

Event topic : wechess-gameplay-service-gameinvitation-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 chessGameInvitation data object itself.

The following JSON included in the payload illustrates the fullest representation of the chessGameInvitation 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":"chessGameInvitation","method":"POST","action":"create","appVersion":"Version","rowCount":1,"chessGameInvitation":{"id":"ID","gameId":"ID","senderId":"ID","recipientId":"ID","status":"Enum","status_idx":"Integer","expiresAt":"Date","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event gameinvitation-updated

Event topic : wechess-gameplay-service-gameinvitation-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 chessGameInvitation data object itself.

The following JSON included in the payload illustrates the fullest representation of the chessGameInvitation 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":"chessGameInvitation","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"chessGameInvitation":{"id":"ID","gameId":"ID","senderId":"ID","recipientId":"ID","status":"Enum","status_idx":"Integer","expiresAt":"Date","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event gameinvitation-deleted

Event topic : wechess-gameplay-service-gameinvitation-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 chessGameInvitation data object itself.

The following JSON included in the payload illustrates the fullest representation of the chessGameInvitation 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":"chessGameInvitation","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"chessGameInvitation":{"id":"ID","gameId":"ID","senderId":"ID","recipientId":"ID","status":"Enum","status_idx":"Integer","expiresAt":"Date","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event customboard-created

Event topic : wechess-gameplay-service-customboard-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 customBoard data object itself.

The following JSON included in the payload illustrates the fullest representation of the customBoard 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":"customBoard","method":"POST","action":"create","appVersion":"Version","rowCount":1,"customBoard":{"id":"ID","name":"String","fen":"String","description":"Text","isPublished":"Boolean","category":"Enum","category_idx":"Integer","createdById":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event customboard-updated

Event topic : wechess-gameplay-service-customboard-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 customBoard data object itself.

The following JSON included in the payload illustrates the fullest representation of the customBoard 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":"customBoard","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"customBoard":{"id":"ID","name":"String","fen":"String","description":"Text","isPublished":"Boolean","category":"Enum","category_idx":"Integer","createdById":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event customboard-deleted

Event topic : wechess-gameplay-service-customboard-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 customBoard data object itself.

The following JSON included in the payload illustrates the fullest representation of the customBoard 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":"customBoard","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"customBoard":{"id":"ID","name":"String","fen":"String","description":"Text","isPublished":"Boolean","category":"Enum","category_idx":"Integer","createdById":"ID","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event boardtheme-created

Event topic : wechess-gameplay-service-boardtheme-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 boardTheme data object itself.

The following JSON included in the payload illustrates the fullest representation of the boardTheme 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":"boardTheme","method":"POST","action":"create","appVersion":"Version","rowCount":1,"boardTheme":{"id":"ID","name":"String","lightSquare":"String","darkSquare":"String","isPublished":"Boolean","createdById":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event boardtheme-updated

Event topic : wechess-gameplay-service-boardtheme-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 boardTheme data object itself.

The following JSON included in the payload illustrates the fullest representation of the boardTheme 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":"boardTheme","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"boardTheme":{"id":"ID","name":"String","lightSquare":"String","darkSquare":"String","isPublished":"Boolean","createdById":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event boardtheme-deleted

Event topic : wechess-gameplay-service-boardtheme-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 boardTheme data object itself.

The following JSON included in the payload illustrates the fullest representation of the boardTheme 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":"boardTheme","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"boardTheme":{"id":"ID","name":"String","lightSquare":"String","darkSquare":"String","isPublished":"Boolean","createdById":"ID","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event gamehubmessage-deleted

Event topic : wechess-gameplay-service-gamehubmessage-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 gameHubMessage data object itself.

The following JSON included in the payload illustrates the fullest representation of the gameHubMessage 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":"gameHubMessage","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"gameHubMessage":{"id":"ID","roomId":"ID","senderId":"ID","senderName":"String","senderAvatar":"String","messageType":"Enum","messageType_idx":"Integer","content":"Object","timestamp":null,"status":"Enum","status_idx":"Integer","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event gamehubmessage-updated

Event topic : wechess-gameplay-service-gamehubmessage-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 gameHubMessage data object itself.

The following JSON included in the payload illustrates the fullest representation of the gameHubMessage 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":"gameHubMessage","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"gameHubMessage":{"id":"ID","roomId":"ID","senderId":"ID","senderName":"String","senderAvatar":"String","messageType":"Enum","messageType_idx":"Integer","content":"Object","timestamp":null,"status":"Enum","status_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Index Event boardtheme-created

Event topic: elastic-index-wechess_boardtheme-created

Event payload:

{"id":"ID","name":"String","lightSquare":"String","darkSquare":"String","isPublished":"Boolean","createdById":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event boardtheme-updated

Event topic: elastic-index-wechess_boardtheme-created

Event payload:

{"id":"ID","name":"String","lightSquare":"String","darkSquare":"String","isPublished":"Boolean","createdById":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event boardtheme-deleted

Event topic: elastic-index-wechess_boardtheme-deleted

Event payload:

{"id":"ID","name":"String","lightSquare":"String","darkSquare":"String","isPublished":"Boolean","createdById":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event boardtheme-extended

Event topic: elastic-index-wechess_boardtheme-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 game-created

Event topic : wechess-gameplay-service-game-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 chessGame data object itself.

The following JSON included in the payload illustrates the fullest representation of the chessGame 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":"chessGame","method":"POST","action":"create","appVersion":"Version","rowCount":1,"chessGame":{"id":"ID","playerWhiteId":"ID","playerBlackId":"ID","createdById":"ID","status":"Enum","status_idx":"Integer","mode":"Enum","mode_idx":"Integer","invitationCode":"String","currentFEN":"String","gameType":"Enum","gameType_idx":"Integer","saveStatus":"Enum","saveStatus_idx":"Integer","saveRequestWhite":"Boolean","saveRequestBlack":"Boolean","movedAt":"Date","result":"Enum","result_idx":"Integer","terminatedById":"ID","reportStatus":"Enum","reportStatus_idx":"Integer","guestPlayerWhite":"Boolean","guestPlayerBlack":"Boolean","initialFEN":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event game-updated

Event topic : wechess-gameplay-service-game-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 chessGame data object itself.

The following JSON included in the payload illustrates the fullest representation of the chessGame 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":"chessGame","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"chessGame":{"id":"ID","playerWhiteId":"ID","playerBlackId":"ID","createdById":"ID","status":"Enum","status_idx":"Integer","mode":"Enum","mode_idx":"Integer","invitationCode":"String","currentFEN":"String","gameType":"Enum","gameType_idx":"Integer","saveStatus":"Enum","saveStatus_idx":"Integer","saveRequestWhite":"Boolean","saveRequestBlack":"Boolean","movedAt":"Date","result":"Enum","result_idx":"Integer","terminatedById":"ID","reportStatus":"Enum","reportStatus_idx":"Integer","guestPlayerWhite":"Boolean","guestPlayerBlack":"Boolean","initialFEN":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event game-deleted

Event topic : wechess-gameplay-service-game-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 chessGame data object itself.

The following JSON included in the payload illustrates the fullest representation of the chessGame 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":"chessGame","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"chessGame":{"id":"ID","playerWhiteId":"ID","playerBlackId":"ID","createdById":"ID","status":"Enum","status_idx":"Integer","mode":"Enum","mode_idx":"Integer","invitationCode":"String","currentFEN":"String","gameType":"Enum","gameType_idx":"Integer","saveStatus":"Enum","saveStatus_idx":"Integer","saveRequestWhite":"Boolean","saveRequestBlack":"Boolean","movedAt":"Date","result":"Enum","result_idx":"Integer","terminatedById":"ID","reportStatus":"Enum","reportStatus_idx":"Integer","guestPlayerWhite":"Boolean","guestPlayerBlack":"Boolean","initialFEN":"String","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event game-retrived

Event topic : wechess-gameplay-service-game-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 chessGame data object itself.

The following JSON included in the payload illustrates the fullest representation of the chessGame 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":"chessGame","method":"GET","action":"get","appVersion":"Version","rowCount":1,"chessGame":{"id":"ID","playerWhiteId":"ID","playerBlackId":"ID","createdById":"ID","status":"Enum","status_idx":"Integer","mode":"Enum","mode_idx":"Integer","invitationCode":"String","currentFEN":"String","gameType":"Enum","gameType_idx":"Integer","saveStatus":"Enum","saveStatus_idx":"Integer","saveRequestWhite":"Boolean","saveRequestBlack":"Boolean","movedAt":"Date","result":"Enum","result_idx":"Integer","terminatedById":"ID","reportStatus":"Enum","reportStatus_idx":"Integer","guestPlayerWhite":"Boolean","guestPlayerBlack":"Boolean","initialFEN":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","moves":[{"moveNumber":"Integer","moveNotation":"String","moveTime":"Integer","movedById":"ID","moveTimestamp":"Date"},{},{}]}}

Route Event games-listed

Event topic : wechess-gameplay-service-games-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 chessGames data object itself.

The following JSON included in the payload illustrates the fullest representation of the chessGames 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":"chessGames","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","chessGames":[{"id":"ID","playerWhiteId":"ID","playerBlackId":"ID","createdById":"ID","status":"Enum","status_idx":"Integer","mode":"Enum","mode_idx":"Integer","invitationCode":"String","currentFEN":"String","gameType":"Enum","gameType_idx":"Integer","saveStatus":"Enum","saveStatus_idx":"Integer","saveRequestWhite":"Boolean","saveRequestBlack":"Boolean","movedAt":"Date","result":"Enum","result_idx":"Integer","terminatedById":"ID","reportStatus":"Enum","reportStatus_idx":"Integer","guestPlayerWhite":"Boolean","guestPlayerBlack":"Boolean","initialFEN":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]}

Route Event gamemove-created

Event topic : wechess-gameplay-service-gamemove-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 chessGameMove data object itself.

The following JSON included in the payload illustrates the fullest representation of the chessGameMove 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":"chessGameMove","method":"POST","action":"create","appVersion":"Version","rowCount":1,"chessGameMove":{"id":"ID","gameId":"ID","moveNumber":"Integer","moveNotation":"String","moveTime":"Integer","movedById":"ID","moveTimestamp":"Date","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event gamemoves-listed

Event topic : wechess-gameplay-service-gamemoves-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 chessGameMoves data object itself.

The following JSON included in the payload illustrates the fullest representation of the chessGameMoves 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":"chessGameMoves","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","chessGameMoves":[{"id":"ID","gameId":"ID","moveNumber":"Integer","moveNotation":"String","moveTime":"Integer","movedById":"ID","moveTimestamp":"Date","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]}

Route Event gameinvitation-created

Event topic : wechess-gameplay-service-gameinvitation-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 chessGameInvitation data object itself.

The following JSON included in the payload illustrates the fullest representation of the chessGameInvitation 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":"chessGameInvitation","method":"POST","action":"create","appVersion":"Version","rowCount":1,"chessGameInvitation":{"id":"ID","gameId":"ID","senderId":"ID","recipientId":"ID","status":"Enum","status_idx":"Integer","expiresAt":"Date","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event gameinvitation-updated

Event topic : wechess-gameplay-service-gameinvitation-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 chessGameInvitation data object itself.

The following JSON included in the payload illustrates the fullest representation of the chessGameInvitation 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":"chessGameInvitation","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"chessGameInvitation":{"id":"ID","gameId":"ID","senderId":"ID","recipientId":"ID","status":"Enum","status_idx":"Integer","expiresAt":"Date","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event gameinvitation-deleted

Event topic : wechess-gameplay-service-gameinvitation-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 chessGameInvitation data object itself.

The following JSON included in the payload illustrates the fullest representation of the chessGameInvitation 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":"chessGameInvitation","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"chessGameInvitation":{"id":"ID","gameId":"ID","senderId":"ID","recipientId":"ID","status":"Enum","status_idx":"Integer","expiresAt":"Date","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event customboard-created

Event topic : wechess-gameplay-service-customboard-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 customBoard data object itself.

The following JSON included in the payload illustrates the fullest representation of the customBoard 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":"customBoard","method":"POST","action":"create","appVersion":"Version","rowCount":1,"customBoard":{"id":"ID","name":"String","fen":"String","description":"Text","isPublished":"Boolean","category":"Enum","category_idx":"Integer","createdById":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event customboard-updated

Event topic : wechess-gameplay-service-customboard-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 customBoard data object itself.

The following JSON included in the payload illustrates the fullest representation of the customBoard 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":"customBoard","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"customBoard":{"id":"ID","name":"String","fen":"String","description":"Text","isPublished":"Boolean","category":"Enum","category_idx":"Integer","createdById":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event customboard-deleted

Event topic : wechess-gameplay-service-customboard-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 customBoard data object itself.

The following JSON included in the payload illustrates the fullest representation of the customBoard 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":"customBoard","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"customBoard":{"id":"ID","name":"String","fen":"String","description":"Text","isPublished":"Boolean","category":"Enum","category_idx":"Integer","createdById":"ID","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event boardtheme-created

Event topic : wechess-gameplay-service-boardtheme-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 boardTheme data object itself.

The following JSON included in the payload illustrates the fullest representation of the boardTheme 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":"boardTheme","method":"POST","action":"create","appVersion":"Version","rowCount":1,"boardTheme":{"id":"ID","name":"String","lightSquare":"String","darkSquare":"String","isPublished":"Boolean","createdById":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event boardtheme-updated

Event topic : wechess-gameplay-service-boardtheme-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 boardTheme data object itself.

The following JSON included in the payload illustrates the fullest representation of the boardTheme 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":"boardTheme","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"boardTheme":{"id":"ID","name":"String","lightSquare":"String","darkSquare":"String","isPublished":"Boolean","createdById":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event boardtheme-deleted

Event topic : wechess-gameplay-service-boardtheme-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 boardTheme data object itself.

The following JSON included in the payload illustrates the fullest representation of the boardTheme 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":"boardTheme","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"boardTheme":{"id":"ID","name":"String","lightSquare":"String","darkSquare":"String","isPublished":"Boolean","createdById":"ID","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event gamehubmessage-deleted

Event topic : wechess-gameplay-service-gamehubmessage-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 gameHubMessage data object itself.

The following JSON included in the payload illustrates the fullest representation of the gameHubMessage 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":"gameHubMessage","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"gameHubMessage":{"id":"ID","roomId":"ID","senderId":"ID","senderName":"String","senderAvatar":"String","messageType":"Enum","messageType_idx":"Integer","content":"Object","timestamp":null,"status":"Enum","status_idx":"Integer","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event gamehubmessage-updated

Event topic : wechess-gameplay-service-gamehubmessage-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 gameHubMessage data object itself.

The following JSON included in the payload illustrates the fullest representation of the gameHubMessage 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":"gameHubMessage","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"gameHubMessage":{"id":"ID","roomId":"ID","senderId":"ID","senderName":"String","senderAvatar":"String","messageType":"Enum","messageType_idx":"Integer","content":"Object","timestamp":null,"status":"Enum","status_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Index Event userpreference-created

Event topic: elastic-index-wechess_userpreference-created

Event payload:

{"id":"ID","userId":"ID","activeThemeId":"String","soundEnabled":"Boolean","showAnimations":"Boolean","boardOrientation":"Enum","boardOrientation_idx":"Integer","premoveEnabled":"Boolean","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event userpreference-updated

Event topic: elastic-index-wechess_userpreference-created

Event payload:

{"id":"ID","userId":"ID","activeThemeId":"String","soundEnabled":"Boolean","showAnimations":"Boolean","boardOrientation":"Enum","boardOrientation_idx":"Integer","premoveEnabled":"Boolean","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event userpreference-deleted

Event topic: elastic-index-wechess_userpreference-deleted

Event payload:

{"id":"ID","userId":"ID","activeThemeId":"String","soundEnabled":"Boolean","showAnimations":"Boolean","boardOrientation":"Enum","boardOrientation_idx":"Integer","premoveEnabled":"Boolean","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event userpreference-extended

Event topic: elastic-index-wechess_userpreference-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 game-created

Event topic : wechess-gameplay-service-game-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 chessGame data object itself.

The following JSON included in the payload illustrates the fullest representation of the chessGame 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":"chessGame","method":"POST","action":"create","appVersion":"Version","rowCount":1,"chessGame":{"id":"ID","playerWhiteId":"ID","playerBlackId":"ID","createdById":"ID","status":"Enum","status_idx":"Integer","mode":"Enum","mode_idx":"Integer","invitationCode":"String","currentFEN":"String","gameType":"Enum","gameType_idx":"Integer","saveStatus":"Enum","saveStatus_idx":"Integer","saveRequestWhite":"Boolean","saveRequestBlack":"Boolean","movedAt":"Date","result":"Enum","result_idx":"Integer","terminatedById":"ID","reportStatus":"Enum","reportStatus_idx":"Integer","guestPlayerWhite":"Boolean","guestPlayerBlack":"Boolean","initialFEN":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event game-updated

Event topic : wechess-gameplay-service-game-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 chessGame data object itself.

The following JSON included in the payload illustrates the fullest representation of the chessGame 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":"chessGame","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"chessGame":{"id":"ID","playerWhiteId":"ID","playerBlackId":"ID","createdById":"ID","status":"Enum","status_idx":"Integer","mode":"Enum","mode_idx":"Integer","invitationCode":"String","currentFEN":"String","gameType":"Enum","gameType_idx":"Integer","saveStatus":"Enum","saveStatus_idx":"Integer","saveRequestWhite":"Boolean","saveRequestBlack":"Boolean","movedAt":"Date","result":"Enum","result_idx":"Integer","terminatedById":"ID","reportStatus":"Enum","reportStatus_idx":"Integer","guestPlayerWhite":"Boolean","guestPlayerBlack":"Boolean","initialFEN":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event game-deleted

Event topic : wechess-gameplay-service-game-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 chessGame data object itself.

The following JSON included in the payload illustrates the fullest representation of the chessGame 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":"chessGame","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"chessGame":{"id":"ID","playerWhiteId":"ID","playerBlackId":"ID","createdById":"ID","status":"Enum","status_idx":"Integer","mode":"Enum","mode_idx":"Integer","invitationCode":"String","currentFEN":"String","gameType":"Enum","gameType_idx":"Integer","saveStatus":"Enum","saveStatus_idx":"Integer","saveRequestWhite":"Boolean","saveRequestBlack":"Boolean","movedAt":"Date","result":"Enum","result_idx":"Integer","terminatedById":"ID","reportStatus":"Enum","reportStatus_idx":"Integer","guestPlayerWhite":"Boolean","guestPlayerBlack":"Boolean","initialFEN":"String","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event game-retrived

Event topic : wechess-gameplay-service-game-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 chessGame data object itself.

The following JSON included in the payload illustrates the fullest representation of the chessGame 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":"chessGame","method":"GET","action":"get","appVersion":"Version","rowCount":1,"chessGame":{"id":"ID","playerWhiteId":"ID","playerBlackId":"ID","createdById":"ID","status":"Enum","status_idx":"Integer","mode":"Enum","mode_idx":"Integer","invitationCode":"String","currentFEN":"String","gameType":"Enum","gameType_idx":"Integer","saveStatus":"Enum","saveStatus_idx":"Integer","saveRequestWhite":"Boolean","saveRequestBlack":"Boolean","movedAt":"Date","result":"Enum","result_idx":"Integer","terminatedById":"ID","reportStatus":"Enum","reportStatus_idx":"Integer","guestPlayerWhite":"Boolean","guestPlayerBlack":"Boolean","initialFEN":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","moves":[{"moveNumber":"Integer","moveNotation":"String","moveTime":"Integer","movedById":"ID","moveTimestamp":"Date"},{},{}]}}

Route Event games-listed

Event topic : wechess-gameplay-service-games-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 chessGames data object itself.

The following JSON included in the payload illustrates the fullest representation of the chessGames 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":"chessGames","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","chessGames":[{"id":"ID","playerWhiteId":"ID","playerBlackId":"ID","createdById":"ID","status":"Enum","status_idx":"Integer","mode":"Enum","mode_idx":"Integer","invitationCode":"String","currentFEN":"String","gameType":"Enum","gameType_idx":"Integer","saveStatus":"Enum","saveStatus_idx":"Integer","saveRequestWhite":"Boolean","saveRequestBlack":"Boolean","movedAt":"Date","result":"Enum","result_idx":"Integer","terminatedById":"ID","reportStatus":"Enum","reportStatus_idx":"Integer","guestPlayerWhite":"Boolean","guestPlayerBlack":"Boolean","initialFEN":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]}

Route Event gamemove-created

Event topic : wechess-gameplay-service-gamemove-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 chessGameMove data object itself.

The following JSON included in the payload illustrates the fullest representation of the chessGameMove 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":"chessGameMove","method":"POST","action":"create","appVersion":"Version","rowCount":1,"chessGameMove":{"id":"ID","gameId":"ID","moveNumber":"Integer","moveNotation":"String","moveTime":"Integer","movedById":"ID","moveTimestamp":"Date","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event gamemoves-listed

Event topic : wechess-gameplay-service-gamemoves-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 chessGameMoves data object itself.

The following JSON included in the payload illustrates the fullest representation of the chessGameMoves 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":"chessGameMoves","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","chessGameMoves":[{"id":"ID","gameId":"ID","moveNumber":"Integer","moveNotation":"String","moveTime":"Integer","movedById":"ID","moveTimestamp":"Date","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]}

Route Event gameinvitation-created

Event topic : wechess-gameplay-service-gameinvitation-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 chessGameInvitation data object itself.

The following JSON included in the payload illustrates the fullest representation of the chessGameInvitation 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":"chessGameInvitation","method":"POST","action":"create","appVersion":"Version","rowCount":1,"chessGameInvitation":{"id":"ID","gameId":"ID","senderId":"ID","recipientId":"ID","status":"Enum","status_idx":"Integer","expiresAt":"Date","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event gameinvitation-updated

Event topic : wechess-gameplay-service-gameinvitation-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 chessGameInvitation data object itself.

The following JSON included in the payload illustrates the fullest representation of the chessGameInvitation 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":"chessGameInvitation","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"chessGameInvitation":{"id":"ID","gameId":"ID","senderId":"ID","recipientId":"ID","status":"Enum","status_idx":"Integer","expiresAt":"Date","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event gameinvitation-deleted

Event topic : wechess-gameplay-service-gameinvitation-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 chessGameInvitation data object itself.

The following JSON included in the payload illustrates the fullest representation of the chessGameInvitation 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":"chessGameInvitation","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"chessGameInvitation":{"id":"ID","gameId":"ID","senderId":"ID","recipientId":"ID","status":"Enum","status_idx":"Integer","expiresAt":"Date","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event customboard-created

Event topic : wechess-gameplay-service-customboard-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 customBoard data object itself.

The following JSON included in the payload illustrates the fullest representation of the customBoard 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":"customBoard","method":"POST","action":"create","appVersion":"Version","rowCount":1,"customBoard":{"id":"ID","name":"String","fen":"String","description":"Text","isPublished":"Boolean","category":"Enum","category_idx":"Integer","createdById":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event customboard-updated

Event topic : wechess-gameplay-service-customboard-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 customBoard data object itself.

The following JSON included in the payload illustrates the fullest representation of the customBoard 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":"customBoard","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"customBoard":{"id":"ID","name":"String","fen":"String","description":"Text","isPublished":"Boolean","category":"Enum","category_idx":"Integer","createdById":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event customboard-deleted

Event topic : wechess-gameplay-service-customboard-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 customBoard data object itself.

The following JSON included in the payload illustrates the fullest representation of the customBoard 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":"customBoard","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"customBoard":{"id":"ID","name":"String","fen":"String","description":"Text","isPublished":"Boolean","category":"Enum","category_idx":"Integer","createdById":"ID","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event boardtheme-created

Event topic : wechess-gameplay-service-boardtheme-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 boardTheme data object itself.

The following JSON included in the payload illustrates the fullest representation of the boardTheme 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":"boardTheme","method":"POST","action":"create","appVersion":"Version","rowCount":1,"boardTheme":{"id":"ID","name":"String","lightSquare":"String","darkSquare":"String","isPublished":"Boolean","createdById":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event boardtheme-updated

Event topic : wechess-gameplay-service-boardtheme-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 boardTheme data object itself.

The following JSON included in the payload illustrates the fullest representation of the boardTheme 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":"boardTheme","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"boardTheme":{"id":"ID","name":"String","lightSquare":"String","darkSquare":"String","isPublished":"Boolean","createdById":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event boardtheme-deleted

Event topic : wechess-gameplay-service-boardtheme-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 boardTheme data object itself.

The following JSON included in the payload illustrates the fullest representation of the boardTheme 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":"boardTheme","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"boardTheme":{"id":"ID","name":"String","lightSquare":"String","darkSquare":"String","isPublished":"Boolean","createdById":"ID","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event gamehubmessage-deleted

Event topic : wechess-gameplay-service-gamehubmessage-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 gameHubMessage data object itself.

The following JSON included in the payload illustrates the fullest representation of the gameHubMessage 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":"gameHubMessage","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"gameHubMessage":{"id":"ID","roomId":"ID","senderId":"ID","senderName":"String","senderAvatar":"String","messageType":"Enum","messageType_idx":"Integer","content":"Object","timestamp":null,"status":"Enum","status_idx":"Integer","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event gamehubmessage-updated

Event topic : wechess-gameplay-service-gamehubmessage-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 gameHubMessage data object itself.

The following JSON included in the payload illustrates the fullest representation of the gameHubMessage 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":"gameHubMessage","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"gameHubMessage":{"id":"ID","roomId":"ID","senderId":"ID","senderName":"String","senderAvatar":"String","messageType":"Enum","messageType_idx":"Integer","content":"Object","timestamp":null,"status":"Enum","status_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Index Event gamehubmessage-created

Event topic: elastic-index-wechess_gamehubmessage-created

Event payload:

{"id":"ID","roomId":"ID","senderId":"ID","senderName":"String","senderAvatar":"String","messageType":"Enum","messageType_idx":"Integer","content":"Object","timestamp":null,"status":"Enum","status_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event gamehubmessage-updated

Event topic: elastic-index-wechess_gamehubmessage-created

Event payload:

{"id":"ID","roomId":"ID","senderId":"ID","senderName":"String","senderAvatar":"String","messageType":"Enum","messageType_idx":"Integer","content":"Object","timestamp":null,"status":"Enum","status_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event gamehubmessage-deleted

Event topic: elastic-index-wechess_gamehubmessage-deleted

Event payload:

{"id":"ID","roomId":"ID","senderId":"ID","senderName":"String","senderAvatar":"String","messageType":"Enum","messageType_idx":"Integer","content":"Object","timestamp":null,"status":"Enum","status_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event gamehubmessage-extended

Event topic: elastic-index-wechess_gamehubmessage-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 game-created

Event topic : wechess-gameplay-service-game-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 chessGame data object itself.

The following JSON included in the payload illustrates the fullest representation of the chessGame 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":"chessGame","method":"POST","action":"create","appVersion":"Version","rowCount":1,"chessGame":{"id":"ID","playerWhiteId":"ID","playerBlackId":"ID","createdById":"ID","status":"Enum","status_idx":"Integer","mode":"Enum","mode_idx":"Integer","invitationCode":"String","currentFEN":"String","gameType":"Enum","gameType_idx":"Integer","saveStatus":"Enum","saveStatus_idx":"Integer","saveRequestWhite":"Boolean","saveRequestBlack":"Boolean","movedAt":"Date","result":"Enum","result_idx":"Integer","terminatedById":"ID","reportStatus":"Enum","reportStatus_idx":"Integer","guestPlayerWhite":"Boolean","guestPlayerBlack":"Boolean","initialFEN":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event game-updated

Event topic : wechess-gameplay-service-game-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 chessGame data object itself.

The following JSON included in the payload illustrates the fullest representation of the chessGame 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":"chessGame","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"chessGame":{"id":"ID","playerWhiteId":"ID","playerBlackId":"ID","createdById":"ID","status":"Enum","status_idx":"Integer","mode":"Enum","mode_idx":"Integer","invitationCode":"String","currentFEN":"String","gameType":"Enum","gameType_idx":"Integer","saveStatus":"Enum","saveStatus_idx":"Integer","saveRequestWhite":"Boolean","saveRequestBlack":"Boolean","movedAt":"Date","result":"Enum","result_idx":"Integer","terminatedById":"ID","reportStatus":"Enum","reportStatus_idx":"Integer","guestPlayerWhite":"Boolean","guestPlayerBlack":"Boolean","initialFEN":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event game-deleted

Event topic : wechess-gameplay-service-game-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 chessGame data object itself.

The following JSON included in the payload illustrates the fullest representation of the chessGame 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":"chessGame","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"chessGame":{"id":"ID","playerWhiteId":"ID","playerBlackId":"ID","createdById":"ID","status":"Enum","status_idx":"Integer","mode":"Enum","mode_idx":"Integer","invitationCode":"String","currentFEN":"String","gameType":"Enum","gameType_idx":"Integer","saveStatus":"Enum","saveStatus_idx":"Integer","saveRequestWhite":"Boolean","saveRequestBlack":"Boolean","movedAt":"Date","result":"Enum","result_idx":"Integer","terminatedById":"ID","reportStatus":"Enum","reportStatus_idx":"Integer","guestPlayerWhite":"Boolean","guestPlayerBlack":"Boolean","initialFEN":"String","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event game-retrived

Event topic : wechess-gameplay-service-game-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 chessGame data object itself.

The following JSON included in the payload illustrates the fullest representation of the chessGame 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":"chessGame","method":"GET","action":"get","appVersion":"Version","rowCount":1,"chessGame":{"id":"ID","playerWhiteId":"ID","playerBlackId":"ID","createdById":"ID","status":"Enum","status_idx":"Integer","mode":"Enum","mode_idx":"Integer","invitationCode":"String","currentFEN":"String","gameType":"Enum","gameType_idx":"Integer","saveStatus":"Enum","saveStatus_idx":"Integer","saveRequestWhite":"Boolean","saveRequestBlack":"Boolean","movedAt":"Date","result":"Enum","result_idx":"Integer","terminatedById":"ID","reportStatus":"Enum","reportStatus_idx":"Integer","guestPlayerWhite":"Boolean","guestPlayerBlack":"Boolean","initialFEN":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","moves":[{"moveNumber":"Integer","moveNotation":"String","moveTime":"Integer","movedById":"ID","moveTimestamp":"Date"},{},{}]}}

Route Event games-listed

Event topic : wechess-gameplay-service-games-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 chessGames data object itself.

The following JSON included in the payload illustrates the fullest representation of the chessGames 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":"chessGames","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","chessGames":[{"id":"ID","playerWhiteId":"ID","playerBlackId":"ID","createdById":"ID","status":"Enum","status_idx":"Integer","mode":"Enum","mode_idx":"Integer","invitationCode":"String","currentFEN":"String","gameType":"Enum","gameType_idx":"Integer","saveStatus":"Enum","saveStatus_idx":"Integer","saveRequestWhite":"Boolean","saveRequestBlack":"Boolean","movedAt":"Date","result":"Enum","result_idx":"Integer","terminatedById":"ID","reportStatus":"Enum","reportStatus_idx":"Integer","guestPlayerWhite":"Boolean","guestPlayerBlack":"Boolean","initialFEN":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]}

Route Event gamemove-created

Event topic : wechess-gameplay-service-gamemove-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 chessGameMove data object itself.

The following JSON included in the payload illustrates the fullest representation of the chessGameMove 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":"chessGameMove","method":"POST","action":"create","appVersion":"Version","rowCount":1,"chessGameMove":{"id":"ID","gameId":"ID","moveNumber":"Integer","moveNotation":"String","moveTime":"Integer","movedById":"ID","moveTimestamp":"Date","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event gamemoves-listed

Event topic : wechess-gameplay-service-gamemoves-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 chessGameMoves data object itself.

The following JSON included in the payload illustrates the fullest representation of the chessGameMoves 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":"chessGameMoves","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","chessGameMoves":[{"id":"ID","gameId":"ID","moveNumber":"Integer","moveNotation":"String","moveTime":"Integer","movedById":"ID","moveTimestamp":"Date","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]}

Route Event gameinvitation-created

Event topic : wechess-gameplay-service-gameinvitation-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 chessGameInvitation data object itself.

The following JSON included in the payload illustrates the fullest representation of the chessGameInvitation 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":"chessGameInvitation","method":"POST","action":"create","appVersion":"Version","rowCount":1,"chessGameInvitation":{"id":"ID","gameId":"ID","senderId":"ID","recipientId":"ID","status":"Enum","status_idx":"Integer","expiresAt":"Date","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event gameinvitation-updated

Event topic : wechess-gameplay-service-gameinvitation-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 chessGameInvitation data object itself.

The following JSON included in the payload illustrates the fullest representation of the chessGameInvitation 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":"chessGameInvitation","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"chessGameInvitation":{"id":"ID","gameId":"ID","senderId":"ID","recipientId":"ID","status":"Enum","status_idx":"Integer","expiresAt":"Date","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event gameinvitation-deleted

Event topic : wechess-gameplay-service-gameinvitation-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 chessGameInvitation data object itself.

The following JSON included in the payload illustrates the fullest representation of the chessGameInvitation 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":"chessGameInvitation","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"chessGameInvitation":{"id":"ID","gameId":"ID","senderId":"ID","recipientId":"ID","status":"Enum","status_idx":"Integer","expiresAt":"Date","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event customboard-created

Event topic : wechess-gameplay-service-customboard-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 customBoard data object itself.

The following JSON included in the payload illustrates the fullest representation of the customBoard 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":"customBoard","method":"POST","action":"create","appVersion":"Version","rowCount":1,"customBoard":{"id":"ID","name":"String","fen":"String","description":"Text","isPublished":"Boolean","category":"Enum","category_idx":"Integer","createdById":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event customboard-updated

Event topic : wechess-gameplay-service-customboard-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 customBoard data object itself.

The following JSON included in the payload illustrates the fullest representation of the customBoard 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":"customBoard","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"customBoard":{"id":"ID","name":"String","fen":"String","description":"Text","isPublished":"Boolean","category":"Enum","category_idx":"Integer","createdById":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event customboard-deleted

Event topic : wechess-gameplay-service-customboard-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 customBoard data object itself.

The following JSON included in the payload illustrates the fullest representation of the customBoard 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":"customBoard","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"customBoard":{"id":"ID","name":"String","fen":"String","description":"Text","isPublished":"Boolean","category":"Enum","category_idx":"Integer","createdById":"ID","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event boardtheme-created

Event topic : wechess-gameplay-service-boardtheme-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 boardTheme data object itself.

The following JSON included in the payload illustrates the fullest representation of the boardTheme 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":"boardTheme","method":"POST","action":"create","appVersion":"Version","rowCount":1,"boardTheme":{"id":"ID","name":"String","lightSquare":"String","darkSquare":"String","isPublished":"Boolean","createdById":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event boardtheme-updated

Event topic : wechess-gameplay-service-boardtheme-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 boardTheme data object itself.

The following JSON included in the payload illustrates the fullest representation of the boardTheme 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":"boardTheme","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"boardTheme":{"id":"ID","name":"String","lightSquare":"String","darkSquare":"String","isPublished":"Boolean","createdById":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event boardtheme-deleted

Event topic : wechess-gameplay-service-boardtheme-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 boardTheme data object itself.

The following JSON included in the payload illustrates the fullest representation of the boardTheme 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":"boardTheme","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"boardTheme":{"id":"ID","name":"String","lightSquare":"String","darkSquare":"String","isPublished":"Boolean","createdById":"ID","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event gamehubmessage-deleted

Event topic : wechess-gameplay-service-gamehubmessage-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 gameHubMessage data object itself.

The following JSON included in the payload illustrates the fullest representation of the gameHubMessage 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":"gameHubMessage","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"gameHubMessage":{"id":"ID","roomId":"ID","senderId":"ID","senderName":"String","senderAvatar":"String","messageType":"Enum","messageType_idx":"Integer","content":"Object","timestamp":null,"status":"Enum","status_idx":"Integer","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event gamehubmessage-updated

Event topic : wechess-gameplay-service-gamehubmessage-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 gameHubMessage data object itself.

The following JSON included in the payload illustrates the fullest representation of the gameHubMessage 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":"gameHubMessage","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"gameHubMessage":{"id":"ID","roomId":"ID","senderId":"ID","senderName":"String","senderAvatar":"String","messageType":"Enum","messageType_idx":"Integer","content":"Object","timestamp":null,"status":"Enum","status_idx":"Integer","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Index Event gamehubmoderation-created

Event topic: elastic-index-wechess_gamehubmoderation-created

Event payload:

{"id":"ID","roomId":"ID","userId":"ID","action":"Enum","action_idx":"Integer","reason":"Text","duration":"Integer","expiresAt":null,"issuedBy":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event gamehubmoderation-updated

Event topic: elastic-index-wechess_gamehubmoderation-created

Event payload:

{"id":"ID","roomId":"ID","userId":"ID","action":"Enum","action_idx":"Integer","reason":"Text","duration":"Integer","expiresAt":null,"issuedBy":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event gamehubmoderation-deleted

Event topic: elastic-index-wechess_gamehubmoderation-deleted

Event payload:

{"id":"ID","roomId":"ID","userId":"ID","action":"Enum","action_idx":"Integer","reason":"Text","duration":"Integer","expiresAt":null,"issuedBy":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event gamehubmoderation-extended

Event topic: elastic-index-wechess_gamehubmoderation-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 game-created

Event topic : wechess-gameplay-service-game-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 chessGame data object itself.

The following JSON included in the payload illustrates the fullest representation of the chessGame 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":"chessGame","method":"POST","action":"create","appVersion":"Version","rowCount":1,"chessGame":{"id":"ID","playerWhiteId":"ID","playerBlackId":"ID","createdById":"ID","status":"Enum","status_idx":"Integer","mode":"Enum","mode_idx":"Integer","invitationCode":"String","currentFEN":"String","gameType":"Enum","gameType_idx":"Integer","saveStatus":"Enum","saveStatus_idx":"Integer","saveRequestWhite":"Boolean","saveRequestBlack":"Boolean","movedAt":"Date","result":"Enum","result_idx":"Integer","terminatedById":"ID","reportStatus":"Enum","reportStatus_idx":"Integer","guestPlayerWhite":"Boolean","guestPlayerBlack":"Boolean","initialFEN":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event game-updated

Event topic : wechess-gameplay-service-game-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 chessGame data object itself.

The following JSON included in the payload illustrates the fullest representation of the chessGame 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":"chessGame","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"chessGame":{"id":"ID","playerWhiteId":"ID","playerBlackId":"ID","createdById":"ID","status":"Enum","status_idx":"Integer","mode":"Enum","mode_idx":"Integer","invitationCode":"String","currentFEN":"String","gameType":"Enum","gameType_idx":"Integer","saveStatus":"Enum","saveStatus_idx":"Integer","saveRequestWhite":"Boolean","saveRequestBlack":"Boolean","movedAt":"Date","result":"Enum","result_idx":"Integer","terminatedById":"ID","reportStatus":"Enum","reportStatus_idx":"Integer","guestPlayerWhite":"Boolean","guestPlayerBlack":"Boolean","initialFEN":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event game-deleted

Event topic : wechess-gameplay-service-game-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 chessGame data object itself.

The following JSON included in the payload illustrates the fullest representation of the chessGame 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":"chessGame","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"chessGame":{"id":"ID","playerWhiteId":"ID","playerBlackId":"ID","createdById":"ID","status":"Enum","status_idx":"Integer","mode":"Enum","mode_idx":"Integer","invitationCode":"String","currentFEN":"String","gameType":"Enum","gameType_idx":"Integer","saveStatus":"Enum","saveStatus_idx":"Integer","saveRequestWhite":"Boolean","saveRequestBlack":"Boolean","movedAt":"Date","result":"Enum","result_idx":"Integer","terminatedById":"ID","reportStatus":"Enum","reportStatus_idx":"Integer","guestPlayerWhite":"Boolean","guestPlayerBlack":"Boolean","initialFEN":"String","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event game-retrived

Event topic : wechess-gameplay-service-game-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 chessGame data object itself.

The following JSON included in the payload illustrates the fullest representation of the chessGame 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":"chessGame","method":"GET","action":"get","appVersion":"Version","rowCount":1,"chessGame":{"id":"ID","playerWhiteId":"ID","playerBlackId":"ID","createdById":"ID","status":"Enum","status_idx":"Integer","mode":"Enum","mode_idx":"Integer","invitationCode":"String","currentFEN":"String","gameType":"Enum","gameType_idx":"Integer","saveStatus":"Enum","saveStatus_idx":"Integer","saveRequestWhite":"Boolean","saveRequestBlack":"Boolean","movedAt":"Date","result":"Enum","result_idx":"Integer","terminatedById":"ID","reportStatus":"Enum","reportStatus_idx":"Integer","guestPlayerWhite":"Boolean","guestPlayerBlack":"Boolean","initialFEN":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","moves":[{"moveNumber":"Integer","moveNotation":"String","moveTime":"Integer","movedById":"ID","moveTimestamp":"Date"},{},{}]}}

Route Event games-listed

Event topic : wechess-gameplay-service-games-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 chessGames data object itself.

The following JSON included in the payload illustrates the fullest representation of the chessGames 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":"chessGames","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","chessGames":[{"id":"ID","playerWhiteId":"ID","playerBlackId":"ID","createdById":"ID","status":"Enum","status_idx":"Integer","mode":"Enum","mode_idx":"Integer","invitationCode":"String","currentFEN":"String","gameType":"Enum","gameType_idx":"Integer","saveStatus":"Enum","saveStatus_idx":"Integer","saveRequestWhite":"Boolean","saveRequestBlack":"Boolean","movedAt":"Date","result":"Enum","result_idx":"Integer","terminatedById":"ID","reportStatus":"Enum","reportStatus_idx":"Integer","guestPlayerWhite":"Boolean","guestPlayerBlack":"Boolean","initialFEN":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]}

Route Event gamemove-created

Event topic : wechess-gameplay-service-gamemove-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 chessGameMove data object itself.

The following JSON included in the payload illustrates the fullest representation of the chessGameMove 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":"chessGameMove","method":"POST","action":"create","appVersion":"Version","rowCount":1,"chessGameMove":{"id":"ID","gameId":"ID","moveNumber":"Integer","moveNotation":"String","moveTime":"Integer","movedById":"ID","moveTimestamp":"Date","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event gamemoves-listed

Event topic : wechess-gameplay-service-gamemoves-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 chessGameMoves data object itself.

The following JSON included in the payload illustrates the fullest representation of the chessGameMoves 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":"chessGameMoves","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","chessGameMoves":[{"id":"ID","gameId":"ID","moveNumber":"Integer","moveNotation":"String","moveTime":"Integer","movedById":"ID","moveTimestamp":"Date","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]}

Route Event gameinvitation-created

Event topic : wechess-gameplay-service-gameinvitation-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 chessGameInvitation data object itself.

The following JSON included in the payload illustrates the fullest representation of the chessGameInvitation 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":"chessGameInvitation","method":"POST","action":"create","appVersion":"Version","rowCount":1,"chessGameInvitation":{"id":"ID","gameId":"ID","senderId":"ID","recipientId":"ID","status":"Enum","status_idx":"Integer","expiresAt":"Date","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event gameinvitation-updated

Event topic : wechess-gameplay-service-gameinvitation-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 chessGameInvitation data object itself.

The following JSON included in the payload illustrates the fullest representation of the chessGameInvitation 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":"chessGameInvitation","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"chessGameInvitation":{"id":"ID","gameId":"ID","senderId":"ID","recipientId":"ID","status":"Enum","status_idx":"Integer","expiresAt":"Date","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event gameinvitation-deleted

Event topic : wechess-gameplay-service-gameinvitation-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 chessGameInvitation data object itself.

The following JSON included in the payload illustrates the fullest representation of the chessGameInvitation 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":"chessGameInvitation","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"chessGameInvitation":{"id":"ID","gameId":"ID","senderId":"ID","recipientId":"ID","status":"Enum","status_idx":"Integer","expiresAt":"Date","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event customboard-created

Event topic : wechess-gameplay-service-customboard-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 customBoard data object itself.

The following JSON included in the payload illustrates the fullest representation of the customBoard 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":"customBoard","method":"POST","action":"create","appVersion":"Version","rowCount":1,"customBoard":{"id":"ID","name":"String","fen":"String","description":"Text","isPublished":"Boolean","category":"Enum","category_idx":"Integer","createdById":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event customboard-updated

Event topic : wechess-gameplay-service-customboard-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 customBoard data object itself.

The following JSON included in the payload illustrates the fullest representation of the customBoard 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":"customBoard","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"customBoard":{"id":"ID","name":"String","fen":"String","description":"Text","isPublished":"Boolean","category":"Enum","category_idx":"Integer","createdById":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event customboard-deleted

Event topic : wechess-gameplay-service-customboard-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 customBoard data object itself.

The following JSON included in the payload illustrates the fullest representation of the customBoard 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":"customBoard","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"customBoard":{"id":"ID","name":"String","fen":"String","description":"Text","isPublished":"Boolean","category":"Enum","category_idx":"Integer","createdById":"ID","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event boardtheme-created

Event topic : wechess-gameplay-service-boardtheme-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 boardTheme data object itself.

The following JSON included in the payload illustrates the fullest representation of the boardTheme 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":"boardTheme","method":"POST","action":"create","appVersion":"Version","rowCount":1,"boardTheme":{"id":"ID","name":"String","lightSquare":"String","darkSquare":"String","isPublished":"Boolean","createdById":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event boardtheme-updated

Event topic : wechess-gameplay-service-boardtheme-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 boardTheme data object itself.

The following JSON included in the payload illustrates the fullest representation of the boardTheme 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":"boardTheme","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"boardTheme":{"id":"ID","name":"String","lightSquare":"String","darkSquare":"String","isPublished":"Boolean","createdById":"ID","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event boardtheme-deleted

Event topic : wechess-gameplay-service-boardtheme-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 boardTheme data object itself.

The following JSON included in the payload illustrates the fullest representation of the boardTheme 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":"boardTheme","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"boardTheme":{"id":"ID","name":"String","lightSquare":"String","darkSquare":"String","isPublished":"Boolean","createdById":"ID","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event gamehubmessage-deleted

Event topic : wechess-gameplay-service-gamehubmessage-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 gameHubMessage data object itself.

The following JSON included in the payload illustrates the fullest representation of the gameHubMessage 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":"gameHubMessage","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"gameHubMessage":{"id":"ID","roomId":"ID","senderId":"ID","senderName":"String","senderAvatar":"String","messageType":"Enum","messageType_idx":"Integer","content":"Object","timestamp":null,"status":"Enum","status_idx":"Integer","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event gamehubmessage-updated

Event topic : wechess-gameplay-service-gamehubmessage-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 gameHubMessage data object itself.

The following JSON included in the payload illustrates the fullest representation of the gameHubMessage 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":"gameHubMessage","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"gameHubMessage":{"id":"ID","roomId":"ID","senderId":"ID","senderName":"String","senderAvatar":"String","messageType":"Enum","messageType_idx":"Integer","content":"Object","timestamp":null,"status":"Enum","status_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 chessGame

Service Design Specification - Object Design for chessGame

wechess-gameplay-service documentation

Document Overview

This document outlines the object design for the chessGame model in our application. It includes details about the model’s attributes, relationships, and any specific validation or business logic that applies.

chessGame Data Object

Object Overview

Description: No description provided.

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
playerWhiteId ID Yes User ID of the player assigned White (guest or registered); references auth:user.id.
playerBlackId ID No -
createdById ID Yes ID of the user who created the game (can be a guest or registered user).
status Enum Yes Lifecycle status: pending, active, paused, completed, terminated
mode Enum Yes Game mode: public (matchmaking), private (invitation-based)
invitationCode String No -
currentFEN String Yes Current board state in FEN notation for restoration/resume.
gameType Enum Yes Game type: timed, untimed, blitz, rapid
saveStatus Enum Yes Game mutual-saving: notSaveable, requested, paused (both agreed)
saveRequestWhite Boolean No Whether white has requested save/resume; mutual save when both true.
saveRequestBlack Boolean No Whether black has requested save/resume; mutual save when both true.
movedAt Date No Timestamp of last move (heartbeat/game activity).
result Enum No Game result/outcome: whiteWin, blackWin, draw, aborted
terminatedById ID No ID of administrator who forced terminated the game (if applicable).
reportStatus Enum No Moderation/review status: none, reported, underReview
guestPlayerWhite Boolean No True if white is a guest (not a registered user); needed to distinguish guest/registered in history.
guestPlayerBlack Boolean No True if black is a guest (not a registered user); needed to distinguish guest/registered in history.
initialFEN String No The starting FEN position when the game was created. Used to identify custom games.

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

playerWhiteId createdById mode invitationCode gameType initialFEN

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

playerWhiteId playerBlackId createdById status mode invitationCode currentFEN gameType saveStatus saveRequestWhite saveRequestBlack movedAt result terminatedById reportStatus guestPlayerWhite guestPlayerBlack initialFEN

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

playerWhiteId playerBlackId createdById status mode invitationCode currentFEN gameType saveStatus saveRequestWhite saveRequestBlack movedAt result terminatedById reportStatus guestPlayerWhite guestPlayerBlack initialFEN

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

playerWhiteId playerBlackId createdById status mode invitationCode movedAt result

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

mode invitationCode

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

playerWhiteId playerBlackId createdById terminatedById

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

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: 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: No

Filter Properties

status invitationCode

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 chessGameMove

Service Design Specification - Object Design for chessGameMove

wechess-gameplay-service documentation

Document Overview

This document outlines the object design for the chessGameMove model in our application. It includes details about the model’s attributes, relationships, and any specific validation or business logic that applies.

chessGameMove Data Object

Object Overview

Description: Represents a single move in a chess game (FIDE-compliant SAN/LAN representation, timestamp, player, time, move number).

This object represents a core data structure within the service and acts as the blueprint for database interaction, API generation, and business logic enforcement. It is defined using the ObjectSettings pattern, which governs its behavior, access control, caching strategy, and integration points with other systems such as Stripe and Redis.

Core Configuration

Composite Indexes

The index also defines a conflict resolution strategy for duplicate key violations.

When a new record would violate this composite index, the following action will be taken:

On Duplicate: throwError

An error will be thrown, preventing the insertion of conflicting data.

Properties Schema

Display Label Property: moveNotation — This property is the default display label for records of this data object. Relation dropdowns and record references in the frontend will show the value of this property as the human-readable label.

Property Type Required Description
gameId ID Yes Reference to the chessGame this move belongs to.
moveNumber Integer Yes Move number (starting from 1 in each game).
moveNotation String Yes Chess move in either Standard Algebraic or Long Algebraic Notation (SAN/LAN).
moveTime Integer No Time in milliseconds since the previous move (for time control, etc.).
movedById ID Yes User ID of the player who made the move (guest/registered); references auth:user.id.
moveTimestamp Date Yes Timestamp when move was made.

Default Values

Default values are automatically assigned to properties when a new object is created, if no value is provided in the request body. Since default values are applied on db level, they should be literal values, not expressions.If you want to use expressions, you can use transposed parameters in any business API to set default values dynamically.

Constant Properties

gameId moveNumber moveNotation moveTime movedById moveTimestamp

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

gameId moveNumber moveNotation moveTime movedById moveTimestamp

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

gameId moveNumber moveNotation movedById moveTimestamp

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

gameId moveNumber moveTimestamp

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

gameId moveNumber

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

gameId movedById

Mindbricks supports relations between data objects, allowing you to define how objects are linked together. You can define relations in the data object properties, which will be used to create foreign key constraints in the database. For complex joins operations, Mindbricks supportsa BFF pattern, where you can view dynamic and static views based on Elastic Search Indexes. Use db level relations for simple one-to-one or one-to-many relationships, and use BFF views for complex joins that require multiple data objects to be joined together.

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

On Delete: Set Null Required: Yes

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

On Delete: Set Null Required: No

Filter Properties

gameId

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 chessGameInvitation

Service Design Specification - Object Design for chessGameInvitation

wechess-gameplay-service documentation

Document Overview

This document outlines the object design for the chessGameInvitation model in our application. It includes details about the model’s attributes, relationships, and any specific validation or business logic that applies.

chessGameInvitation Data Object

Object Overview

Description: An invitation for a private chess game between two players; status tracked; expires at set time or when accepted/declined.

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
gameId ID Yes Game this invitation is linked to.
senderId ID Yes -
recipientId ID Yes -
status Enum Yes -
expiresAt Date Yes Expiration date/time for the invitation.

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

gameId

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

gameId senderId recipientId status expiresAt

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

gameId senderId recipientId status expiresAt

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

gameId senderId recipientId expiresAt

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

gameId

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

gameId senderId recipientId

Mindbricks supports relations between data objects, allowing you to define how objects are linked together. You can define relations in the data object properties, which will be used to create foreign key constraints in the database. For complex joins operations, Mindbricks supportsa BFF pattern, where you can view dynamic and static views based on Elastic Search Indexes. Use db level relations for simple one-to-one or one-to-many relationships, and use BFF views for complex joins that require multiple data objects to be joined together.

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

On Delete: Set Null Required: Yes

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

On Delete: Set Null Required: No

The target object is a parent object, meaning that the relation is a one-to-many relationship from target to this object.

On Delete: Set Null Required: No

Filter Properties

senderId recipientId status

Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API’s that have “Auto Params” enabled.


Service Design Specification - Object Design for customBoard

Service Design Specification - Object Design for customBoard

wechess-gameplay-service documentation

Document Overview

This document outlines the object design for the customBoard model in our application. It includes details about the model’s attributes, relationships, and any specific validation or business logic that applies.

customBoard Data Object

Object Overview

Description: No description provided.

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

Display Label Property: name — This property is the default display label for records of this data object. Relation dropdowns and record references in the frontend will show the value of this property as the human-readable label.

Property Type Required Description
name String Yes Name of the custom board position
fen String Yes FEN string representing the board position
description Text No Optional description of the custom board
isPublished Boolean Yes -
category Enum Yes -
createdById ID Yes -

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

name fen description isPublished category createdById

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

name fen description isPublished category createdById

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 isPublished category createdById

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

createdById

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

isPublished category createdById

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 boardTheme

Service Design Specification - Object Design for boardTheme

wechess-gameplay-service documentation

Document Overview

This document outlines the object design for the boardTheme model in our application. It includes details about the model’s attributes, relationships, and any specific validation or business logic that applies.

boardTheme Data Object

Object Overview

Description: No description provided.

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

Display Label Property: name — This property is the default display label for records of this data object. Relation dropdowns and record references in the frontend will show the value of this property as the human-readable label.

Property Type Required Description
name String Yes Theme display name
lightSquare String Yes Hex color for light squares
darkSquare String Yes Hex color for dark squares
isPublished Boolean No Whether the theme is publicly visible
createdById ID Yes User who created this theme

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

createdById

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

name lightSquare darkSquare isPublished createdById

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

name lightSquare darkSquare isPublished createdById

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 isPublished createdById

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

createdById

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

isPublished

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 userPreference

Service Design Specification - Object Design for userPreference

wechess-gameplay-service documentation

Document Overview

This document outlines the object design for the userPreference model in our application. It includes details about the model’s attributes, relationships, and any specific validation or business logic that applies.

userPreference Data Object

Object Overview

Description: No description provided.

This object represents a core data structure within the service and acts as the blueprint for database interaction, API generation, and business logic enforcement. It is defined using the ObjectSettings pattern, which governs its behavior, access control, caching strategy, and integration points with other systems such as Stripe and Redis.

Core Configuration

Properties Schema

Property Type Required Description
userId ID Yes The user this preferences record belongs to
activeThemeId String No ID of the currently selected board theme (preset ID or custom theme ID)
soundEnabled Boolean No Whether game sounds are enabled
showAnimations Boolean No Whether board animations are shown
boardOrientation Enum No Default board orientation preference
premoveEnabled Boolean No Whether premove feature is enabled

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

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

userId activeThemeId soundEnabled showAnimations boardOrientation premoveEnabled

An update crud API created with the option Auto Params enabled will automatically update these properties with the provided values in the request body. If you want to update any property in your own business logic not by user input, you can set the Allow Auto Update option to false. These properties will be added to the update API’s body parameters and can be updated by the user if any value is provided in the request body.

Enum Properties

Enum properties are defined with a set of allowed values, ensuring that only valid options can be assigned to them. The enum options value will be stored as strings in the database, but when a data object is created an addtional property with the same name plus an idx suffix will be created, which will hold the index of the selected enum option. You can use the index property to sort by the enum value or when your enum options represent a sequence of values.

Elastic Search Indexing

userId activeThemeId soundEnabled showAnimations boardOrientation premoveEnabled

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

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

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.

Relation Properties

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: No


Service Design Specification - Object Design for gameHubMessage

Service Design Specification - Object Design for gameHubMessage

wechess-gameplay-service documentation

Document Overview

This document outlines the object design for the gameHubMessage model in our application. It includes details about the model’s attributes, relationships, and any specific validation or business logic that applies.

gameHubMessage Data Object

Object Overview

Description: Auto-generated message DataObject for the gameHub RealtimeHub. Stores all messages with typed content payloads.

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
roomId ID Yes Reference to the room this message belongs to
senderId ID No Reference to the user who sent this message
senderName String No Display name of the sender (denormalized from user profile at send time)
senderAvatar String No Avatar URL of the sender (denormalized from user profile at send time)
messageType Enum Yes Content type discriminator for this message
content Object Yes Type-specific content payload (structure depends on messageType)
timestamp No Message creation time
status Enum No Message moderation status

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

roomId senderId senderName senderAvatar messageType timestamp

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

roomId senderId senderName senderAvatar messageType content timestamp status

An update crud API created with the option Auto Params enabled will automatically update these properties with the provided values in the request body. If you want to update any property in your own business logic not by user input, you can set the Allow Auto Update option to false. These properties will be added to the update API’s body parameters and can be updated by the user if any value is provided in the request body.

Enum Properties

Enum properties are defined with a set of allowed values, ensuring that only valid options can be assigned to them. The enum options value will be stored as strings in the database, but when a data object is created an addtional property with the same name plus an idx suffix will be created, which will hold the index of the selected enum option. You can use the index property to sort by the enum value or when your enum options represent a sequence of values.

Elastic Search Indexing

roomId senderId senderName senderAvatar messageType content timestamp status

Properties that are indexed in Elastic Search will be searchable via the Elastic Search API. While all properties are stored in the elastic search index of the data object, only those marked for Elastic Search indexing will be available for search queries.

Database Indexing

roomId senderId senderName senderAvatar messageType content timestamp status

Properties that are indexed in the database will be optimized for query performance, allowing for faster data retrieval. Make a property indexed in the database if you want to use it frequently in query filters or sorting.

Secondary Key Properties

roomId

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

senderId

Session data properties are used to store data that is specific to the user session, allowing for personalized experiences and temporary data storage. If a property is configured as session data, it will be automatically mapped to the related field in the user session during CRUD operations. Note that session data properties can not be mutated by the user, but only by the system.

Filter Properties

roomId senderId senderName senderAvatar messageType content timestamp status

Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API’s that have “Auto Params” enabled.


Service Design Specification - Object Design for gameHubModeration

Service Design Specification - Object Design for gameHubModeration

wechess-gameplay-service documentation

Document Overview

This document outlines the object design for the gameHubModeration model in our application. It includes details about the model’s attributes, relationships, and any specific validation or business logic that applies.

gameHubModeration Data Object

Object Overview

Description: Auto-generated moderation DataObject for the gameHub RealtimeHub. Stores block and silence actions for room-level user moderation.

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
roomId ID Yes Reference to the room where the moderation action applies
userId ID Yes The user who is blocked or silenced
action Enum Yes Moderation action type
reason Text No Optional reason for the moderation action
duration Integer No Duration in seconds. 0 means permanent
expiresAt No Expiry timestamp. Null means permanent
issuedBy ID No The moderator who issued the action

Default Values

Default values are automatically assigned to properties when a new object is created, if no value is provided in the request body. Since default values are applied on db level, they should be literal values, not expressions.If you want to use expressions, you can use transposed parameters in any business API to set default values dynamically.

Constant Properties

roomId userId action duration expiresAt issuedBy

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

roomId userId action reason duration expiresAt issuedBy

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

roomId userId action reason duration expiresAt issuedBy

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

roomId userId action reason duration expiresAt issuedBy

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

roomId userId

Secondary key properties are used to create an additional indexed identifiers for the data object, allowing for alternative access patterns. Different than normal indexed properties, secondary keys will act as primary keys and Mindbricks will provide automatic secondary key db utility functions to access the data object by the secondary key.

Relation Properties

roomId

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

issuedBy

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

roomId userId action reason duration expiresAt issuedBy

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 Game

Business API Design Specification - Create Game

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 createGame 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 createGame Business API is designed to handle a create operation on the ChessGame 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 chess game session (public or private). Sets up all initial state, assigns player roles, and sets mode.

API Frontend Description By The Backend Architect

Called when matchmaking or private game is created. Invited/private games have invitationCode. Only logged-in users (guest or registered) can create games. Raise event for gameCreated for notification/bff.

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 createGame Business API includes a REST controller that can be triggered via the following route:

/v1/game

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 createGame Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The createGame Business API has 19 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
chessGameId ID No - body chessGameId
Description: This id paremeter is used to create the data object with a given specific id. Leave null for automatic id.
playerWhiteId ID Yes - body playerWhiteId
Description: User ID of the player assigned White (guest or registered); references auth:user.id.
playerBlackId ID No - body playerBlackId
Description: -
createdById ID Yes - body createdById
Description: ID of the user who created the game (can be a guest or registered user).
status Enum Yes - body status
Description: Lifecycle status: pending, active, paused, completed, terminated
mode Enum Yes - body mode
Description: Game mode: public (matchmaking), private (invitation-based)
invitationCode String No - body invitationCode
Description: -
currentFEN String Yes - body currentFEN
Description: Current board state in FEN notation for restoration/resume.
gameType Enum Yes - body gameType
Description: Game type: timed, untimed, blitz, rapid
saveStatus Enum Yes - body saveStatus
Description: Game mutual-saving: notSaveable, requested, paused (both agreed)
saveRequestWhite Boolean No - body saveRequestWhite
Description: Whether white has requested save/resume; mutual save when both true.
saveRequestBlack Boolean No - body saveRequestBlack
Description: Whether black has requested save/resume; mutual save when both true.
movedAt Date No - body movedAt
Description: Timestamp of last move (heartbeat/game activity).
result Enum No - body result
Description: Game result/outcome: whiteWin, blackWin, draw, aborted
terminatedById ID No - body terminatedById
Description: ID of administrator who forced terminated the game (if applicable).
reportStatus Enum No - body reportStatus
Description: Moderation/review status: none, reported, underReview
guestPlayerWhite Boolean No - body guestPlayerWhite
Description: True if white is a guest (not a registered user); needed to distinguish guest/registered in history.
guestPlayerBlack Boolean No - body guestPlayerBlack
Description: True if black is a guest (not a registered user); needed to distinguish guest/registered in history.
initialFEN String No - body initialFEN
Description: The starting FEN position when the game was created. Used to identify custom games.

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 createGame 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.chessGameId,
  playerWhiteId: this.playerWhiteId,
  playerBlackId: this.playerBlackId,
  createdById: this.createdById,
  status: this.status,
  mode: this.mode,
  invitationCode: this.invitationCode,
  currentFEN: this.currentFEN,
  gameType: this.gameType,
  saveStatus: this.saveStatus,
  saveRequestWhite: this.saveRequestWhite,
  saveRequestBlack: this.saveRequestBlack,
  movedAt: this.movedAt,
  result: this.result,
  terminatedById: this.terminatedById,
  reportStatus: this.reportStatus,
  guestPlayerWhite: this.guestPlayerWhite,
  guestPlayerBlack: this.guestPlayerBlack,
  initialFEN: this.initialFEN,
  isActive: true,
  _archivedAt: null,
}

Business Logic Workflow

[1] Step : startBusinessApi

Manager initializes context, populates session and request objects, prepares internal structures for parameter handling and workflow execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Manager reads input parameters, normalizes missing values, applies default type casting, and stores them in the API context.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Manager transforms parameters, computes derived values, flattens or remaps arrays/objects, and adjusts formats for downstream processing.


[4] Step : checkParameters

Manager executes built-in validations: required field checks, type enforcement, and basic business rules. Prevents operation if validation fails.


[5] Step : checkBasicAuth

Manager performs authentication and authorization checks: verifies session, user roles, permissions, and tenant restrictions.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildDataClause

Manager constructs the final data object for creation, fills auto-generated fields (IDs, timestamps, owner fields), and ensures schema consistency.

You can use the following settings to change some behavior of this step. dataClause

[7] Step : mainCreateOperation

Manager executes the database insert operation, updates indexes/caches, and triggers internal post-processing like linked default records.


[8] Step : buildOutput

Manager shapes the response: masks sensitive fields, resolves linked references, and formats output according to API contract.


[9] Step : sendResponse

Manager sends the response to the client and finalizes internal tasks like flushing logs or updating session state.


[10] Step : raiseApiEvent

Manager triggers API-level events (Kafka, WebSocket, async workflows) as the final internal step.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The createGame api has got 18 regular client parameters

Parameter Type Required Population
playerWhiteId ID true request.body?.[“playerWhiteId”]
playerBlackId ID false request.body?.[“playerBlackId”]
createdById ID true request.body?.[“createdById”]
status Enum true request.body?.[“status”]
mode Enum true request.body?.[“mode”]
invitationCode String false request.body?.[“invitationCode”]
currentFEN String true request.body?.[“currentFEN”]
gameType Enum true request.body?.[“gameType”]
saveStatus Enum true request.body?.[“saveStatus”]
saveRequestWhite Boolean false request.body?.[“saveRequestWhite”]
saveRequestBlack Boolean false request.body?.[“saveRequestBlack”]
movedAt Date false request.body?.[“movedAt”]
result Enum false request.body?.[“result”]
terminatedById ID false request.body?.[“terminatedById”]
reportStatus Enum false request.body?.[“reportStatus”]
guestPlayerWhite Boolean false request.body?.[“guestPlayerWhite”]
guestPlayerBlack Boolean false request.body?.[“guestPlayerBlack”]
initialFEN String false request.body?.[“initialFEN”]

REST Request

To access the api you can use the REST controller with the path POST /v1/game

  axios({
    method: 'POST',
    url: '/v1/game',
    data: {
            playerWhiteId:"ID",  
            playerBlackId:"ID",  
            createdById:"ID",  
            status:"Enum",  
            mode:"Enum",  
            invitationCode:"String",  
            currentFEN:"String",  
            gameType:"Enum",  
            saveStatus:"Enum",  
            saveRequestWhite:"Boolean",  
            saveRequestBlack:"Boolean",  
            movedAt:"Date",  
            result:"Enum",  
            terminatedById:"ID",  
            reportStatus:"Enum",  
            guestPlayerWhite:"Boolean",  
            guestPlayerBlack:"Boolean",  
            initialFEN:"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 chessGame 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": "chessGame",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"chessGame": {
		"id": "ID",
		"playerWhiteId": "ID",
		"playerBlackId": "ID",
		"createdById": "ID",
		"status": "Enum",
		"status_idx": "Integer",
		"mode": "Enum",
		"mode_idx": "Integer",
		"invitationCode": "String",
		"currentFEN": "String",
		"gameType": "Enum",
		"gameType_idx": "Integer",
		"saveStatus": "Enum",
		"saveStatus_idx": "Integer",
		"saveRequestWhite": "Boolean",
		"saveRequestBlack": "Boolean",
		"movedAt": "Date",
		"result": "Enum",
		"result_idx": "Integer",
		"terminatedById": "ID",
		"reportStatus": "Enum",
		"reportStatus_idx": "Integer",
		"guestPlayerWhite": "Boolean",
		"guestPlayerBlack": "Boolean",
		"initialFEN": "String",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Business API Design Specification - Update Game

Business API Design Specification - Update Game

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 updateGame 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 updateGame Business API is designed to handle a update operation on the ChessGame data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

Updates chess game state including board position, status, save flags etc. Auth: only participants or admin.

API Frontend Description By The Backend Architect

Used for updating board state, status, mutual saving, etc. Most fields are read-only after game completion/termination except by admin. Raise event for gameUpdated for notification/bff.

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 updateGame Business API includes a REST controller that can be triggered via the following route:

/v1/game/:chessGameId

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 updateGame Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The updateGame Business API has 13 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
chessGameId ID Yes - urlpath chessGameId
Description: This id paremeter is used to select the required data object that will be updated
playerBlackId ID No - body playerBlackId
Description: -
status Enum No - body status
Description: Lifecycle status: pending, active, paused, completed, terminated
currentFEN String No - body currentFEN
Description: Current board state in FEN notation for restoration/resume.
saveStatus Enum No - body saveStatus
Description: Game mutual-saving: notSaveable, requested, paused (both agreed)
saveRequestWhite Boolean No - body saveRequestWhite
Description: Whether white has requested save/resume; mutual save when both true.
saveRequestBlack Boolean No - body saveRequestBlack
Description: Whether black has requested save/resume; mutual save when both true.
movedAt Date No - body movedAt
Description: Timestamp of last move (heartbeat/game activity).
result Enum No - body result
Description: Game result/outcome: whiteWin, blackWin, draw, aborted
terminatedById ID No - body terminatedById
Description: ID of administrator who forced terminated the game (if applicable).
reportStatus Enum No - body reportStatus
Description: Moderation/review status: none, reported, underReview
guestPlayerWhite Boolean No - body guestPlayerWhite
Description: True if white is a guest (not a registered user); needed to distinguish guest/registered in history.
guestPlayerBlack Boolean No - body guestPlayerBlack
Description: True if black is a guest (not a registered user); needed to distinguish guest/registered in history.

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 updateGame Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({$and:[{id:this.chessGameId},{isActive:true}]}), {"path":"services[1].businessLogic[1].whereClause.fullWhereClause"})

Data Clause

Defines custom field-value assignments used to modify or augment the default payload for create and update operations. These settings override values derived from the session or parameters if explicitly provided.", Note that a default data clause is always prepared by Mindbricks using data property settings, however any property in the data clause can be override by Data Clause Settings.

An update data clause populates all update-allowed properties of a data object, however the null properties (that are not provided by client) are ignored in db layer.

Custom Data Clause Override No custom data clause override configured

Actual Data Clause

The business api will use the following data clause. Note that any calculated value will be added to the data clause in the api manager.

{
  playerBlackId: this.playerBlackId,
  status: this.status,
  currentFEN: this.currentFEN,
  saveStatus: this.saveStatus,
  saveRequestWhite: this.saveRequestWhite,
  saveRequestBlack: this.saveRequestBlack,
  movedAt: this.movedAt,
  result: this.result,
  terminatedById: this.terminatedById,
  reportStatus: this.reportStatus,
  guestPlayerWhite: this.guestPlayerWhite,
  guestPlayerBlack: this.guestPlayerBlack,
}

Business Logic Workflow

[1] Step : startBusinessApi

Manager initializes context, prepares request and session objects, and sets up internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Manager reads parameters from the request or Redis, applies defaults, and writes them into context for downstream milestones.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Manager executes parameter transform scripts and derives any helper values or reshaped payloads into the context.


[4] Step : checkParameters

Manager validates required parameters, checks ID formats (UUID/ObjectId), and ensures all preconditions for update are met.


[5] Step : checkBasicAuth

Manager performs login verification, role, and permission checks, enforcing tenant and access rules before update.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildWhereClause

Manager constructs the WHERE clause used to identify the record to update, applying ownership and parent checks if necessary.

You can use the following settings to change some behavior of this step. whereClause

[7] Step : fetchInstance

Manager fetches the existing record from the database and writes it to the context for validation or enrichment.


[8] Step : checkInstance

Manager performs instance-level validations, including ownership, existence, lock status, or other pre-update checks.


[9] Action : preventThirdPlayerJoin

Action Type: ValidationAction

Prevents a third user from overwriting the black player slot when the game already has a distinct opponent

class Api {
  async preventThirdPlayerJoin() {
    const isValid = runMScript(
      () =>
        !this.playerBlackId ||
        !this.chessGame.playerBlackId ||
        this.chessGame.playerBlackId === this.chessGame.playerWhiteId ||
        this.playerBlackId === this.chessGame.playerBlackId,
      {
        path: "services[1].businessLogic[1].actions.validationActions[0].validationScript",
      },
    );

    if (!isValid) {
      throw new BadRequestError(
        "This game already has two players and cannot accept another player.",
      );
    }
    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] Action : processGameResult

Action Type: FunctionCallAction

When a game is completed or terminated with a valid result (whiteWin/blackWin/draw), compute ELO changes and update both players’ stats in the leaderboard service.

class Api {
  async processGameResult() {
    try {
      return runMScript(() => LIB.processGameResult(this), {
        path: "services[1].businessLogic[1].actions.functionCallActions[0].callScript",
      });
    } catch (err) {
      console.error("Error in FunctionCallAction processGameResult:", err);
      throw err;
    }
  }
}

[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 updateGame api has got 13 regular client parameters

Parameter Type Required Population
chessGameId ID true request.params?.[“chessGameId”]
playerBlackId ID request.body?.[“playerBlackId”]
status Enum false request.body?.[“status”]
currentFEN String false request.body?.[“currentFEN”]
saveStatus Enum false request.body?.[“saveStatus”]
saveRequestWhite Boolean false request.body?.[“saveRequestWhite”]
saveRequestBlack Boolean false request.body?.[“saveRequestBlack”]
movedAt Date false request.body?.[“movedAt”]
result Enum false request.body?.[“result”]
terminatedById ID false request.body?.[“terminatedById”]
reportStatus Enum false request.body?.[“reportStatus”]
guestPlayerWhite Boolean false request.body?.[“guestPlayerWhite”]
guestPlayerBlack Boolean false request.body?.[“guestPlayerBlack”]

REST Request

To access the api you can use the REST controller with the path PATCH /v1/game/:chessGameId

  axios({
    method: 'PATCH',
    url: `/v1/game/${chessGameId}`,
    data: {
            playerBlackId:"ID",  
            status:"Enum",  
            currentFEN:"String",  
            saveStatus:"Enum",  
            saveRequestWhite:"Boolean",  
            saveRequestBlack:"Boolean",  
            movedAt:"Date",  
            result:"Enum",  
            terminatedById:"ID",  
            reportStatus:"Enum",  
            guestPlayerWhite:"Boolean",  
            guestPlayerBlack:"Boolean",  
    
    },
    params: {
    
        }
  });

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the chessGame 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": "chessGame",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"chessGame": {
		"id": "ID",
		"playerWhiteId": "ID",
		"playerBlackId": "ID",
		"createdById": "ID",
		"status": "Enum",
		"status_idx": "Integer",
		"mode": "Enum",
		"mode_idx": "Integer",
		"invitationCode": "String",
		"currentFEN": "String",
		"gameType": "Enum",
		"gameType_idx": "Integer",
		"saveStatus": "Enum",
		"saveStatus_idx": "Integer",
		"saveRequestWhite": "Boolean",
		"saveRequestBlack": "Boolean",
		"movedAt": "Date",
		"result": "Enum",
		"result_idx": "Integer",
		"terminatedById": "ID",
		"reportStatus": "Enum",
		"reportStatus_idx": "Integer",
		"guestPlayerWhite": "Boolean",
		"guestPlayerBlack": "Boolean",
		"initialFEN": "String",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Business API Design Specification - Delete Game

Business API Design Specification - Delete Game

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 deleteGame 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 deleteGame Business API is designed to handle a delete operation on the ChessGame 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 chess game (soft-delete). Only allowed for admins or system cleanup.

API Frontend Description By The Backend Architect

Hard deletion not recommended; soft-deletion disables user/game access. Used for moderation/cleanup only. Regular users cannot delete games. Raise event for gameDeleted for moderation/audit.

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 deleteGame Business API includes a REST controller that can be triggered via the following route:

/v1/game/:chessGameId

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 deleteGame Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The deleteGame 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
chessGameId ID Yes - urlpath chessGameId
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 deleteGame Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({$and:[{id:this.chessGameId},{isActive:true}]}), {"path":"services[1].businessLogic[2].whereClause.fullWhereClause"})

Delete Options

Use these options to set delete specific settings.

useSoftDelete: true If true, the record will be marked as deleted (isActive: false) instead of removed. The implementation depends on the data object’s soft delete configuration.

Business Logic Workflow

[1] Step : startBusinessApi

Manager initializes context, prepares request/session objects, and sets up internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] 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 deleteGame api has got 1 regular client parameter

Parameter Type Required Population
chessGameId ID true request.params?.[“chessGameId”]

REST Request

To access the api you can use the REST controller with the path DELETE /v1/game/:chessGameId

  axios({
    method: 'DELETE',
    url: `/v1/game/${chessGameId}`,
    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 chessGame 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": "chessGame",
	"method": "DELETE",
	"action": "delete",
	"appVersion": "Version",
	"rowCount": 1,
	"chessGame": {
		"id": "ID",
		"playerWhiteId": "ID",
		"playerBlackId": "ID",
		"createdById": "ID",
		"status": "Enum",
		"status_idx": "Integer",
		"mode": "Enum",
		"mode_idx": "Integer",
		"invitationCode": "String",
		"currentFEN": "String",
		"gameType": "Enum",
		"gameType_idx": "Integer",
		"saveStatus": "Enum",
		"saveStatus_idx": "Integer",
		"saveRequestWhite": "Boolean",
		"saveRequestBlack": "Boolean",
		"movedAt": "Date",
		"result": "Enum",
		"result_idx": "Integer",
		"terminatedById": "ID",
		"reportStatus": "Enum",
		"reportStatus_idx": "Integer",
		"guestPlayerWhite": "Boolean",
		"guestPlayerBlack": "Boolean",
		"initialFEN": "String",
		"isActive": false,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Business API Design Specification - Get Game

Business API Design Specification - Get Game

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 getGame 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 getGame Business API is designed to handle a get operation on the ChessGame 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 chess game by ID. Only participants, admin, or invitation recipient may access.

API Frontend Description By The Backend Architect

Retrieve all game details and limited move history for preview/study. If user is not participant, must check invitation. Raise event for gameFetched.

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 getGame Business API includes a REST controller that can be triggered via the following route:

/v1/game/:chessGameId

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 getGame Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The getGame 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
chessGameId ID Yes - urlpath chessGameId
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 getGame Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Select Clause

Specifies which fields will be selected from the main data object during a get or list operation. Leave blank to select all properties. This applies only to get and list type APIs.",

``

Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({$and:[{id:this.chessGameId},{isActive:true}]}), {"path":"services[1].businessLogic[3].whereClause.fullWhereClause"})

Get Options

Use these options to set get specific settings.

setAsRead: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed.

No setAsread field-value pair is configured.

Business Logic Workflow

[1] Step : startBusinessApi

Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Extracts parameters from request and Redis, applies defaults, and writes them to context.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Executes parameter transformation scripts, applies type coercion, merges derived values, and reshapes inputs for downstream milestones.


[4] Step : checkParameters

Validates required and custom parameters, enforcing business-specific rules and constraints.


[5] Step : checkBasicAuth

Performs login, role, and permission checks, and applies dynamic object-level access rules.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildWhereClause

Builds the WHERE clause for fetching the object and applies additional scoped filters if configured.

You can use the following settings to change some behavior of this step. whereClause

[7] Step : mainGetOperation

Executes the database fetch, retrieves the object, and stores it in context for enrichment or further checks.

You can use the following settings to change some behavior of this step. selectClause, getOptions

[8] Step : checkInstance

Performs instance-level validations, such as ownership, existence, or access conditions.


[9] Step : buildOutput

Assembles the response from the object, applies masking, formatting, and injects additional metadata if needed.


[10] Step : sendResponse

Delivers the response to the controller for client delivery.


[11] Step : raiseApiEvent

Triggers optional API-level events after workflow completion, sending messages to integrations like Kafka if configured.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The getGame api has got 1 regular client parameter

Parameter Type Required Population
chessGameId ID true request.params?.[“chessGameId”]

REST Request

To access the api you can use the REST controller with the path GET /v1/game/:chessGameId

  axios({
    method: 'GET',
    url: `/v1/game/${chessGameId}`,
    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 chessGame 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": "chessGame",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"chessGame": {
		"id": "ID",
		"playerWhiteId": "ID",
		"playerBlackId": "ID",
		"createdById": "ID",
		"status": "Enum",
		"status_idx": "Integer",
		"mode": "Enum",
		"mode_idx": "Integer",
		"invitationCode": "String",
		"currentFEN": "String",
		"gameType": "Enum",
		"gameType_idx": "Integer",
		"saveStatus": "Enum",
		"saveStatus_idx": "Integer",
		"saveRequestWhite": "Boolean",
		"saveRequestBlack": "Boolean",
		"movedAt": "Date",
		"result": "Enum",
		"result_idx": "Integer",
		"terminatedById": "ID",
		"reportStatus": "Enum",
		"reportStatus_idx": "Integer",
		"guestPlayerWhite": "Boolean",
		"guestPlayerBlack": "Boolean",
		"initialFEN": "String",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"moves": [
			{
				"moveNumber": "Integer",
				"moveNotation": "String",
				"moveTime": "Integer",
				"movedById": "ID",
				"moveTimestamp": "Date"
			},
			{},
			{}
		]
	}
}

Business API Design Specification - List Games

Business API Design Specification - List Games

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 listGames 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 listGames Business API is designed to handle a list operation on the ChessGame data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

List chess games by participant or admin query. Supports filtering by status, participants, mode, etc.

API Frontend Description By The Backend Architect

Used for history browsing, admin review, or finding ongoing/mutually saved games. Raise event for gameListFetched for audit/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 listGames Business API includes a REST controller that can be triggered via the following route:

/v1/games

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 listGames Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The listGames Business API has 2 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client.

Business API parameters can be:

Filter Parameters

The listGames api supports 2 optional filter parameters for filtering list results using URL query parameters. These parameters are only available for list type APIs.

status Filter

Type: Enum
Description: Lifecycle status: pending, active, paused, completed, terminated
Location: Query Parameter

Usage:

Examples:

// Get records with specific enum value
GET /v1/games?status=active

// Get records with multiple enum values (use multiple parameters)
GET /v1/games?status=active&status=pending

// Get records without this field
GET /v1/games?status=null

invitationCode Filter

Type: String
Description: Filter by invitationCode
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/games?invitationCode=john
// Matches: "John", "Johnny", "johnson", "McJohn", etc.

// Find records with multiple values (use multiple parameters)
GET /v1/games?invitationCode=laptop&invitationCode=phone&invitationCode=tablet
// Matches records containing "laptop", "phone", or "tablet" anywhere in the field

// Find records without this field
GET /v1/games?invitationCode=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 listGames Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Select Clause

Specifies which fields will be selected from the main data object during a get or list operation. Leave blank to select all properties. This applies only to get and list type APIs.",

``

Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({isActive:true}), {"path":"services[1].businessLogic[4].whereClause.fullWhereClause"})

List Options

Defines list-specific options including filtering logic, default sorting, and result customization for APIs that return multiple records.

List Sort By Sort order definitions for the result set. Multiple fields can be provided with direction (asc/desc).

[ movedAt desc ]

List Group By Grouping definitions for the result set. This is typically used for visual or report-based grouping.

The list is not grouped.

setAsRead: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed.

No setAsread field-value pair is configured.

Permission Filter Optional filter that applies permission constraints dynamically based on session or object roles. So that the list items are filtered by the user’s OBAC or ABAC permissions.

Permission filter is not active at the moment. Follow Mindbricks updates to be able to use it.

Pagination Options

Contains settings to configure pagination behavior for list APIs. Includes options like page size, offset, cursor support, and total count inclusion.

Business Logic Workflow

[1] Step : startBusinessApi

Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Reads request and Redis parameters, applies defaults, and writes them to context for downstream processing.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Transforms and normalizes parameters, derives dependent values, and reshapes inputs for the main list query.


[4] Step : checkParameters

Executes validation logic on required and custom parameters, enforcing business rules and cross-field consistency.


[5] Step : checkBasicAuth

Performs role-based access checks and applies dynamic membership or session-based restrictions.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildWhereClause

Constructs the main query WHERE clause and applies optional filters or scoped access controls.

You can use the following settings to change some behavior of this step. whereClause

[7] Step : mainListOperation

Executes the paginated database query, retrieves the list, and stores results in context for enrichment.

You can use the following settings to change some behavior of this step. selectClause, listOptions, paginationOptions

[8] Step : buildOutput

Assembles the list response, sanitizes sensitive fields, applies transformations, and injects extra context if needed.


[9] Step : sendResponse

Sends the paginated list to the client through the controller.


[10] Step : raiseApiEvent

Triggers optional post-workflow events, such as Kafka messages, logs, or system notifications.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The listGames 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
status Enum No Lifecycle status: pending, active, paused, completed, terminated
invitationCode String No Filter by invitationCode

REST Request

To access the api you can use the REST controller with the path GET /v1/games

  axios({
    method: 'GET',
    url: '/v1/games',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section for usage examples)
        // status: '<value>' // Filter by status
        // invitationCode: '<value>' // Filter by invitationCode
            }
  });

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 chessGames 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": "chessGames",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"chessGames": [
		{
			"id": "ID",
			"playerWhiteId": "ID",
			"playerBlackId": "ID",
			"createdById": "ID",
			"status": "Enum",
			"status_idx": "Integer",
			"mode": "Enum",
			"mode_idx": "Integer",
			"invitationCode": "String",
			"currentFEN": "String",
			"gameType": "Enum",
			"gameType_idx": "Integer",
			"saveStatus": "Enum",
			"saveStatus_idx": "Integer",
			"saveRequestWhite": "Boolean",
			"saveRequestBlack": "Boolean",
			"movedAt": "Date",
			"result": "Enum",
			"result_idx": "Integer",
			"terminatedById": "ID",
			"reportStatus": "Enum",
			"reportStatus_idx": "Integer",
			"guestPlayerWhite": "Boolean",
			"guestPlayerBlack": "Boolean",
			"initialFEN": "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 Gamemove

Business API Design Specification - Create Gamemove

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 createGameMove 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 createGameMove Business API is designed to handle a create operation on the ChessGameMove data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

Record a move in an ongoing chess game. Only participants or admin can add moves.

API Frontend Description By The Backend Architect

Called in-order for each legitimate move. Ensures move sequence is preserved. Move time and timestamp acquired on submit. Raises event for moveAdded.

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 createGameMove Business API includes a REST controller that can be triggered via the following route:

/v1/gamemove

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 createGameMove Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The createGameMove 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
chessGameMoveId ID No - body chessGameMoveId
Description: This id paremeter is used to create the data object with a given specific id. Leave null for automatic id.
gameId ID Yes - body gameId
Description: Reference to the chessGame this move belongs to.
moveNumber Integer Yes - body moveNumber
Description: Move number (starting from 1 in each game).
moveNotation String Yes - body moveNotation
Description: Chess move in either Standard Algebraic or Long Algebraic Notation (SAN/LAN).
moveTime Integer No - body moveTime
Description: Time in milliseconds since the previous move (for time control, etc.).
movedById ID Yes - body movedById
Description: User ID of the player who made the move (guest/registered); references auth:user.id.
moveTimestamp Date Yes - body moveTimestamp
Description: Timestamp when move was made.

Parameter Transformations

Some parameters are post-processed using transform scripts after being read from the request but before validation or workflow execution. Only parameters with a transform script are listed below.

No parameters are transformed in this API.

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the createGameMove 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.chessGameMoveId,
  gameId: this.gameId,
  moveNumber: this.moveNumber,
  moveNotation: this.moveNotation,
  moveTime: this.moveTime,
  movedById: this.movedById,
  moveTimestamp: this.moveTimestamp,
  isActive: true,
  _archivedAt: null,
}

Business Logic Workflow

[1] Step : startBusinessApi

Manager initializes context, populates session and request objects, prepares internal structures for parameter handling and workflow execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Manager reads input parameters, normalizes missing values, applies default type casting, and stores them in the API context.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Manager transforms parameters, computes derived values, flattens or remaps arrays/objects, and adjusts formats for downstream processing.


[4] Step : checkParameters

Manager executes built-in validations: required field checks, type enforcement, and basic business rules. Prevents operation if validation fails.


[5] Step : checkBasicAuth

Manager performs authentication and authorization checks: verifies session, user roles, permissions, and tenant restrictions.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildDataClause

Manager constructs the final data object for creation, fills auto-generated fields (IDs, timestamps, owner fields), and ensures schema consistency.

You can use the following settings to change some behavior of this step. dataClause

[7] Step : mainCreateOperation

Manager executes the database insert operation, updates indexes/caches, and triggers internal post-processing like linked default records.


[8] Step : buildOutput

Manager shapes the response: masks sensitive fields, resolves linked references, and formats output according to API contract.


[9] Step : sendResponse

Manager sends the response to the client and finalizes internal tasks like flushing logs or updating session state.


[10] Step : raiseApiEvent

Manager triggers API-level events (Kafka, WebSocket, async workflows) as the final internal step.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The createGameMove api has got 6 regular client parameters

Parameter Type Required Population
gameId ID true request.body?.[“gameId”]
moveNumber Integer true request.body?.[“moveNumber”]
moveNotation String true request.body?.[“moveNotation”]
moveTime Integer false request.body?.[“moveTime”]
movedById ID true request.body?.[“movedById”]
moveTimestamp Date true request.body?.[“moveTimestamp”]

REST Request

To access the api you can use the REST controller with the path POST /v1/gamemove

  axios({
    method: 'POST',
    url: '/v1/gamemove',
    data: {
            gameId:"ID",  
            moveNumber:"Integer",  
            moveNotation:"String",  
            moveTime:"Integer",  
            movedById:"ID",  
            moveTimestamp:"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 chessGameMove 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": "chessGameMove",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"chessGameMove": {
		"id": "ID",
		"gameId": "ID",
		"moveNumber": "Integer",
		"moveNotation": "String",
		"moveTime": "Integer",
		"movedById": "ID",
		"moveTimestamp": "Date",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Business API Design Specification - List Gamemoves

Business API Design Specification - List Gamemoves

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 listGameMoves 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 listGameMoves Business API is designed to handle a list operation on the ChessGameMove data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

List moves for a given game. Only participants or admin can view.

API Frontend Description By The Backend Architect

Used for reviewing game history/study. Returns moves ordered by moveNumber asc.

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 listGameMoves Business API includes a REST controller that can be triggered via the following route:

/v1/gamemoves

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 listGameMoves Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The listGameMoves 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 listGameMoves api supports 1 optional filter parameter for filtering list results using URL query parameters. These parameters are only available for list type APIs.

gameId Filter

Type: ID
Description: Reference to the chessGame this move belongs to.
Location: Query Parameter

Usage:

Non-Array Property:

Examples:

// Get records with a specific ID
GET /v1/gamemoves?gameId=550e8400-e29b-41d4-a716-446655440000

// Get records with multiple IDs (use multiple parameters)
GET /v1/gamemoves?gameId=550e8400-e29b-41d4-a716-446655440000&gameId=660e8400-e29b-41d4-a716-446655440001

// Get records without this field
GET /v1/gamemoves?gameId=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 listGameMoves Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Select Clause

Specifies which fields will be selected from the main data object during a get or list operation. Leave blank to select all properties. This applies only to get and list type APIs.",

``

Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({isActive:true}), {"path":"services[1].businessLogic[6].whereClause.fullWhereClause"})

List Options

Defines list-specific options including filtering logic, default sorting, and result customization for APIs that return multiple records.

List Sort By Sort order definitions for the result set. Multiple fields can be provided with direction (asc/desc).

[ moveNumber asc ]

List Group By Grouping definitions for the result set. This is typically used for visual or report-based grouping.

The list is not grouped.

setAsRead: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed.

No setAsread field-value pair is configured.

Permission Filter Optional filter that applies permission constraints dynamically based on session or object roles. So that the list items are filtered by the user’s OBAC or ABAC permissions.

Permission filter is not active at the moment. Follow Mindbricks updates to be able to use it.

Pagination Options

Contains settings to configure pagination behavior for list APIs. Includes options like page size, offset, cursor support, and total count inclusion.

Business Logic Workflow

[1] Step : startBusinessApi

Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Reads request and Redis parameters, applies defaults, and writes them to context for downstream processing.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Transforms and normalizes parameters, derives dependent values, and reshapes inputs for the main list query.


[4] Step : checkParameters

Executes validation logic on required and custom parameters, enforcing business rules and cross-field consistency.


[5] Step : checkBasicAuth

Performs role-based access checks and applies dynamic membership or session-based restrictions.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildWhereClause

Constructs the main query WHERE clause and applies optional filters or scoped access controls.

You can use the following settings to change some behavior of this step. whereClause

[7] Step : mainListOperation

Executes the paginated database query, retrieves the list, and stores results in context for enrichment.

You can use the following settings to change some behavior of this step. selectClause, listOptions, paginationOptions

[8] Step : buildOutput

Assembles the list response, sanitizes sensitive fields, applies transformations, and injects extra context if needed.


[9] Step : sendResponse

Sends the paginated list to the client through the controller.


[10] Step : raiseApiEvent

Triggers optional post-workflow events, such as Kafka messages, logs, or system notifications.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The listGameMoves 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
gameId ID No Reference to the chessGame this move belongs to.

REST Request

To access the api you can use the REST controller with the path GET /v1/gamemoves

  axios({
    method: 'GET',
    url: '/v1/gamemoves',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section for usage examples)
        // gameId: '<value>' // Filter by gameId
            }
  });

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 chessGameMoves 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": "chessGameMoves",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"chessGameMoves": [
		{
			"id": "ID",
			"gameId": "ID",
			"moveNumber": "Integer",
			"moveNotation": "String",
			"moveTime": "Integer",
			"movedById": "ID",
			"moveTimestamp": "Date",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID"
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Business API Design Specification - Create Gameinvitation

Business API Design Specification - Create Gameinvitation

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 createGameInvitation 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 createGameInvitation Business API is designed to handle a create operation on the ChessGameInvitation data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

Send an invitation for a private chess game to a user (guest or registered).

API Frontend Description By The Backend Architect

Used for starting private games. Invitation auto-invalidates on expiry. Raise event for invitationSent for notification.

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 createGameInvitation Business API includes a REST controller that can be triggered via the following route:

/v1/gameinvitation

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 createGameInvitation Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The createGameInvitation 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
chessGameInvitationId ID No - body chessGameInvitationId
Description: This id paremeter is used to create the data object with a given specific id. Leave null for automatic id.
gameId ID Yes - body gameId
Description: Game this invitation is linked to.
senderId ID Yes - body senderId
Description: -
recipientId ID Yes - body recipientId
Description: -
status Enum Yes - body status
Description: -
expiresAt Date Yes - body expiresAt
Description: Expiration date/time for the invitation.

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 createGameInvitation 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.chessGameInvitationId,
  gameId: this.gameId,
  senderId: this.senderId,
  recipientId: this.recipientId,
  status: this.status,
  expiresAt: this.expiresAt,
  isActive: true,
  _archivedAt: null,
}

Business Logic Workflow

[1] Step : startBusinessApi

Manager initializes context, populates session and request objects, prepares internal structures for parameter handling and workflow execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Manager reads input parameters, normalizes missing values, applies default type casting, and stores them in the API context.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Manager transforms parameters, computes derived values, flattens or remaps arrays/objects, and adjusts formats for downstream processing.


[4] Step : checkParameters

Manager executes built-in validations: required field checks, type enforcement, and basic business rules. Prevents operation if validation fails.


[5] Step : checkBasicAuth

Manager performs authentication and authorization checks: verifies session, user roles, permissions, and tenant restrictions.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildDataClause

Manager constructs the final data object for creation, fills auto-generated fields (IDs, timestamps, owner fields), and ensures schema consistency.

You can use the following settings to change some behavior of this step. dataClause

[7] Step : mainCreateOperation

Manager executes the database insert operation, updates indexes/caches, and triggers internal post-processing like linked default records.


[8] Step : buildOutput

Manager shapes the response: masks sensitive fields, resolves linked references, and formats output according to API contract.


[9] Step : sendResponse

Manager sends the response to the client and finalizes internal tasks like flushing logs or updating session state.


[10] Step : raiseApiEvent

Manager triggers API-level events (Kafka, WebSocket, async workflows) as the final internal step.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The createGameInvitation api has got 5 regular client parameters

Parameter Type Required Population
gameId ID true request.body?.[“gameId”]
senderId ID true request.body?.[“senderId”]
recipientId ID true request.body?.[“recipientId”]
status Enum true request.body?.[“status”]
expiresAt Date true request.body?.[“expiresAt”]

REST Request

To access the api you can use the REST controller with the path POST /v1/gameinvitation

  axios({
    method: 'POST',
    url: '/v1/gameinvitation',
    data: {
            gameId:"ID",  
            senderId:"ID",  
            recipientId:"ID",  
            status:"Enum",  
            expiresAt:"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 chessGameInvitation 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": "chessGameInvitation",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"chessGameInvitation": {
		"id": "ID",
		"gameId": "ID",
		"senderId": "ID",
		"recipientId": "ID",
		"status": "Enum",
		"status_idx": "Integer",
		"expiresAt": "Date",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Business API Design Specification - Update Gameinvitation

Business API Design Specification - Update Gameinvitation

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 updateGameInvitation 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 updateGameInvitation Business API is designed to handle a update operation on the ChessGameInvitation data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

Update the status or expiry of a game invitation (accept, decline, cancel, expire). Only sender, recipient, or admin can change status.

API Frontend Description By The Backend Architect

Used for invitation workflow (accept, decline, cancel); handled securely as only involved users or admin can update. Event is raised for notification.

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 updateGameInvitation Business API includes a REST controller that can be triggered via the following route:

/v1/gameinvitation/:chessGameInvitationId

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 updateGameInvitation Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The updateGameInvitation 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
chessGameInvitationId ID Yes - urlpath chessGameInvitationId
Description: This id paremeter is used to select the required data object that will be updated
senderId ID No - body senderId
Description: -
recipientId ID No - body recipientId
Description: -
status Enum No - body status
Description: -
expiresAt Date No - body expiresAt
Description: Expiration date/time for the invitation.

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 updateGameInvitation Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({$and:[{id:this.chessGameInvitationId},{isActive:true}]}), {"path":"services[1].businessLogic[8].whereClause.fullWhereClause"})

Data Clause

Defines custom field-value assignments used to modify or augment the default payload for create and update operations. These settings override values derived from the session or parameters if explicitly provided.", Note that a default data clause is always prepared by Mindbricks using data property settings, however any property in the data clause can be override by Data Clause Settings.

An update data clause populates all update-allowed properties of a data object, however the null properties (that are not provided by client) are ignored in db layer.

Custom Data Clause Override 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.

{
  senderId: this.senderId,
  recipientId: this.recipientId,
  status: this.status,
  expiresAt: this.expiresAt,
}

Business Logic Workflow

[1] Step : startBusinessApi

Manager initializes context, prepares request and session objects, and sets up internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Manager reads parameters from the request or Redis, applies defaults, and writes them into context for downstream milestones.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Manager executes parameter transform scripts and derives any helper values or reshaped payloads into the context.


[4] Step : checkParameters

Manager validates required parameters, checks ID formats (UUID/ObjectId), and ensures all preconditions for update are met.


[5] Step : checkBasicAuth

Manager performs login verification, role, and permission checks, enforcing tenant and access rules before update.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildWhereClause

Manager constructs the WHERE clause used to identify the record to update, applying ownership and parent checks if necessary.

You can use the following settings to change some behavior of this step. whereClause

[7] Step : fetchInstance

Manager fetches the existing record from the database and writes it to the context for validation or enrichment.


[8] Step : checkInstance

Manager performs instance-level validations, including ownership, existence, lock status, or other pre-update checks.


[9] Step : buildDataClause

Manager prepares the data clause for the update, applying transformations or enhancements before persisting.

You can use the following settings to change some behavior of this step. dataClause

[10] Step : mainUpdateOperation

Manager executes the update operation with the WHERE and data clauses. Database-level events are raised if configured.


[11] Step : buildOutput

Manager assembles the response object from the update result, masking fields or injecting additional metadata.


[12] Step : sendResponse

Manager sends the response back to the controller for delivery to the client.


[13] Step : raiseApiEvent

Manager triggers API-level events, sending relevant messages to Kafka or other integrations if configured.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The updateGameInvitation api has got 5 regular client parameters

Parameter Type Required Population
chessGameInvitationId ID true request.params?.[“chessGameInvitationId”]
senderId ID request.body?.[“senderId”]
recipientId ID request.body?.[“recipientId”]
status Enum request.body?.[“status”]
expiresAt Date false request.body?.[“expiresAt”]

REST Request

To access the api you can use the REST controller with the path PATCH /v1/gameinvitation/:chessGameInvitationId

  axios({
    method: 'PATCH',
    url: `/v1/gameinvitation/${chessGameInvitationId}`,
    data: {
            senderId:"ID",  
            recipientId:"ID",  
            status:"Enum",  
            expiresAt:"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 chessGameInvitation 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": "chessGameInvitation",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"chessGameInvitation": {
		"id": "ID",
		"gameId": "ID",
		"senderId": "ID",
		"recipientId": "ID",
		"status": "Enum",
		"status_idx": "Integer",
		"expiresAt": "Date",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Business API Design Specification - Delete Gameinvitation

Business API Design Specification - Delete Gameinvitation

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 deleteGameInvitation 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 deleteGameInvitation Business API is designed to handle a delete operation on the ChessGameInvitation 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 game invitation (soft-deletes); only admin may do this for moderation/cleanup.

API Frontend Description By The Backend Architect

Not available to normal users. Moderation purposes only. Raise event for invitationRemoved for mods.

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 deleteGameInvitation Business API includes a REST controller that can be triggered via the following route:

/v1/gameinvitation/:chessGameInvitationId

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 deleteGameInvitation Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The deleteGameInvitation 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
chessGameInvitationId ID Yes - urlpath chessGameInvitationId
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 deleteGameInvitation Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({$and:[{id:this.chessGameInvitationId},{isActive:true}]}), {"path":"services[1].businessLogic[9].whereClause.fullWhereClause"})

Delete Options

Use these options to set delete specific settings.

useSoftDelete: true If true, the record will be marked as deleted (isActive: false) instead of removed. The implementation depends on the data object’s soft delete configuration.

Business Logic Workflow

[1] Step : startBusinessApi

Manager initializes context, prepares request/session objects, and sets up internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] 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 deleteGameInvitation api has got 1 regular client parameter

Parameter Type Required Population
chessGameInvitationId ID true request.params?.[“chessGameInvitationId”]

REST Request

To access the api you can use the REST controller with the path DELETE /v1/gameinvitation/:chessGameInvitationId

  axios({
    method: 'DELETE',
    url: `/v1/gameinvitation/${chessGameInvitationId}`,
    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 chessGameInvitation 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": "chessGameInvitation",
	"method": "DELETE",
	"action": "delete",
	"appVersion": "Version",
	"rowCount": 1,
	"chessGameInvitation": {
		"id": "ID",
		"gameId": "ID",
		"senderId": "ID",
		"recipientId": "ID",
		"status": "Enum",
		"status_idx": "Integer",
		"expiresAt": "Date",
		"isActive": false,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Business API Design Specification - List Gameinvitations

Business API Design Specification - List Gameinvitations

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 listGameInvitations 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 listGameInvitations Business API is designed to handle a list operation on the ChessGameInvitation data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

List game invitations. Supports filtering by recipientId, senderId, status, gameId.

API Frontend Description By The Backend Architect

Used to show pending invitations to a user, or to list all invitations for a game.

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 listGameInvitations Business API includes a REST controller that can be triggered via the following route:

/v1/gameinvitations

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 listGameInvitations Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The listGameInvitations 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 listGameInvitations api supports 3 optional filter parameters for filtering list results using URL query parameters. These parameters are only available for list type APIs.

senderId Filter

Type: ID
Description: Filter by senderId
Location: Query Parameter

Usage:

Non-Array Property:

Examples:

// Get records with a specific ID
GET /v1/gameinvitations?senderId=550e8400-e29b-41d4-a716-446655440000

// Get records with multiple IDs (use multiple parameters)
GET /v1/gameinvitations?senderId=550e8400-e29b-41d4-a716-446655440000&senderId=660e8400-e29b-41d4-a716-446655440001

// Get records without this field
GET /v1/gameinvitations?senderId=null

recipientId Filter

Type: ID
Description: Filter by recipientId
Location: Query Parameter

Usage:

Non-Array Property:

Examples:

// Get records with a specific ID
GET /v1/gameinvitations?recipientId=550e8400-e29b-41d4-a716-446655440000

// Get records with multiple IDs (use multiple parameters)
GET /v1/gameinvitations?recipientId=550e8400-e29b-41d4-a716-446655440000&recipientId=660e8400-e29b-41d4-a716-446655440001

// Get records without this field
GET /v1/gameinvitations?recipientId=null

status Filter

Type: Enum
Description: Filter by status
Location: Query Parameter

Usage:

Examples:

// Get records with specific enum value
GET /v1/gameinvitations?status=active

// Get records with multiple enum values (use multiple parameters)
GET /v1/gameinvitations?status=active&status=pending

// Get records without this field
GET /v1/gameinvitations?status=null

Parameter Transformations

Some parameters are post-processed using transform scripts after being read from the request but before validation or workflow execution. Only parameters with a transform script are listed below.

No parameters are transformed in this API.

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the listGameInvitations Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Select Clause

Specifies which fields will be selected from the main data object during a get or list operation. Leave blank to select all properties. This applies only to get and list type APIs.",

``

Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({isActive:true}), {"path":"services[1].businessLogic[10].whereClause.fullWhereClause"})

List Options

Defines list-specific options including filtering logic, default sorting, and result customization for APIs that return multiple records.

List Sort By Sort order definitions for the result set. Multiple fields can be provided with direction (asc/desc).

[ 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, sseSettings, cronSettings

[2] Step : readParameters

Reads request and Redis parameters, applies defaults, and writes them to context for downstream processing.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Transforms and normalizes parameters, derives dependent values, and reshapes inputs for the main list query.


[4] Step : checkParameters

Executes validation logic on required and custom parameters, enforcing business rules and cross-field consistency.


[5] Step : checkBasicAuth

Performs role-based access checks and applies dynamic membership or session-based restrictions.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildWhereClause

Constructs the main query WHERE clause and applies optional filters or scoped access controls.

You can use the following settings to change some behavior of this step. whereClause

[7] Step : mainListOperation

Executes the paginated database query, retrieves the list, and stores results in context for enrichment.

You can use the following settings to change some behavior of this step. selectClause, listOptions, paginationOptions

[8] Step : buildOutput

Assembles the list response, sanitizes sensitive fields, applies transformations, and injects extra context if needed.


[9] Step : sendResponse

Sends the paginated list to the client through the controller.


[10] Step : raiseApiEvent

Triggers optional post-workflow events, such as Kafka messages, logs, or system notifications.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The listGameInvitations 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
senderId ID No Filter by senderId
recipientId ID No Filter by recipientId
status Enum No Filter by status

REST Request

To access the api you can use the REST controller with the path GET /v1/gameinvitations

  axios({
    method: 'GET',
    url: '/v1/gameinvitations',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section for usage examples)
        // senderId: '<value>' // Filter by senderId
        // recipientId: '<value>' // Filter by recipientId
        // status: '<value>' // Filter by status
            }
  });

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the chessGameInvitations 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": "chessGameInvitations",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"chessGameInvitations": [
		{
			"id": "ID",
			"gameId": "ID",
			"senderId": "ID",
			"recipientId": "ID",
			"status": "Enum",
			"status_idx": "Integer",
			"expiresAt": "Date",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID"
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Business API Design Specification - Create Customboard

Business API Design Specification - Create Customboard

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 createCustomBoard 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 createCustomBoard Business API is designed to handle a create operation on the CustomBoard 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 custom chess board position. Any logged-in user can create boards.

API Frontend Description By The Backend Architect

Called when a user saves a custom board position from the board editor. createdById is auto-set from session.

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The createCustomBoard Business API includes a REST controller that can be triggered via the following route:

/v1/customboards

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 createCustomBoard Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The createCustomBoard 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
customBoardId ID No - body customBoardId
Description: This id paremeter is used to create the data object with a given specific id. Leave null for automatic id.
name String Yes - body name
Description: Name of the custom board position
fen String Yes - body fen
Description: FEN string representing the board position
description Text No - body description
Description: Optional description of the custom board
isPublished Boolean Yes - body isPublished
Description: -
category Enum Yes - body category
Description: -
createdById ID Yes - body createdById
Description: -

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 createCustomBoard 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.customBoardId,
  name: this.name,
  fen: this.fen,
  description: this.description,
  isPublished: this.isPublished,
  category: this.category,
  createdById: this.createdById,
  isActive: true,
  _archivedAt: null,
}

Business Logic Workflow

[1] Step : startBusinessApi

Manager initializes context, populates session and request objects, prepares internal structures for parameter handling and workflow execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Manager reads input parameters, normalizes missing values, applies default type casting, and stores them in the API context.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Manager transforms parameters, computes derived values, flattens or remaps arrays/objects, and adjusts formats for downstream processing.


[4] Step : checkParameters

Manager executes built-in validations: required field checks, type enforcement, and basic business rules. Prevents operation if validation fails.


[5] Step : checkBasicAuth

Manager performs authentication and authorization checks: verifies session, user roles, permissions, and tenant restrictions.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildDataClause

Manager constructs the final data object for creation, fills auto-generated fields (IDs, timestamps, owner fields), and ensures schema consistency.

You can use the following settings to change some behavior of this step. dataClause

[7] Step : mainCreateOperation

Manager executes the database insert operation, updates indexes/caches, and triggers internal post-processing like linked default records.


[8] Step : buildOutput

Manager shapes the response: masks sensitive fields, resolves linked references, and formats output according to API contract.


[9] Step : sendResponse

Manager sends the response to the client and finalizes internal tasks like flushing logs or updating session state.


[10] Step : raiseApiEvent

Manager triggers API-level events (Kafka, WebSocket, async workflows) as the final internal step.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The createCustomBoard api has got 6 regular client parameters

Parameter Type Required Population
name String true request.body?.[“name”]
fen String true request.body?.[“fen”]
description Text false request.body?.[“description”]
isPublished Boolean true request.body?.[“isPublished”]
category Enum true request.body?.[“category”]
createdById ID true request.body?.[“createdById”]

REST Request

To access the api you can use the REST controller with the path POST /v1/customboards

  axios({
    method: 'POST',
    url: '/v1/customboards',
    data: {
            name:"String",  
            fen:"String",  
            description:"Text",  
            isPublished:"Boolean",  
            category:"Enum",  
            createdById:"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 customBoard 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": "customBoard",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"customBoard": {
		"id": "ID",
		"name": "String",
		"fen": "String",
		"description": "Text",
		"isPublished": "Boolean",
		"category": "Enum",
		"category_idx": "Integer",
		"createdById": "ID",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Business API Design Specification - List Customboards

Business API Design Specification - List Customboards

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 listCustomBoards 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 listCustomBoards Business API is designed to handle a list operation on the CustomBoard data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

List custom board positions. Supports filtering by isPublished, category, and createdById.

API Frontend Description By The Backend Architect

Used to browse published community boards or user’s own boards. Filter by isPublished=true for public boards.

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 listCustomBoards Business API includes a REST controller that can be triggered via the following route:

/v1/customboards

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 listCustomBoards Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The listCustomBoards 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 listCustomBoards api supports 3 optional filter parameters for filtering list results using URL query parameters. These parameters are only available for list type APIs.

isPublished Filter

Type: Boolean
Description: Filter by isPublished
Location: Query Parameter

Usage:

Examples:

// Get records with true value
GET /v1/customboards?isPublished=true

// Get records with false value (or null)
GET /v1/customboards?isPublished=false

// Get records without this field
GET /v1/customboards?isPublished=null

Note: When filtering by false, the query also includes records where the boolean field is null.

category Filter

Type: Enum
Description: Filter by category
Location: Query Parameter

Usage:

Examples:

// Get records with specific enum value
GET /v1/customboards?category=active

// Get records with multiple enum values (use multiple parameters)
GET /v1/customboards?category=active&category=pending

// Get records without this field
GET /v1/customboards?category=null

createdById Filter

Type: ID
Description: Filter by createdById
Location: Query Parameter

Usage:

Non-Array Property:

Examples:

// Get records with a specific ID
GET /v1/customboards?createdById=550e8400-e29b-41d4-a716-446655440000

// Get records with multiple IDs (use multiple parameters)
GET /v1/customboards?createdById=550e8400-e29b-41d4-a716-446655440000&createdById=660e8400-e29b-41d4-a716-446655440001

// Get records without this field
GET /v1/customboards?createdById=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 listCustomBoards Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Select Clause

Specifies which fields will be selected from the main data object during a get or list operation. Leave blank to select all properties. This applies only to get and list type APIs.",

``

Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({isActive:true}), {"path":"services[1].businessLogic[12].whereClause.fullWhereClause"})

List Options

Defines list-specific options including filtering logic, default sorting, and result customization for APIs that return multiple records.

List Sort By Sort order definitions for the result set. Multiple fields can be provided with direction (asc/desc).

[ 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, sseSettings, cronSettings

[2] Step : readParameters

Reads request and Redis parameters, applies defaults, and writes them to context for downstream processing.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Transforms and normalizes parameters, derives dependent values, and reshapes inputs for the main list query.


[4] Step : checkParameters

Executes validation logic on required and custom parameters, enforcing business rules and cross-field consistency.


[5] Step : checkBasicAuth

Performs role-based access checks and applies dynamic membership or session-based restrictions.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildWhereClause

Constructs the main query WHERE clause and applies optional filters or scoped access controls.

You can use the following settings to change some behavior of this step. whereClause

[7] Step : mainListOperation

Executes the paginated database query, retrieves the list, and stores results in context for enrichment.

You can use the following settings to change some behavior of this step. selectClause, listOptions, paginationOptions

[8] Step : buildOutput

Assembles the list response, sanitizes sensitive fields, applies transformations, and injects extra context if needed.


[9] Step : sendResponse

Sends the paginated list to the client through the controller.


[10] Step : raiseApiEvent

Triggers optional post-workflow events, such as Kafka messages, logs, or system notifications.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The listCustomBoards 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
isPublished Boolean No Filter by isPublished
category Enum No Filter by category
createdById ID No Filter by createdById

REST Request

To access the api you can use the REST controller with the path GET /v1/customboards

  axios({
    method: 'GET',
    url: '/v1/customboards',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section for usage examples)
        // isPublished: '<value>' // Filter by isPublished
        // category: '<value>' // Filter by category
        // createdById: '<value>' // Filter by createdById
            }
  });

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 customBoards 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": "customBoards",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"customBoards": [
		{
			"id": "ID",
			"name": "String",
			"fen": "String",
			"description": "Text",
			"isPublished": "Boolean",
			"category": "Enum",
			"category_idx": "Integer",
			"createdById": "ID",
			"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 - Get Customboard

Business API Design Specification - Get Customboard

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 getCustomBoard 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 getCustomBoard Business API is designed to handle a get operation on the CustomBoard 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 custom board position by ID.

API Frontend Description By The Backend Architect

Used to load a specific custom board for editing or playing.

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 getCustomBoard Business API includes a REST controller that can be triggered via the following route:

/v1/customboards/:customBoardId

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 getCustomBoard Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The getCustomBoard 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
customBoardId ID Yes - urlpath customBoardId
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 getCustomBoard Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Select Clause

Specifies which fields will be selected from the main data object during a get or list operation. Leave blank to select all properties. This applies only to get and list type APIs.",

``

Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({$and:[{id:this.customBoardId},{isActive:true}]}), {"path":"services[1].businessLogic[13].whereClause.fullWhereClause"})

Get Options

Use these options to set get specific settings.

setAsRead: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed.

No setAsread field-value pair is configured.

Business Logic Workflow

[1] Step : startBusinessApi

Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Extracts parameters from request and Redis, applies defaults, and writes them to context.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Executes parameter transformation scripts, applies type coercion, merges derived values, and reshapes inputs for downstream milestones.


[4] Step : checkParameters

Validates required and custom parameters, enforcing business-specific rules and constraints.


[5] Step : checkBasicAuth

Performs login, role, and permission checks, and applies dynamic object-level access rules.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildWhereClause

Builds the WHERE clause for fetching the object and applies additional scoped filters if configured.

You can use the following settings to change some behavior of this step. whereClause

[7] Step : mainGetOperation

Executes the database fetch, retrieves the object, and stores it in context for enrichment or further checks.

You can use the following settings to change some behavior of this step. selectClause, getOptions

[8] Step : checkInstance

Performs instance-level validations, such as ownership, existence, or access conditions.


[9] Step : buildOutput

Assembles the response from the object, applies masking, formatting, and injects additional metadata if needed.


[10] Step : sendResponse

Delivers the response to the controller for client delivery.


[11] Step : raiseApiEvent

Triggers optional API-level events after workflow completion, sending messages to integrations like Kafka if configured.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The getCustomBoard api has got 1 regular client parameter

Parameter Type Required Population
customBoardId ID true request.params?.[“customBoardId”]

REST Request

To access the api you can use the REST controller with the path GET /v1/customboards/:customBoardId

  axios({
    method: 'GET',
    url: `/v1/customboards/${customBoardId}`,
    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 customBoard 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": "customBoard",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"customBoard": {
		"id": "ID",
		"name": "String",
		"fen": "String",
		"description": "Text",
		"isPublished": "Boolean",
		"category": "Enum",
		"category_idx": "Integer",
		"createdById": "ID",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Business API Design Specification - Update Customboard

Business API Design Specification - Update Customboard

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 updateCustomBoard 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 updateCustomBoard Business API is designed to handle a update operation on the CustomBoard data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

Update a custom board position. Only the creator can update their own boards.

API Frontend Description By The Backend Architect

Used to edit board name, description, FEN, category, or publish/unpublish.

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 updateCustomBoard Business API includes a REST controller that can be triggered via the following route:

/v1/customboards/:customBoardId

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 updateCustomBoard Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The updateCustomBoard 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
customBoardId ID Yes - urlpath customBoardId
Description: This id paremeter is used to select the required data object that will be updated
name String No - body name
Description: Name of the custom board position
fen String No - body fen
Description: FEN string representing the board position
description Text No - body description
Description: Optional description of the custom board
isPublished Boolean No - body isPublished
Description: -
category Enum No - body category
Description: -
createdById ID No - body createdById
Description: -

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 updateCustomBoard Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({$and:[{id:this.customBoardId},{isActive:true}]}), {"path":"services[1].businessLogic[14].whereClause.fullWhereClause"})

Data Clause

Defines custom field-value assignments used to modify or augment the default payload for create and update operations. These settings override values derived from the session or parameters if explicitly provided.", Note that a default data clause is always prepared by Mindbricks using data property settings, however any property in the data clause can be override by Data Clause Settings.

An update data clause populates all update-allowed properties of a data object, however the null properties (that are not provided by client) are ignored in db layer.

Custom Data Clause Override No custom data clause override configured

Actual Data Clause

The business api will use the following data clause. Note that any calculated value will be added to the data clause in the api manager.

{
  name: this.name,
  fen: this.fen,
  description: this.description,
  isPublished: this.isPublished,
  category: this.category,
  createdById: this.createdById,
}

Business Logic Workflow

[1] Step : startBusinessApi

Manager initializes context, prepares request and session objects, and sets up internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Manager reads parameters from the request or Redis, applies defaults, and writes them into context for downstream milestones.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Manager executes parameter transform scripts and derives any helper values or reshaped payloads into the context.


[4] Step : checkParameters

Manager validates required parameters, checks ID formats (UUID/ObjectId), and ensures all preconditions for update are met.


[5] Step : checkBasicAuth

Manager performs login verification, role, and permission checks, enforcing tenant and access rules before update.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildWhereClause

Manager constructs the WHERE clause used to identify the record to update, applying ownership and parent checks if necessary.

You can use the following settings to change some behavior of this step. whereClause

[7] Step : fetchInstance

Manager fetches the existing record from the database and writes it to the context for validation or enrichment.


[8] Step : checkInstance

Manager performs instance-level validations, including ownership, existence, lock status, or other pre-update checks.


[9] Step : buildDataClause

Manager prepares the data clause for the update, applying transformations or enhancements before persisting.

You can use the following settings to change some behavior of this step. dataClause

[10] Step : mainUpdateOperation

Manager executes the update operation with the WHERE and data clauses. Database-level events are raised if configured.


[11] Step : buildOutput

Manager assembles the response object from the update result, masking fields or injecting additional metadata.


[12] Step : sendResponse

Manager sends the response back to the controller for delivery to the client.


[13] Step : raiseApiEvent

Manager triggers API-level events, sending relevant messages to Kafka or other integrations if configured.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The updateCustomBoard api has got 7 regular client parameters

Parameter Type Required Population
customBoardId ID true request.params?.[“customBoardId”]
name String false request.body?.[“name”]
fen String false request.body?.[“fen”]
description Text false request.body?.[“description”]
isPublished Boolean request.body?.[“isPublished”]
category Enum request.body?.[“category”]
createdById ID request.body?.[“createdById”]

REST Request

To access the api you can use the REST controller with the path PATCH /v1/customboards/:customBoardId

  axios({
    method: 'PATCH',
    url: `/v1/customboards/${customBoardId}`,
    data: {
            name:"String",  
            fen:"String",  
            description:"Text",  
            isPublished:"Boolean",  
            category:"Enum",  
            createdById:"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 customBoard 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": "customBoard",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"customBoard": {
		"id": "ID",
		"name": "String",
		"fen": "String",
		"description": "Text",
		"isPublished": "Boolean",
		"category": "Enum",
		"category_idx": "Integer",
		"createdById": "ID",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Business API Design Specification - Delete Customboard

Business API Design Specification - Delete Customboard

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 deleteCustomBoard 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 deleteCustomBoard Business API is designed to handle a delete operation on the CustomBoard 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 custom board position (soft-delete). Only creator or admin can delete.

API Frontend Description By The Backend Architect

Used to remove a custom board. Soft-deletes so data can be recovered 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 deleteCustomBoard Business API includes a REST controller that can be triggered via the following route:

/v1/customboards/:customBoardId

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 deleteCustomBoard Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The deleteCustomBoard 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
customBoardId ID Yes - urlpath customBoardId
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 deleteCustomBoard Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({$and:[{id:this.customBoardId},{isActive:true}]}), {"path":"services[1].businessLogic[15].whereClause.fullWhereClause"})

Delete Options

Use these options to set delete specific settings.

useSoftDelete: true If true, the record will be marked as deleted (isActive: false) instead of removed. The implementation depends on the data object’s soft delete configuration.

Business Logic Workflow

[1] Step : startBusinessApi

Manager initializes context, prepares request/session objects, and sets up internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] 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 deleteCustomBoard api has got 1 regular client parameter

Parameter Type Required Population
customBoardId ID true request.params?.[“customBoardId”]

REST Request

To access the api you can use the REST controller with the path DELETE /v1/customboards/:customBoardId

  axios({
    method: 'DELETE',
    url: `/v1/customboards/${customBoardId}`,
    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 customBoard 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": "customBoard",
	"method": "DELETE",
	"action": "delete",
	"appVersion": "Version",
	"rowCount": 1,
	"customBoard": {
		"id": "ID",
		"name": "String",
		"fen": "String",
		"description": "Text",
		"isPublished": "Boolean",
		"category": "Enum",
		"category_idx": "Integer",
		"createdById": "ID",
		"isActive": false,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Business API Design Specification - Create Boardtheme

Business API Design Specification - Create Boardtheme

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 createBoardTheme 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 createBoardTheme Business API is designed to handle a create operation on the BoardTheme 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 custom board color theme.

API Frontend Description By The Backend Architect

Called when user saves a new custom theme from the themes picker.

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 createBoardTheme Business API includes a REST controller that can be triggered via the following route:

/v1/boardthemes

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 createBoardTheme Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The createBoardTheme 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
boardThemeId ID No - body boardThemeId
Description: This id paremeter is used to create the data object with a given specific id. Leave null for automatic id.
name String Yes - body name
Description: Theme display name
lightSquare String Yes - body lightSquare
Description: Hex color for light squares
darkSquare String Yes - body darkSquare
Description: Hex color for dark squares
createdById ID Yes - body createdById
Description: User who created this theme

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 createBoardTheme 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.boardThemeId,
  name: this.name,
  lightSquare: this.lightSquare,
  darkSquare: this.darkSquare,
  createdById: this.createdById,
  isActive: true,
  _archivedAt: null,
}

Business Logic Workflow

[1] Step : startBusinessApi

Manager initializes context, populates session and request objects, prepares internal structures for parameter handling and workflow execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Manager reads input parameters, normalizes missing values, applies default type casting, and stores them in the API context.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Manager transforms parameters, computes derived values, flattens or remaps arrays/objects, and adjusts formats for downstream processing.


[4] Step : checkParameters

Manager executes built-in validations: required field checks, type enforcement, and basic business rules. Prevents operation if validation fails.


[5] Step : checkBasicAuth

Manager performs authentication and authorization checks: verifies session, user roles, permissions, and tenant restrictions.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildDataClause

Manager constructs the final data object for creation, fills auto-generated fields (IDs, timestamps, owner fields), and ensures schema consistency.

You can use the following settings to change some behavior of this step. dataClause

[7] Step : mainCreateOperation

Manager executes the database insert operation, updates indexes/caches, and triggers internal post-processing like linked default records.


[8] Step : buildOutput

Manager shapes the response: masks sensitive fields, resolves linked references, and formats output according to API contract.


[9] Step : sendResponse

Manager sends the response to the client and finalizes internal tasks like flushing logs or updating session state.


[10] Step : raiseApiEvent

Manager triggers API-level events (Kafka, WebSocket, async workflows) as the final internal step.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The createBoardTheme api has got 4 regular client parameters

Parameter Type Required Population
name String true request.body?.[“name”]
lightSquare String true request.body?.[“lightSquare”]
darkSquare String true request.body?.[“darkSquare”]
createdById ID true request.body?.[“createdById”]

REST Request

To access the api you can use the REST controller with the path POST /v1/boardthemes

  axios({
    method: 'POST',
    url: '/v1/boardthemes',
    data: {
            name:"String",  
            lightSquare:"String",  
            darkSquare:"String",  
            createdById:"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 boardTheme 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": "boardTheme",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"boardTheme": {
		"id": "ID",
		"name": "String",
		"lightSquare": "String",
		"darkSquare": "String",
		"isPublished": "Boolean",
		"createdById": "ID",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Business API Design Specification - List Boardthemes

Business API Design Specification - List Boardthemes

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 listBoardThemes 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 listBoardThemes Business API is designed to handle a list operation on the BoardTheme data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

List board themes. Filter by isPublished for community themes or createdById for user’s own.

API Frontend Description By The Backend Architect

Used to load user’s custom themes and community-published themes.

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 listBoardThemes Business API includes a REST controller that can be triggered via the following route:

/v1/boardthemes

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 listBoardThemes Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The listBoardThemes 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 listBoardThemes api supports 1 optional filter parameter for filtering list results using URL query parameters. These parameters are only available for list type APIs.

isPublished Filter

Type: Boolean
Description: Whether the theme is publicly visible
Location: Query Parameter

Usage:

Examples:

// Get records with true value
GET /v1/boardthemes?isPublished=true

// Get records with false value (or null)
GET /v1/boardthemes?isPublished=false

// Get records without this field
GET /v1/boardthemes?isPublished=null

Note: When filtering by false, the query also includes records where the boolean field is 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 listBoardThemes Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Select Clause

Specifies which fields will be selected from the main data object during a get or list operation. Leave blank to select all properties. This applies only to get and list type APIs.",

``

Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({isActive:true}), {"path":"services[1].businessLogic[17].whereClause.fullWhereClause"})

List Options

Defines list-specific options including filtering logic, default sorting, and result customization for APIs that return multiple records.

List Sort By Sort order definitions for the result set. Multiple fields can be provided with direction (asc/desc).

[ 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, sseSettings, cronSettings

[2] Step : readParameters

Reads request and Redis parameters, applies defaults, and writes them to context for downstream processing.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Transforms and normalizes parameters, derives dependent values, and reshapes inputs for the main list query.


[4] Step : checkParameters

Executes validation logic on required and custom parameters, enforcing business rules and cross-field consistency.


[5] Step : checkBasicAuth

Performs role-based access checks and applies dynamic membership or session-based restrictions.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildWhereClause

Constructs the main query WHERE clause and applies optional filters or scoped access controls.

You can use the following settings to change some behavior of this step. whereClause

[7] Step : mainListOperation

Executes the paginated database query, retrieves the list, and stores results in context for enrichment.

You can use the following settings to change some behavior of this step. selectClause, listOptions, paginationOptions

[8] Step : buildOutput

Assembles the list response, sanitizes sensitive fields, applies transformations, and injects extra context if needed.


[9] Step : sendResponse

Sends the paginated list to the client through the controller.


[10] Step : raiseApiEvent

Triggers optional post-workflow events, such as Kafka messages, logs, or system notifications.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The listBoardThemes 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
isPublished Boolean No Whether the theme is publicly visible

REST Request

To access the api you can use the REST controller with the path GET /v1/boardthemes

  axios({
    method: 'GET',
    url: '/v1/boardthemes',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section for usage examples)
        // isPublished: '<value>' // Filter by isPublished
            }
  });

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 boardThemes 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": "boardThemes",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"boardThemes": [
		{
			"id": "ID",
			"name": "String",
			"lightSquare": "String",
			"darkSquare": "String",
			"isPublished": "Boolean",
			"createdById": "ID",
			"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 Boardtheme

Business API Design Specification - Update Boardtheme

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 updateBoardTheme 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 updateBoardTheme Business API is designed to handle a update operation on the BoardTheme data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

Update a custom board theme. Only creator can update.

API Frontend Description By The Backend Architect

Used to edit theme colors/name or publish/unpublish.

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 updateBoardTheme Business API includes a REST controller that can be triggered via the following route:

/v1/boardthemes/:boardThemeId

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 updateBoardTheme Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The updateBoardTheme 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
boardThemeId ID Yes - urlpath boardThemeId
Description: This id paremeter is used to select the required data object that will be updated
name String No - body name
Description: Theme display name
lightSquare String No - body lightSquare
Description: Hex color for light squares
darkSquare String No - body darkSquare
Description: Hex color for dark squares
isPublished Boolean No - body isPublished
Description: Whether the theme is publicly visible

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 updateBoardTheme Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({$and:[{id:this.boardThemeId},{isActive:true}]}), {"path":"services[1].businessLogic[18].whereClause.fullWhereClause"})

Data Clause

Defines custom field-value assignments used to modify or augment the default payload for create and update operations. These settings override values derived from the session or parameters if explicitly provided.", Note that a default data clause is always prepared by Mindbricks using data property settings, however any property in the data clause can be override by Data Clause Settings.

An update data clause populates all update-allowed properties of a data object, however the null properties (that are not provided by client) are ignored in db layer.

Custom Data Clause Override No custom data clause override configured

Actual Data Clause

The business api will use the following data clause. Note that any calculated value will be added to the data clause in the api manager.

{
  name: this.name,
  lightSquare: this.lightSquare,
  darkSquare: this.darkSquare,
  isPublished: this.isPublished,
}

Business Logic Workflow

[1] Step : startBusinessApi

Manager initializes context, prepares request and session objects, and sets up internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Manager reads parameters from the request or Redis, applies defaults, and writes them into context for downstream milestones.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Manager executes parameter transform scripts and derives any helper values or reshaped payloads into the context.


[4] Step : checkParameters

Manager validates required parameters, checks ID formats (UUID/ObjectId), and ensures all preconditions for update are met.


[5] Step : checkBasicAuth

Manager performs login verification, role, and permission checks, enforcing tenant and access rules before update.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildWhereClause

Manager constructs the WHERE clause used to identify the record to update, applying ownership and parent checks if necessary.

You can use the following settings to change some behavior of this step. whereClause

[7] Step : fetchInstance

Manager fetches the existing record from the database and writes it to the context for validation or enrichment.


[8] Step : checkInstance

Manager performs instance-level validations, including ownership, existence, lock status, or other pre-update checks.


[9] Step : buildDataClause

Manager prepares the data clause for the update, applying transformations or enhancements before persisting.

You can use the following settings to change some behavior of this step. dataClause

[10] Step : mainUpdateOperation

Manager executes the update operation with the WHERE and data clauses. Database-level events are raised if configured.


[11] Step : buildOutput

Manager assembles the response object from the update result, masking fields or injecting additional metadata.


[12] Step : sendResponse

Manager sends the response back to the controller for delivery to the client.


[13] Step : raiseApiEvent

Manager triggers API-level events, sending relevant messages to Kafka or other integrations if configured.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The updateBoardTheme api has got 5 regular client parameters

Parameter Type Required Population
boardThemeId ID true request.params?.[“boardThemeId”]
name String false request.body?.[“name”]
lightSquare String false request.body?.[“lightSquare”]
darkSquare String false request.body?.[“darkSquare”]
isPublished Boolean false request.body?.[“isPublished”]

REST Request

To access the api you can use the REST controller with the path PATCH /v1/boardthemes/:boardThemeId

  axios({
    method: 'PATCH',
    url: `/v1/boardthemes/${boardThemeId}`,
    data: {
            name:"String",  
            lightSquare:"String",  
            darkSquare:"String",  
            isPublished:"Boolean",  
    
    },
    params: {
    
        }
  });

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the boardTheme 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": "boardTheme",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"boardTheme": {
		"id": "ID",
		"name": "String",
		"lightSquare": "String",
		"darkSquare": "String",
		"isPublished": "Boolean",
		"createdById": "ID",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Business API Design Specification - Delete Boardtheme

Business API Design Specification - Delete Boardtheme

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 deleteBoardTheme 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 deleteBoardTheme Business API is designed to handle a delete operation on the BoardTheme 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 custom board theme (soft-delete). Only creator can delete.

API Frontend Description By The Backend Architect

Used to remove user’s custom theme.

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 deleteBoardTheme Business API includes a REST controller that can be triggered via the following route:

/v1/boardthemes/:boardThemeId

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 deleteBoardTheme Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The deleteBoardTheme 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
boardThemeId ID Yes - urlpath boardThemeId
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 deleteBoardTheme Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({$and:[{id:this.boardThemeId},{isActive:true}]}), {"path":"services[1].businessLogic[19].whereClause.fullWhereClause"})

Delete Options

Use these options to set delete specific settings.

useSoftDelete: true If true, the record will be marked as deleted (isActive: false) instead of removed. The implementation depends on the data object’s soft delete configuration.

Business Logic Workflow

[1] Step : startBusinessApi

Manager initializes context, prepares request/session objects, and sets up internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] 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 deleteBoardTheme api has got 1 regular client parameter

Parameter Type Required Population
boardThemeId ID true request.params?.[“boardThemeId”]

REST Request

To access the api you can use the REST controller with the path DELETE /v1/boardthemes/:boardThemeId

  axios({
    method: 'DELETE',
    url: `/v1/boardthemes/${boardThemeId}`,
    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 boardTheme 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": "boardTheme",
	"method": "DELETE",
	"action": "delete",
	"appVersion": "Version",
	"rowCount": 1,
	"boardTheme": {
		"id": "ID",
		"name": "String",
		"lightSquare": "String",
		"darkSquare": "String",
		"isPublished": "Boolean",
		"createdById": "ID",
		"isActive": false,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Business API Design Specification - Create Userpreference

Business API Design Specification - Create Userpreference

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 createUserPreference 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 createUserPreference Business API is designed to handle a create operation on the UserPreference data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

Create user preferences record. One per user, auto-sets userId from session.

API Frontend Description By The Backend Architect

Called once when user first changes a preference. userId is auto-set.

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 createUserPreference Business API includes a REST controller that can be triggered via the following route:

/v1/userpreferences

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 createUserPreference Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The createUserPreference 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
userPreferenceId ID No - body userPreferenceId
Description: This id paremeter is used to create the data object with a given specific id. Leave null for automatic id.
userId ID Yes - body userId
Description: The user this preferences record belongs to
activeThemeId String No - body activeThemeId
Description: ID of the currently selected board theme (preset ID or custom theme ID)
soundEnabled Boolean No - body soundEnabled
Description: Whether game sounds are enabled
showAnimations Boolean No - body showAnimations
Description: Whether board animations are shown
boardOrientation Enum No - body boardOrientation
Description: Default board orientation preference
premoveEnabled Boolean No - body premoveEnabled
Description: Whether premove feature is enabled

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 createUserPreference 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.userPreferenceId,
  userId: this.userId,
  activeThemeId: this.activeThemeId,
  soundEnabled: this.soundEnabled,
  showAnimations: this.showAnimations,
  boardOrientation: this.boardOrientation,
  premoveEnabled: this.premoveEnabled,
  isActive: true,
  _archivedAt: null,
}

Business Logic Workflow

[1] Step : startBusinessApi

Manager initializes context, populates session and request objects, prepares internal structures for parameter handling and workflow execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Manager reads input parameters, normalizes missing values, applies default type casting, and stores them in the API context.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Manager transforms parameters, computes derived values, flattens or remaps arrays/objects, and adjusts formats for downstream processing.


[4] Step : checkParameters

Manager executes built-in validations: required field checks, type enforcement, and basic business rules. Prevents operation if validation fails.


[5] Step : checkBasicAuth

Manager performs authentication and authorization checks: verifies session, user roles, permissions, and tenant restrictions.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildDataClause

Manager constructs the final data object for creation, fills auto-generated fields (IDs, timestamps, owner fields), and ensures schema consistency.

You can use the following settings to change some behavior of this step. dataClause

[7] Step : mainCreateOperation

Manager executes the database insert operation, updates indexes/caches, and triggers internal post-processing like linked default records.


[8] Step : buildOutput

Manager shapes the response: masks sensitive fields, resolves linked references, and formats output according to API contract.


[9] Step : sendResponse

Manager sends the response to the client and finalizes internal tasks like flushing logs or updating session state.


[10] Step : raiseApiEvent

Manager triggers API-level events (Kafka, WebSocket, async workflows) as the final internal step.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The createUserPreference api has got 6 regular client parameters

Parameter Type Required Population
userId ID true request.body?.[“userId”]
activeThemeId String false request.body?.[“activeThemeId”]
soundEnabled Boolean false request.body?.[“soundEnabled”]
showAnimations Boolean false request.body?.[“showAnimations”]
boardOrientation Enum false request.body?.[“boardOrientation”]
premoveEnabled Boolean false request.body?.[“premoveEnabled”]

REST Request

To access the api you can use the REST controller with the path POST /v1/userpreferences

  axios({
    method: 'POST',
    url: '/v1/userpreferences',
    data: {
            userId:"ID",  
            activeThemeId:"String",  
            soundEnabled:"Boolean",  
            showAnimations:"Boolean",  
            boardOrientation:"Enum",  
            premoveEnabled:"Boolean",  
    
    },
    params: {
    
        }
  });

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the userPreference 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": "userPreference",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"userPreference": {
		"id": "ID",
		"userId": "ID",
		"activeThemeId": "String",
		"soundEnabled": "Boolean",
		"showAnimations": "Boolean",
		"boardOrientation": "Enum",
		"boardOrientation_idx": "Integer",
		"premoveEnabled": "Boolean",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Business API Design Specification - Update Userpreference

Business API Design Specification - Update Userpreference

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 updateUserPreference 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 updateUserPreference Business API is designed to handle a update operation on the UserPreference data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

Update user preferences. Only the owner can update their own preferences.

API Frontend Description By The Backend Architect

Called when user changes theme, sound, animation, or other settings.

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 updateUserPreference Business API includes a REST controller that can be triggered via the following route:

/v1/userpreferences/:userPreferenceId

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 updateUserPreference Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The updateUserPreference 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
userPreferenceId ID Yes - urlpath userPreferenceId
Description: This id paremeter is used to select the required data object that will be updated
activeThemeId String No - body activeThemeId
Description: ID of the currently selected board theme (preset ID or custom theme ID)
soundEnabled Boolean No - body soundEnabled
Description: Whether game sounds are enabled
showAnimations Boolean No - body showAnimations
Description: Whether board animations are shown
boardOrientation Enum No - body boardOrientation
Description: Default board orientation preference
premoveEnabled Boolean No - body premoveEnabled
Description: Whether premove feature is enabled

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 updateUserPreference Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({$and:[{id:this.userPreferenceId},{isActive:true}]}), {"path":"services[1].businessLogic[21].whereClause.fullWhereClause"})

Data Clause

Defines custom field-value assignments used to modify or augment the default payload for create and update operations. These settings override values derived from the session or parameters if explicitly provided.", Note that a default data clause is always prepared by Mindbricks using data property settings, however any property in the data clause can be override by Data Clause Settings.

An update data clause populates all update-allowed properties of a data object, however the null properties (that are not provided by client) are ignored in db layer.

Custom Data Clause Override No custom data clause override configured

Actual Data Clause

The business api will use the following data clause. Note that any calculated value will be added to the data clause in the api manager.

{
  activeThemeId: this.activeThemeId,
  soundEnabled: this.soundEnabled,
  showAnimations: this.showAnimations,
  boardOrientation: this.boardOrientation,
  premoveEnabled: this.premoveEnabled,
}

Business Logic Workflow

[1] Step : startBusinessApi

Manager initializes context, prepares request and session objects, and sets up internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Manager reads parameters from the request or Redis, applies defaults, and writes them into context for downstream milestones.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Manager executes parameter transform scripts and derives any helper values or reshaped payloads into the context.


[4] Step : checkParameters

Manager validates required parameters, checks ID formats (UUID/ObjectId), and ensures all preconditions for update are met.


[5] Step : checkBasicAuth

Manager performs login verification, role, and permission checks, enforcing tenant and access rules before update.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildWhereClause

Manager constructs the WHERE clause used to identify the record to update, applying ownership and parent checks if necessary.

You can use the following settings to change some behavior of this step. whereClause

[7] Step : fetchInstance

Manager fetches the existing record from the database and writes it to the context for validation or enrichment.


[8] Step : checkInstance

Manager performs instance-level validations, including ownership, existence, lock status, or other pre-update checks.


[9] Step : buildDataClause

Manager prepares the data clause for the update, applying transformations or enhancements before persisting.

You can use the following settings to change some behavior of this step. dataClause

[10] Step : mainUpdateOperation

Manager executes the update operation with the WHERE and data clauses. Database-level events are raised if configured.


[11] Step : buildOutput

Manager assembles the response object from the update result, masking fields or injecting additional metadata.


[12] Step : sendResponse

Manager sends the response back to the controller for delivery to the client.


[13] Step : raiseApiEvent

Manager triggers API-level events, sending relevant messages to Kafka or other integrations if configured.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The updateUserPreference api has got 6 regular client parameters

Parameter Type Required Population
userPreferenceId ID true request.params?.[“userPreferenceId”]
activeThemeId String false request.body?.[“activeThemeId”]
soundEnabled Boolean false request.body?.[“soundEnabled”]
showAnimations Boolean false request.body?.[“showAnimations”]
boardOrientation Enum false request.body?.[“boardOrientation”]
premoveEnabled Boolean false request.body?.[“premoveEnabled”]

REST Request

To access the api you can use the REST controller with the path PATCH /v1/userpreferences/:userPreferenceId

  axios({
    method: 'PATCH',
    url: `/v1/userpreferences/${userPreferenceId}`,
    data: {
            activeThemeId:"String",  
            soundEnabled:"Boolean",  
            showAnimations:"Boolean",  
            boardOrientation:"Enum",  
            premoveEnabled:"Boolean",  
    
    },
    params: {
    
        }
  });

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the userPreference 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": "userPreference",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"userPreference": {
		"id": "ID",
		"userId": "ID",
		"activeThemeId": "String",
		"soundEnabled": "Boolean",
		"showAnimations": "Boolean",
		"boardOrientation": "Enum",
		"boardOrientation_idx": "Integer",
		"premoveEnabled": "Boolean",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Business API Design Specification - Get Userpreference

Business API Design Specification - Get Userpreference

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 getUserPreference 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 getUserPreference Business API is designed to handle a get operation on the UserPreference 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 user’s preferences by ID.

API Frontend Description By The Backend Architect

Called on app load to restore user’s preferences.

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 getUserPreference Business API includes a REST controller that can be triggered via the following route:

/v1/userpreferences/:userPreferenceId

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 getUserPreference Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The getUserPreference 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
userPreferenceId ID Yes - urlpath userPreferenceId
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 getUserPreference Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Select Clause

Specifies which fields will be selected from the main data object during a get or list operation. Leave blank to select all properties. This applies only to get and list type APIs.",

``

Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({$and:[{id:this.userPreferenceId},{isActive:true}]}), {"path":"services[1].businessLogic[22].whereClause.fullWhereClause"})

Get Options

Use these options to set get specific settings.

setAsRead: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed.

No setAsread field-value pair is configured.

Business Logic Workflow

[1] Step : startBusinessApi

Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Extracts parameters from request and Redis, applies defaults, and writes them to context.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Executes parameter transformation scripts, applies type coercion, merges derived values, and reshapes inputs for downstream milestones.


[4] Step : checkParameters

Validates required and custom parameters, enforcing business-specific rules and constraints.


[5] Step : checkBasicAuth

Performs login, role, and permission checks, and applies dynamic object-level access rules.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildWhereClause

Builds the WHERE clause for fetching the object and applies additional scoped filters if configured.

You can use the following settings to change some behavior of this step. whereClause

[7] Step : mainGetOperation

Executes the database fetch, retrieves the object, and stores it in context for enrichment or further checks.

You can use the following settings to change some behavior of this step. selectClause, getOptions

[8] Step : checkInstance

Performs instance-level validations, such as ownership, existence, or access conditions.


[9] Step : buildOutput

Assembles the response from the object, applies masking, formatting, and injects additional metadata if needed.


[10] Step : sendResponse

Delivers the response to the controller for client delivery.


[11] Step : raiseApiEvent

Triggers optional API-level events after workflow completion, sending messages to integrations like Kafka if configured.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The getUserPreference api has got 1 regular client parameter

Parameter Type Required Population
userPreferenceId ID true request.params?.[“userPreferenceId”]

REST Request

To access the api you can use the REST controller with the path GET /v1/userpreferences/:userPreferenceId

  axios({
    method: 'GET',
    url: `/v1/userpreferences/${userPreferenceId}`,
    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 userPreference 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": "userPreference",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"userPreference": {
		"id": "ID",
		"userId": "ID",
		"activeThemeId": "String",
		"soundEnabled": "Boolean",
		"showAnimations": "Boolean",
		"boardOrientation": "Enum",
		"boardOrientation_idx": "Integer",
		"premoveEnabled": "Boolean",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Business API Design Specification - List Userpreferences

Business API Design Specification - List Userpreferences

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 listUserPreferences 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 listUserPreferences Business API is designed to handle a list operation on the UserPreference data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

List user preferences. Filter by userId to get a specific user’s preferences.

API Frontend Description By The Backend Architect

Used to find user’s preference record by userId filter.

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 listUserPreferences Business API includes a REST controller that can be triggered via the following route:

/v1/userpreferences

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 listUserPreferences Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The listUserPreferences 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 listUserPreferences Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Select Clause

Specifies which fields will be selected from the main data object during a get or list operation. Leave blank to select all properties. This applies only to get and list type APIs.",

``

Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({isActive:true}), {"path":"services[1].businessLogic[23].whereClause.fullWhereClause"})

List Options

Defines list-specific options including filtering logic, default sorting, and result customization for APIs that return multiple records.

List Sort By Sort order definitions for the result set. Multiple fields can be provided with direction (asc/desc).

Specific sort order is not configure, natural order (ascending id) will be used.

List Group By Grouping definitions for the result set. This is typically used for visual or report-based grouping.

The list is not grouped.

setAsRead: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed.

No setAsread field-value pair is configured.

Permission Filter Optional filter that applies permission constraints dynamically based on session or object roles. So that the list items are filtered by the user’s OBAC or ABAC permissions.

Permission filter is not active at the moment. Follow Mindbricks updates to be able to use it.

Pagination Options

Contains settings to configure pagination behavior for list APIs. Includes options like page size, offset, cursor support, and total count inclusion.

Business Logic Workflow

[1] Step : startBusinessApi

Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Reads request and Redis parameters, applies defaults, and writes them to context for downstream processing.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Transforms and normalizes parameters, derives dependent values, and reshapes inputs for the main list query.


[4] Step : checkParameters

Executes validation logic on required and custom parameters, enforcing business rules and cross-field consistency.


[5] Step : checkBasicAuth

Performs role-based access checks and applies dynamic membership or session-based restrictions.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildWhereClause

Constructs the main query WHERE clause and applies optional filters or scoped access controls.

You can use the following settings to change some behavior of this step. whereClause

[7] Step : mainListOperation

Executes the paginated database query, retrieves the list, and stores results in context for enrichment.

You can use the following settings to change some behavior of this step. selectClause, listOptions, paginationOptions

[8] Step : buildOutput

Assembles the list response, sanitizes sensitive fields, applies transformations, and injects extra context if needed.


[9] Step : sendResponse

Sends the paginated list to the client through the controller.


[10] Step : raiseApiEvent

Triggers optional post-workflow events, such as Kafka messages, logs, or system notifications.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The listUserPreferences api has got no visible parameters.

REST Request

To access the api you can use the REST controller with the path GET /v1/userpreferences

  axios({
    method: 'GET',
    url: '/v1/userpreferences',
    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 userPreferences 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": "userPreferences",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"userPreferences": [
		{
			"id": "ID",
			"userId": "ID",
			"activeThemeId": "String",
			"soundEnabled": "Boolean",
			"showAnimations": "Boolean",
			"boardOrientation": "Enum",
			"boardOrientation_idx": "Integer",
			"premoveEnabled": "Boolean",
			"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 Gamehubmessages

Business API Design Specification - List Gamehubmessages

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 listGameHubMessages 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 listGameHubMessages Business API is designed to handle a list operation on the GameHubMessage data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

List messages in a gameHub hub room. Accessible by admins and room participants.

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 listGameHubMessages Business API includes a REST controller that can be triggered via the following route:

/v1/v1/gameHub-messages

By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the Parameters section.

MCP Tool

REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This listGameHubMessages Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The listGameHubMessages 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:

Filter Parameters

The listGameHubMessages api supports 8 optional filter parameters for filtering list results using URL query parameters. These parameters are only available for list type APIs.

roomId Filter

Type: ID
Description: Reference to the room this message belongs to
Location: Query Parameter

Usage:

Non-Array Property:

Examples:

// Get records with a specific ID
GET /v1/v1/gameHub-messages?roomId=550e8400-e29b-41d4-a716-446655440000

// Get records with multiple IDs (use multiple parameters)
GET /v1/v1/gameHub-messages?roomId=550e8400-e29b-41d4-a716-446655440000&roomId=660e8400-e29b-41d4-a716-446655440001

// Get records without this field
GET /v1/v1/gameHub-messages?roomId=null

senderId Filter

Type: ID
Description: Reference to the user who sent this message
Location: Query Parameter

Usage:

Non-Array Property:

Examples:

// Get records with a specific ID
GET /v1/v1/gameHub-messages?senderId=550e8400-e29b-41d4-a716-446655440000

// Get records with multiple IDs (use multiple parameters)
GET /v1/v1/gameHub-messages?senderId=550e8400-e29b-41d4-a716-446655440000&senderId=660e8400-e29b-41d4-a716-446655440001

// Get records without this field
GET /v1/v1/gameHub-messages?senderId=null

senderName Filter

Type: String
Description: Display name of the sender (denormalized from user profile at send time)
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/v1/gameHub-messages?senderName=john
// Matches: "John", "Johnny", "johnson", "McJohn", etc.

// Find records with multiple values (use multiple parameters)
GET /v1/v1/gameHub-messages?senderName=laptop&senderName=phone&senderName=tablet
// Matches records containing "laptop", "phone", or "tablet" anywhere in the field

// Find records without this field
GET /v1/v1/gameHub-messages?senderName=null

senderAvatar Filter

Type: String
Description: Avatar URL of the sender (denormalized from user profile at send time)
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/v1/gameHub-messages?senderAvatar=john
// Matches: "John", "Johnny", "johnson", "McJohn", etc.

// Find records with multiple values (use multiple parameters)
GET /v1/v1/gameHub-messages?senderAvatar=laptop&senderAvatar=phone&senderAvatar=tablet
// Matches records containing "laptop", "phone", or "tablet" anywhere in the field

// Find records without this field
GET /v1/v1/gameHub-messages?senderAvatar=null

messageType Filter

Type: Enum
Description: Content type discriminator for this message
Location: Query Parameter

Usage:

Examples:

// Get records with specific enum value
GET /v1/v1/gameHub-messages?messageType=active

// Get records with multiple enum values (use multiple parameters)
GET /v1/v1/gameHub-messages?messageType=active&messageType=pending

// Get records without this field
GET /v1/v1/gameHub-messages?messageType=null

content Filter

Type: Object
Description: Type-specific content payload (structure depends on messageType)
Location: Query Parameter

Usage:

Examples:

// Get records with specific value
GET /v1/v1/gameHub-messages?content=<value>

// Get records with multiple values (use multiple parameters)
GET /v1/v1/gameHub-messages?content=<value1>&content=<value2>

// Get records without this field
GET /v1/v1/gameHub-messages?content=null

timestamp Filter

Type: String
Description: Message creation time
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/v1/gameHub-messages?timestamp=john
// Matches: "John", "Johnny", "johnson", "McJohn", etc.

// Find records with multiple values (use multiple parameters)
GET /v1/v1/gameHub-messages?timestamp=laptop&timestamp=phone&timestamp=tablet
// Matches records containing "laptop", "phone", or "tablet" anywhere in the field

// Find records without this field
GET /v1/v1/gameHub-messages?timestamp=null

status Filter

Type: Enum
Description: Message moderation status
Location: Query Parameter

Usage:

Examples:

// Get records with specific enum value
GET /v1/v1/gameHub-messages?status=active

// Get records with multiple enum values (use multiple parameters)
GET /v1/v1/gameHub-messages?status=active&status=pending

// Get records without this field
GET /v1/v1/gameHub-messages?status=null

Parameter Transformations

Some parameters are post-processed using transform scripts after being read from the request but before validation or workflow execution. Only parameters with a transform script are listed below.

No parameters are transformed in this API.

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the listGameHubMessages Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Select Clause

Specifies which fields will be selected from the main data object during a get or list operation. Leave blank to select all properties. This applies only to get and list type APIs.",

``

Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({isActive:true}), {"path":"services[1].businessLogic[24].whereClause.fullWhereClause"})

List Options

Defines list-specific options including filtering logic, default sorting, and result customization for APIs that return multiple records.

List Sort By Sort order definitions for the result set. Multiple fields can be provided with direction (asc/desc).

[ timestamp desc ]

List Group By Grouping definitions for the result set. This is typically used for visual or report-based grouping.

The list is not grouped.

setAsRead: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed.

No setAsread field-value pair is configured.

Permission Filter Optional filter that applies permission constraints dynamically based on session or object roles. So that the list items are filtered by the user’s OBAC or ABAC permissions.

Permission filter is not active at the moment. Follow Mindbricks updates to be able to use it.

Pagination Options

Contains settings to configure pagination behavior for list APIs. Includes options like page size, offset, cursor support, and total count inclusion.

Business Logic Workflow

[1] Step : startBusinessApi

Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Reads request and Redis parameters, applies defaults, and writes them to context for downstream processing.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Transforms and normalizes parameters, derives dependent values, and reshapes inputs for the main list query.


[4] Step : checkParameters

Executes validation logic on required and custom parameters, enforcing business rules and cross-field consistency.


[5] Step : checkBasicAuth

Performs role-based access checks and applies dynamic membership or session-based restrictions.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildWhereClause

Constructs the main query WHERE clause and applies optional filters or scoped access controls.

You can use the following settings to change some behavior of this step. whereClause

[7] Step : mainListOperation

Executes the paginated database query, retrieves the list, and stores results in context for enrichment.

You can use the following settings to change some behavior of this step. selectClause, listOptions, paginationOptions

[8] Step : buildOutput

Assembles the list response, sanitizes sensitive fields, applies transformations, and injects extra context if needed.


[9] Step : sendResponse

Sends the paginated list to the client through the controller.


[10] Step : raiseApiEvent

Triggers optional post-workflow events, such as Kafka messages, logs, or system notifications.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The listGameHubMessages api has 8 filter parameters available for filtering list results. See the Filter Parameters section above for detailed usage examples.

Filter Parameter Type Array Property Description
roomId ID No Reference to the room this message belongs to
senderId ID No Reference to the user who sent this message
senderName String No Display name of the sender (denormalized from user profile at send time)
senderAvatar String No Avatar URL of the sender (denormalized from user profile at send time)
messageType Enum No Content type discriminator for this message
content Object No Type-specific content payload (structure depends on messageType)
timestamp String No Message creation time
status Enum No Message moderation status

REST Request

To access the api you can use the REST controller with the path GET /v1/v1/gameHub-messages

  axios({
    method: 'GET',
    url: '/v1/v1/gameHub-messages',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section for usage examples)
        // roomId: '<value>' // Filter by roomId
        // senderId: '<value>' // Filter by senderId
        // senderName: '<value>' // Filter by senderName
        // senderAvatar: '<value>' // Filter by senderAvatar
        // messageType: '<value>' // Filter by messageType
        // content: '<value>' // Filter by content
        // timestamp: '<value>' // Filter by timestamp
        // status: '<value>' // Filter by status
            }
  });

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the gameHubMessages 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": "gameHubMessages",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"gameHubMessages": [
		{
			"id": "ID",
			"roomId": "ID",
			"senderId": "ID",
			"senderName": "String",
			"senderAvatar": "String",
			"messageType": "Enum",
			"messageType_idx": "Integer",
			"content": "Object",
			"timestamp": null,
			"status": "Enum",
			"status_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 - Get Gamehubmessage

Business API Design Specification - Get Gamehubmessage

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 getGameHubMessage 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 getGameHubMessage Business API is designed to handle a get operation on the GameHubMessage data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

Get a single gameHub hub message 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 getGameHubMessage Business API includes a REST controller that can be triggered via the following route:

/v1/v1/gameHub-messages/: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 getGameHubMessage Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The getGameHubMessage 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
gameHubMessageId ID Yes - urlpath gameHubMessageId
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 getGameHubMessage Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Select Clause

Specifies which fields will be selected from the main data object during a get or list operation. Leave blank to select all properties. This applies only to get and list type APIs.",

``

Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({$and:[{id:this.gameHubMessageId},{isActive:true}]}), {"path":"services[1].businessLogic[25].whereClause.fullWhereClause"})

Get Options

Use these options to set get specific settings.

setAsRead: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed.

No setAsread field-value pair is configured.

Business Logic Workflow

[1] Step : startBusinessApi

Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Extracts parameters from request and Redis, applies defaults, and writes them to context.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Executes parameter transformation scripts, applies type coercion, merges derived values, and reshapes inputs for downstream milestones.


[4] Step : checkParameters

Validates required and custom parameters, enforcing business-specific rules and constraints.


[5] Step : checkBasicAuth

Performs login, role, and permission checks, and applies dynamic object-level access rules.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildWhereClause

Builds the WHERE clause for fetching the object and applies additional scoped filters if configured.

You can use the following settings to change some behavior of this step. whereClause

[7] Step : mainGetOperation

Executes the database fetch, retrieves the object, and stores it in context for enrichment or further checks.

You can use the following settings to change some behavior of this step. selectClause, getOptions

[8] Step : checkInstance

Performs instance-level validations, such as ownership, existence, or access conditions.


[9] Step : buildOutput

Assembles the response from the object, applies masking, formatting, and injects additional metadata if needed.


[10] Step : sendResponse

Delivers the response to the controller for client delivery.


[11] Step : raiseApiEvent

Triggers optional API-level events after workflow completion, sending messages to integrations like Kafka if configured.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The getGameHubMessage api has got 2 regular client parameters

Parameter Type Required Population
gameHubMessageId ID true request.params?.[“gameHubMessageId”]
id String true request.params?.[“id”]

REST Request

To access the api you can use the REST controller with the path GET /v1/v1/gameHub-messages/:id

  axios({
    method: 'GET',
    url: `/v1/v1/gameHub-messages/${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 gameHubMessage 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": "gameHubMessage",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"gameHubMessage": {
		"id": "ID",
		"roomId": "ID",
		"senderId": "ID",
		"senderName": "String",
		"senderAvatar": "String",
		"messageType": "Enum",
		"messageType_idx": "Integer",
		"content": "Object",
		"timestamp": null,
		"status": "Enum",
		"status_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Business API Design Specification - Delete Gamehubmessage

Business API Design Specification - Delete Gamehubmessage

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 deleteGameHubMessage 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 deleteGameHubMessage Business API is designed to handle a delete operation on the GameHubMessage 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 gameHub hub message. Admins can delete any message; users can delete their own.

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The deleteGameHubMessage Business API includes a REST controller that can be triggered via the following route:

/v1/v1/gameHub-messages/: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 deleteGameHubMessage Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The deleteGameHubMessage 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
gameHubMessageId ID Yes - urlpath gameHubMessageId
Description: This id paremeter is used to select the required data object that will be deleted
id String Yes - urlpath id
Description: This parameter will be used to select the data object that want to 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 deleteGameHubMessage Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({$and:[{id:this.gameHubMessageId},{isActive:true}]}), {"path":"services[1].businessLogic[26].whereClause.fullWhereClause"})

Delete Options

Use these options to set delete specific settings.

useSoftDelete: If true, the record will be marked as deleted (isActive: false) instead of removed. The implementation depends on the data object’s soft delete configuration.

Business Logic Workflow

[1] Step : startBusinessApi

Manager initializes context, prepares request/session objects, and sets up internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Manager reads and normalizes parameters, applies defaults, and stores them in the context for downstream steps.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Manager executes parameter transform scripts, computes derived values, and remaps objects or arrays as needed for later processing.


[4] Step : checkParameters

Manager runs built-in validations including required field checks, type enforcement, and deletion preconditions. Stops execution if validation fails.


[5] Step : checkBasicAuth

Manager validates session, user roles, permissions, and tenant-specific access rules to enforce basic auth restrictions.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildWhereClause

Manager generates the query conditions, applies ownership and parent checks, and ensures the clause is correct for the delete operation.

You can use the following settings to change some behavior of this step. whereClause

[7] Step : fetchInstance

Manager fetches the target record, applies filters from WHERE clause, and writes the instance to the context for further checks.


[8] Step : checkInstance

Manager performs object-level validations such as lock status, soft-delete eligibility, and multi-step approval enforcement.


[9] Step : mainDeleteOperation

Manager executes the delete query, updates related indexes/caches, and handles soft/hard delete logic according to configuration.

You can use the following settings to change some behavior of this step. deleteOptions

[10] Step : buildOutput

Manager shapes the response payload, masks sensitive fields, and formats related cleanup results for output.


[11] Step : sendResponse

Manager delivers the response to the client and finalizes any temporary internal structures.


[12] Step : raiseApiEvent

Manager triggers asynchronous API events, notifies queues or streams, and performs final cleanup for the workflow.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The deleteGameHubMessage api has got 2 regular client parameters

Parameter Type Required Population
gameHubMessageId ID true request.params?.[“gameHubMessageId”]
id String true request.params?.[“id”]

REST Request

To access the api you can use the REST controller with the path DELETE /v1/v1/gameHub-messages/:id

  axios({
    method: 'DELETE',
    url: `/v1/v1/gameHub-messages/${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 gameHubMessage 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": "gameHubMessage",
	"method": "DELETE",
	"action": "delete",
	"appVersion": "Version",
	"rowCount": 1,
	"gameHubMessage": {
		"id": "ID",
		"roomId": "ID",
		"senderId": "ID",
		"senderName": "String",
		"senderAvatar": "String",
		"messageType": "Enum",
		"messageType_idx": "Integer",
		"content": "Object",
		"timestamp": null,
		"status": "Enum",
		"status_idx": "Integer",
		"isActive": false,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Business API Design Specification - Update Gamehubmessage

Business API Design Specification - Update Gamehubmessage

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 updateGameHubMessage 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 updateGameHubMessage Business API is designed to handle a update operation on the GameHubMessage data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

Update a gameHub hub message content. Only the message sender or admins can edit.

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 updateGameHubMessage Business API includes a REST controller that can be triggered via the following route:

/v1/v1/gameHub-messages/: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 updateGameHubMessage Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The updateGameHubMessage 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
gameHubMessageId ID Yes - urlpath gameHubMessageId
Description: This id paremeter is used to select the required data object that will be updated
content Object No - body content
Description: Type-specific content payload (structure depends on messageType)
status Enum No - body status
Description: Message moderation status
id String Yes - urlpath id
Description: This parameter will be used to select the data object that want 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 updateGameHubMessage Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({$and:[{id:this.gameHubMessageId},{isActive:true}]}), {"path":"services[1].businessLogic[27].whereClause.fullWhereClause"})

Data Clause

Defines custom field-value assignments used to modify or augment the default payload for create and update operations. These settings override values derived from the session or parameters if explicitly provided.", Note that a default data clause is always prepared by Mindbricks using data property settings, however any property in the data clause can be override by Data Clause Settings.

An update data clause populates all update-allowed properties of a data object, however the null properties (that are not provided by client) are ignored in db layer.

Custom Data Clause Override No custom data clause override configured

Actual Data Clause

The business api will use the following data clause. Note that any calculated value will be added to the data clause in the api manager.

{
  content: this.content ? (typeof this.content == 'string' ? JSON.parse(this.content) : this.content) : null,
  status: this.status,
}

Business Logic Workflow

[1] Step : startBusinessApi

Manager initializes context, prepares request and session objects, and sets up internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Manager reads parameters from the request or Redis, applies defaults, and writes them into context for downstream milestones.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Manager executes parameter transform scripts and derives any helper values or reshaped payloads into the context.


[4] Step : checkParameters

Manager validates required parameters, checks ID formats (UUID/ObjectId), and ensures all preconditions for update are met.


[5] Step : checkBasicAuth

Manager performs login verification, role, and permission checks, enforcing tenant and access rules before update.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildWhereClause

Manager constructs the WHERE clause used to identify the record to update, applying ownership and parent checks if necessary.

You can use the following settings to change some behavior of this step. whereClause

[7] Step : fetchInstance

Manager fetches the existing record from the database and writes it to the context for validation or enrichment.


[8] Step : checkInstance

Manager performs instance-level validations, including ownership, existence, lock status, or other pre-update checks.


[9] Step : buildDataClause

Manager prepares the data clause for the update, applying transformations or enhancements before persisting.

You can use the following settings to change some behavior of this step. dataClause

[10] Step : mainUpdateOperation

Manager executes the update operation with the WHERE and data clauses. Database-level events are raised if configured.


[11] Step : buildOutput

Manager assembles the response object from the update result, masking fields or injecting additional metadata.


[12] Step : sendResponse

Manager sends the response back to the controller for delivery to the client.


[13] Step : raiseApiEvent

Manager triggers API-level events, sending relevant messages to Kafka or other integrations if configured.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The updateGameHubMessage api has got 4 regular client parameters

Parameter Type Required Population
gameHubMessageId ID true request.params?.[“gameHubMessageId”]
content Object false request.body?.[“content”]
status Enum false request.body?.[“status”]
id String true request.params?.[“id”]

REST Request

To access the api you can use the REST controller with the path PATCH /v1/v1/gameHub-messages/:id

  axios({
    method: 'PATCH',
    url: `/v1/v1/gameHub-messages/${id}`,
    data: {
            content:"Object",  
            status:"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 gameHubMessage 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": "gameHubMessage",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"gameHubMessage": {
		"id": "ID",
		"roomId": "ID",
		"senderId": "ID",
		"senderName": "String",
		"senderAvatar": "String",
		"messageType": "Enum",
		"messageType_idx": "Integer",
		"content": "Object",
		"timestamp": null,
		"status": "Enum",
		"status_idx": "Integer",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Realtime Hubs

Realtime Hub Design Specification - gameHub

Realtime Hub Design Specification - gameHub

This document provides a detailed architectural overview of the gameHub realtime hub within the gameplay service. It covers the hub’s room management, message handling, role-based authorization, event system, and server-side logic.

Hub Overview

Description: Real-time chess game hub. Each chessGame is a room where two players exchange moves, see board state, and receive game lifecycle events (draw offer, resign, timeout, save requests). Supports both guest and registered players.

Room Settings

Rooms are backed by the chessGame DataObject. Each record in this object represents a room that users can join.

Room Eligibility

Before authorization checks, the following condition is evaluated. If it returns false, nobody can join the room:

chessGame.status == 'active' || chessGame.status == 'pending' || chessGame.status == 'paused'

Authorization Flow

The hub uses a layered authorization flow to determine each user’s role when joining a room:

  1. Absolute Roles: Users with roles administrator bypass all checks and receive the system hub role with full permissions.

  2. Auth Sources: The following DataObject-based authorization sources are checked in order. The first match determines the user’s hub role:

    1. whitePlayer
    2. blackPlayer

Hub Roles

Role Read Send Moderate Delete Any Manage Room Moderated
player Yes Yes No No No No

Message Settings

Built-in Message Types

The following message types are supported:

Cross-Cutting Features

Custom Message Types

Event Settings

Standard Events

Event Enabled Type
Typing Indicator No Ephemeral
Recording Indicator No Ephemeral
Read Receipts No Persisted
Delivery Receipts No Persisted
Presence Yes Ephemeral

Auto-Bridged DataObject Events

CRUD events from the room, membership, and message DataObjects are automatically bridged via Kafka and broadcast to connected clients. This includes events like memberJoined, messageEdited, roomUpdated, etc.

Custom Events

History Settings

Guardrails

Setting Value
Max Users Per Room 3
Max Rooms Per User 5
Message Rate Limit 120 msg/min
Max Message Size 16384 bytes
Connection Timeout 600000 ms
Auth Cache TTL 300 seconds
Global Moderation No
Default Silenced No

Server-Side Logic


This document was generated from the realtime hub configuration and should be kept in sync with design changes.


Service Library - gameplay

Service Library - gameplay

This document provides a complete reference of the custom code library for the gameplay service. It includes all library functions, edge functions with their REST endpoints, templates, and assets.

Library Functions

Library functions are reusable modules available to all business APIs and other custom code within the service via require("lib/<moduleName>").

processGameResult.js

const { interserviceCall } = require("serviceCommon");

/**
 * Mindbricks interservice calls return the same envelope as REST (e.g. { playerStats: {...} }).
 * Unwrap so we read id, eloRating, wins, etc. from the actual row.
 */
function unwrapPlayerStats(res) {
  if (res == null || typeof res !== "object") return null;
  const inner = res.playerStats;
  if (inner && typeof inner === "object" && inner.id) return inner;
  if (res.id && res.userId) return res;
  return null;
}

/**
 * Processes a completed/terminated chess game result:
 * - Computes ELO changes for both players
 * - Calls leaderboard service to update playerStats for registered (non-guest) players
 * - Calls leaderboard service to update leaderboardEntry eloRating and rank
 *
 * @param {object} context - The API context (this)
 */
module.exports = async function processGameResult(context) {
  const game = context.chessGame;
  const updatedFields = context;

  const status = updatedFields.status || game.status;
  const result = updatedFields.result || game.result;

  if (!["completed", "terminated"].includes(status) || !result) {
    return null;
  }

  if (result === "aborted") {
    return null;
  }

  const playerWhiteId = game.playerWhiteId;
  const playerBlackId = game.playerBlackId;
  const isWhiteGuest = game.guestPlayerWhite === true;
  const isBlackGuest = game.guestPlayerBlack === true;

  let whiteOutcome;
  let blackOutcome;
  if (result === "whiteWin") {
    whiteOutcome = "win";
    blackOutcome = "loss";
  } else if (result === "blackWin") {
    whiteOutcome = "loss";
    blackOutcome = "win";
  } else if (result === "draw") {
    whiteOutcome = "draw";
    blackOutcome = "draw";
  } else {
    return null;
  }

  let whiteStats = null;
  let blackStats = null;

  if (!isWhiteGuest && playerWhiteId) {
    try {
      const raw = await interserviceCall("leaderboard", "getPlayerStats", { userId: playerWhiteId });
      whiteStats = unwrapPlayerStats(raw);
    } catch (e) {
      /* player may not have stats yet */
    }
  }
  if (!isBlackGuest && playerBlackId) {
    try {
      const raw = await interserviceCall("leaderboard", "getPlayerStats", { userId: playerBlackId });
      blackStats = unwrapPlayerStats(raw);
    } catch (e) {
      /* player may not have stats yet */
    }
  }

  const whiteElo = whiteStats ? (Number(whiteStats.eloRating) || 1200) : 1200;
  const blackElo = blackStats ? (Number(blackStats.eloRating) || 1200) : 1200;

  const K = 32;
  const expectedWhite = 1 / (1 + Math.pow(10, (blackElo - whiteElo) / 400));
  const expectedBlack = 1 / (1 + Math.pow(10, (whiteElo - blackElo) / 400));

  let actualWhite;
  let actualBlack;
  if (result === "whiteWin") {
    actualWhite = 1;
    actualBlack = 0;
  } else if (result === "blackWin") {
    actualWhite = 0;
    actualBlack = 1;
  } else {
    actualWhite = 0.5;
    actualBlack = 0.5;
  }

  const newWhiteElo = Math.round(whiteElo + K * (actualWhite - expectedWhite));
  const newBlackElo = Math.round(blackElo + K * (actualBlack - expectedBlack));

  const now = new Date().toISOString();

  function buildUpdatePayload(stats, outcome, newElo) {
    const wins = (stats ? stats.wins : 0) + (outcome === "win" ? 1 : 0);
    const losses = (stats ? stats.losses : 0) + (outcome === "loss" ? 1 : 0);
    const draws = (stats ? stats.draws : 0) + (outcome === "draw" ? 1 : 0);
    const totalGames = wins + losses + draws;
    let streak = stats ? stats.streak : 0;
    if (outcome === "win") streak = streak > 0 ? streak + 1 : 1;
    else if (outcome === "loss") streak = streak < 0 ? streak - 1 : -1;
    else streak = 0;
    return { eloRating: newElo, totalGames, wins, losses, draws, streak, lastGameAt: now };
  }

  if (!isWhiteGuest && playerWhiteId && whiteStats) {
    try {
      const payload = buildUpdatePayload(whiteStats, whiteOutcome, newWhiteElo);
      await interserviceCall("leaderboard", "updatePlayerStats", { id: whiteStats.id, ...payload });
    } catch (e) {
      console.error("Failed to update white player stats:", e.message);
    }
  }

  if (!isBlackGuest && playerBlackId && blackStats) {
    try {
      const payload = buildUpdatePayload(blackStats, blackOutcome, newBlackElo);
      await interserviceCall("leaderboard", "updatePlayerStats", { id: blackStats.id, ...payload });
    } catch (e) {
      console.error("Failed to update black player stats:", e.message);
    }
  }

  return { whiteElo: newWhiteElo, blackElo: newBlackElo, result };
};

This document was generated from the service library configuration and should be kept in sync with design changes.


LobbyChat Service

Service Design Specification

Service Design Specification

wechess-lobbychat-service documentation Version: 1.0.24

Scope

This document provides a structured architectural overview of the lobbyChat 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.

LobbyChat Service Settings

Public lobby chat microservice. Manages create, list, reporting, moderation, and 24-hour message expiry for guest/registered users.

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 wechess-lobbychat-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 wechess-lobbychat-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
lobbyMessage A single lobby/public chat message between any logged-in user (guest, registered, admin). Ephemeral (24h retention), with reporting and moderation support. Muting is tracked by senderId+mutedUntil for punishment management. accessProtected
lobbyRoom Daily lobby chat room. One record per day (roomId format: lobby-YYYY-MM-DD). Older rooms kept as history. accessProtected
lobbyChatHubMessage Auto-generated message DataObject for the lobbyChatHub RealtimeHub. Stores all messages with typed content payloads. accessPrivate
lobbyChatHubModeration Auto-generated moderation DataObject for the lobbyChatHub RealtimeHub. Stores block and silence actions for room-level user moderation. accessPrivate

lobbyMessage Data Object

Object Overview

Description: A single lobby/public chat message between any logged-in user (guest, registered, admin). Ephemeral (24h retention), with reporting and moderation support. Muting is tracked by senderId+mutedUntil for punishment 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

Properties Schema

Property Type Required Description
senderId ID Yes User ID (guest or registered) who sent the message. References auth:user.id.
senderDisplayName String Yes Display name (from user fullname at send time; allows historical display even if name changes).
content String Yes Chat message body (limited at UI, backend-enforces not empty; max 500 chars).
sentAt Date Yes UTC timestamp when message was sent. Used to enforce 24h retention and sorting.
reportStatus Enum Yes Moderation/report workflow state: none (default), reported (user), underReview (admin).
mutedUntil Date No If set, the message sender is muted in the lobby until this timestamp. Only admins may set. Used with senderId for lookup on enforcement.
removed Boolean Yes If true, message is hidden/removed by admin moderation (soft-remove).
roomId String Yes Daily room identifier (lobby-YYYY-MM-DD). Scopes message to that day.

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

senderId senderDisplayName content 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

reportStatus mutedUntil removed roomId

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

senderId senderDisplayName content sentAt reportStatus mutedUntil removed roomId

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

senderId roomId

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

roomId

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

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

Filter Properties

senderId reportStatus removed

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.

lobbyRoom Data Object

Object Overview

Description: Daily lobby chat room. One record per day (roomId format: lobby-YYYY-MM-DD). Older rooms kept as history.

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
roomId String Yes Room identifier, e.g. lobby-2026-03-10

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

roomId

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

roomId

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

roomId

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

roomId

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.

lobbyChatHubMessage Data Object

Object Overview

Description: Auto-generated message DataObject for the lobbyChatHub RealtimeHub. Stores all messages with typed content payloads.

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
roomId ID Yes Reference to the room this message belongs to
senderId ID No Reference to the user who sent this message
senderName String No Display name of the sender (denormalized from user profile at send time)
senderAvatar String No Avatar URL of the sender (denormalized from user profile at send time)
messageType Enum Yes Content type discriminator for this message
content Object Yes Type-specific content payload (structure depends on messageType)
timestamp No Message creation time
status Enum No Message moderation status
reaction Object No Emoji reactions [{ emoji, userId, timestamp }]

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

roomId senderId senderName senderAvatar messageType timestamp

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

roomId senderId senderName senderAvatar messageType content timestamp status reaction

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

roomId senderId senderName senderAvatar messageType content timestamp status reaction

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

roomId senderId senderName senderAvatar messageType content timestamp status reaction

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

roomId

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

senderId

Session data properties are used to store data that is specific to the user session, allowing for personalized experiences and temporary data storage. If a property is configured as session data, it will be automatically mapped to the related field in the user session during CRUD operations. Note that session data properties can not be mutated by the user, but only by the system.

Filter Properties

roomId senderId senderName senderAvatar messageType content timestamp status reaction

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.

lobbyChatHubModeration Data Object

Object Overview

Description: Auto-generated moderation DataObject for the lobbyChatHub RealtimeHub. Stores block and silence actions for room-level user moderation.

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
roomId ID Yes Reference to the room where the moderation action applies
userId ID Yes The user who is blocked or silenced
action Enum Yes Moderation action type
reason Text No Optional reason for the moderation action
duration Integer No Duration in seconds. 0 means permanent
expiresAt No Expiry timestamp. Null means permanent
issuedBy ID No The moderator who issued the action

Default Values

Default values are automatically assigned to properties when a new object is created, if no value is provided in the request body. Since default values are applied on db level, they should be literal values, not expressions.If you want to use expressions, you can use transposed parameters in any business API to set default values dynamically.

Constant Properties

roomId userId action duration expiresAt issuedBy

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

roomId userId action reason duration expiresAt issuedBy

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

roomId userId action reason duration expiresAt issuedBy

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

roomId userId action reason duration expiresAt issuedBy

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

roomId userId

Secondary key properties are used to create an additional indexed identifiers for the data object, allowing for alternative access patterns. Different than normal indexed properties, secondary keys will act as primary keys and Mindbricks will provide automatic secondary key db utility functions to access the data object by the secondary key.

Relation Properties

roomId

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

issuedBy

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

roomId userId action reason duration expiresAt issuedBy

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

lobbyChat has got 10 Business APIs to manage its internal and crud logic. For the details of each business API refer to its chapter.

Realtime Hubs

lobbyChat has 1 Realtime Hub configured. Each hub provides bidirectional communication powered by Socket.IO with room-based messaging, built-in and custom message types, and auto-generated REST endpoints.

Hub Name Namespace Room DataObject Roles
lobbyChatHub /hub/lobbyChatHub lobbyRoom lobbyUser, moderator

For detailed documentation on each hub, refer to:

Edge Controllers

purgeExpiredLobbyMessages

Configuration:

REST Settings:


Service Library

Functions

lobbyChatValidateMuteAndContent.js

module.exports = async function lobbyChatValidateMuteAndContent(context) {
  // context.session.userId is the sender
  const senderId = context.session.userId;
  if (!senderId) throw new Error('You must be logged in to send messages.');

  // Collect active mute(s) for this sender (any lobbyMessage with mutedUntil > now for this sender)
  const { getLobbyMessageListByQuery } = require("dbLayer");
  const now = new Date();
  const mutedMsgs = await getLobbyMessageListByQuery({ senderId, mutedUntil: { $notnull: true } });
  if (mutedMsgs && mutedMsgs.length > 0) {
    // Muted if *any* applicable unexpired mute exists
    const isMuted = mutedMsgs.some(msg => msg.mutedUntil && new Date(msg.mutedUntil) > now);
    if (isMuted) throw new Error('You are currently muted and cannot send lobby messages.');
  }
  // Content validation
  const body = context.content ?? context.request?.body?.content;
  if (!body || typeof body !== 'string' || !body.trim()) {
    throw new Error('Message content cannot be empty.');
  }
  if (body.length > 500) {
    throw new Error('Message content exceeds 500 character limit.');
  }
  // Attach displayName
  context.senderDisplayName = context.session.fullname || 'Anonymous';
  return true;
}

lobbyChatValidateModerationUpdate.js

module.exports = function lobbyChatValidateModerationUpdate(context) {
  // Only allowed to update: removed, mutedUntil, reportStatus (never content, senderDisplayName)
  const allowed = ['removed','mutedUntil','reportStatus'];
  const updating = Object.keys(context.updateData || {});
  if (updating.some(f => !allowed.includes(f))) {
    throw new Error('Only moderation fields may be changed: removed, mutedUntil, reportStatus.');
  }
  return true;
}

Edge Functions

purgeExpiredLobbyMessages.js

module.exports = async () => {
  // Physically remove all messages older than 24h
  const { deleteLobbyMessageByQuery } = require("dbLayer");
  const cutoff = new Date(Date.now() - 24*60*60*1000);
  const where = { sentAt: { $lt: cutoff.toISOString() } };
  const deleted = await deleteLobbyMessageByQuery(where);
  return { status: 200, deletedCount: deleted.length, cutoff: cutoff.toISOString() };
}

This document was generated from the service architecture definition and should be kept in sync with implementation changes.


REST API GUIDE

REST API GUIDE

wechess-lobbychat-service

Version: 1.0.24

Public lobby chat microservice. Manages create, list, reporting, moderation, and 24-hour message expiry for guest/registered users.

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 LobbyChat Service’s REST API. This document is designed to provide a comprehensive guide to interfacing with our LobbyChat Service exclusively through RESTful API endpoints.

Intended Audience

This documentation is intended for developers and integrators who are looking to interact with the LobbyChat Service via HTTP requests for purposes such as creating, updating, deleting and querying LobbyChat 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 LobbyChat 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 LobbyChat 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 wechess-access-token
Cookie wechess-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 LobbyChat 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 LobbyChat 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 LobbyChat 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 LobbyChat 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 LobbyChat 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 LobbyChat 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

LobbyChat 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.

LobbyMessage resource

Resource Definition : A single lobby/public chat message between any logged-in user (guest, registered, admin). Ephemeral (24h retention), with reporting and moderation support. Muting is tracked by senderId+mutedUntil for punishment management. LobbyMessage Resource Properties

Name Type Required Default Definition
senderId ID User ID (guest or registered) who sent the message. References auth:user.id.
senderDisplayName String Display name (from user fullname at send time; allows historical display even if name changes).
content String Chat message body (limited at UI, backend-enforces not empty; max 500 chars).
sentAt Date UTC timestamp when message was sent. Used to enforce 24h retention and sorting.
reportStatus Enum Moderation/report workflow state: none (default), reported (user), underReview (admin).
mutedUntil Date If set, the message sender is muted in the lobby until this timestamp. Only admins may set. Used with senderId for lookup on enforcement.
removed Boolean If true, message is hidden/removed by admin moderation (soft-remove).
roomId String Daily room identifier (lobby-YYYY-MM-DD). Scopes message to that day.

Enum Properties

Enum properties are represented as strings in the database. The values are mapped to their corresponding names in the application layer.

reportStatus Enum Property

Property Definition : Moderation/report workflow state: none (default), reported (user), underReview (admin).Enum Options

Name Value Index
none "none"" 0
reported "reported"" 1
underReview "underReview"" 2

LobbyRoom resource

Resource Definition : Daily lobby chat room. One record per day (roomId format: lobby-YYYY-MM-DD). Older rooms kept as history. LobbyRoom Resource Properties

Name Type Required Default Definition
roomId String Room identifier, e.g. lobby-2026-03-10

LobbyChatHubMessage resource

Resource Definition : Auto-generated message DataObject for the lobbyChatHub RealtimeHub. Stores all messages with typed content payloads. LobbyChatHubMessage Resource Properties

Name Type Required Default Definition
roomId ID Reference to the room this message belongs to
senderId ID Reference to the user who sent this message
senderName String Display name of the sender (denormalized from user profile at send time)
senderAvatar String Avatar URL of the sender (denormalized from user profile at send time)
messageType Enum Content type discriminator for this message
content Object Type-specific content payload (structure depends on messageType)
timestamp Message creation time
status Enum Message moderation status
reaction Object Emoji reactions [{ emoji, userId, timestamp }]

Enum Properties

Enum properties are represented as strings in the database. The values are mapped to their corresponding names in the application layer.

messageType Enum Property

Property Definition : Content type discriminator for this messageEnum Options

Name Value Index
text "text"" 0
system "system"" 1
status Enum Property

Property Definition : Message moderation statusEnum Options

Name Value Index
pending "pending"" 0
approved "approved"" 1
rejected "rejected"" 2

LobbyChatHubModeration resource

Resource Definition : Auto-generated moderation DataObject for the lobbyChatHub RealtimeHub. Stores block and silence actions for room-level user moderation. LobbyChatHubModeration Resource Properties

Name Type Required Default Definition
roomId ID Reference to the room where the moderation action applies
userId ID The user who is blocked or silenced
action Enum Moderation action type
reason Text Optional reason for the moderation action
duration Integer Duration in seconds. 0 means permanent
expiresAt Expiry timestamp. Null means permanent
issuedBy ID The moderator who issued the action

Enum Properties

Enum properties are represented as strings in the database. The values are mapped to their corresponding names in the application layer.

action Enum Property

Property Definition : Moderation action typeEnum Options

Name Value Index
blocked "blocked"" 0
silenced "silenced"" 1

Business Api

Create Lobbymessage API

[Default create API] — This is the designated default create API for the lobbyMessage data object. Frontend generators and AI agents should use this API for standard CRUD operations. Post a new lobby chat message. Enforces mute (mutedUntil > now), ensures message is not empty and under 500 chars. SenderId and senderDisplayName are populated from session.

API Frontend Description By The Backend Architect

Rest Route

The createLobbyMessage API REST controller can be triggered via the following route:

/v1/lobbymessages

Rest Request Parameters

The createLobbyMessage api has got 8 regular request parameters

Parameter Type Required Population
senderId ID true request.body?.[“senderId”]
senderDisplayName String true request.body?.[“senderDisplayName”]
content String true request.body?.[“content”]
sentAt Date true request.body?.[“sentAt”]
reportStatus Enum true request.body?.[“reportStatus”]
mutedUntil Date false request.body?.[“mutedUntil”]
removed Boolean true request.body?.[“removed”]
roomId String true request.body?.[“roomId”]
senderId : User ID (guest or registered) who sent the message. References auth:user.id.
senderDisplayName : Display name (from user fullname at send time; allows historical display even if name changes).
content : Chat message body (limited at UI, backend-enforces not empty; max 500 chars).
sentAt : UTC timestamp when message was sent. Used to enforce 24h retention and sorting.
reportStatus : Moderation/report workflow state: none (default), reported (user), underReview (admin).
mutedUntil : If set, the message sender is muted in the lobby until this timestamp. Only admins may set. Used with senderId for lookup on enforcement.
removed : If true, message is hidden/removed by admin moderation (soft-remove).
roomId : Daily room identifier (lobby-YYYY-MM-DD). Scopes message to that day.

REST Request To access the api you can use the REST controller with the path POST /v1/lobbymessages

  axios({
    method: 'POST',
    url: '/v1/lobbymessages',
    data: {
            senderId:"ID",  
            senderDisplayName:"String",  
            content:"String",  
            sentAt:"Date",  
            reportStatus:"Enum",  
            mutedUntil:"Date",  
            removed:"Boolean",  
            roomId:"String",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "lobbyMessage",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"lobbyMessage": {
		"id": "ID",
		"senderId": "ID",
		"senderDisplayName": "String",
		"content": "String",
		"sentAt": "Date",
		"reportStatus": "Enum",
		"reportStatus_idx": "Integer",
		"mutedUntil": "Date",
		"removed": "Boolean",
		"roomId": "String",
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"isActive": true
	}
}

List Lobbymessages API

[Default list API] — This is the designated default list API for the lobbyMessage data object. Frontend generators and AI agents should use this API for standard CRUD operations. Fetch latest lobby chat messages from the last 24 hours (not removed). Sorted sentAt desc. Paginated by default (50 per page).

API Frontend Description By The Backend Architect

Rest Route

The listLobbyMessages API REST controller can be triggered via the following route:

/v1/listlobbymessages/:roomId

Rest Request Parameters

The listLobbyMessages api has got 1 regular request parameter

Parameter Type Required Population
roomId String true request.params?.[“roomId”]
roomId : Daily room identifier (lobby-YYYY-MM-DD). Scopes message to that day… The parameter is used to query data.

REST Request To access the api you can use the REST controller with the path GET /v1/listlobbymessages/:roomId

  axios({
    method: 'GET',
    url: `/v1/listlobbymessages/${roomId}`,
    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": "lobbyMessages",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"lobbyMessages": [
		{
			"isActive": true
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Update Lobbymessagemoderation API

[Default update API] — This is the designated default update API for the lobbyMessage data object. Frontend generators and AI agents should use this API for standard CRUD operations. Update message for moderation: only admins may set removed (true), mutedUntil, or set reportStatus to underReview. All users may set reportStatus to reported on a message they wish to report. Message owner may not update content or displayName.

API Frontend Description By The Backend Architect

Rest Route

The updateLobbyMessageModeration API REST controller can be triggered via the following route:

/v1/lobbymessagemoderation/:lobbyMessageId

Rest Request Parameters

The updateLobbyMessageModeration api has got 5 regular request parameters

Parameter Type Required Population
lobbyMessageId ID true request.params?.[“lobbyMessageId”]
reportStatus Enum false request.body?.[“reportStatus”]
mutedUntil Date false request.body?.[“mutedUntil”]
removed Boolean false request.body?.[“removed”]
roomId String false request.body?.[“roomId”]
lobbyMessageId : This id paremeter is used to select the required data object that will be updated
reportStatus : Moderation/report workflow state: none (default), reported (user), underReview (admin).
mutedUntil : If set, the message sender is muted in the lobby until this timestamp. Only admins may set. Used with senderId for lookup on enforcement.
removed : If true, message is hidden/removed by admin moderation (soft-remove).
roomId : Daily room identifier (lobby-YYYY-MM-DD). Scopes message to that day.

REST Request To access the api you can use the REST controller with the path PATCH /v1/lobbymessagemoderation/:lobbyMessageId

  axios({
    method: 'PATCH',
    url: `/v1/lobbymessagemoderation/${lobbyMessageId}`,
    data: {
            reportStatus:"Enum",  
            mutedUntil:"Date",  
            removed:"Boolean",  
            roomId:"String",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "lobbyMessage",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"lobbyMessage": {
		"id": "ID",
		"senderId": "ID",
		"senderDisplayName": "String",
		"content": "String",
		"sentAt": "Date",
		"reportStatus": "Enum",
		"reportStatus_idx": "Integer",
		"mutedUntil": "Date",
		"removed": "Boolean",
		"roomId": "String",
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"isActive": true
	}
}

Delete Lobbymessage API

[Default delete API] — This is the designated default delete API for the lobbyMessage data object. Frontend generators and AI agents should use this API for standard CRUD operations. Physical delete of a lobby message (should only be possible for admin batch/cleanup or hard moderation). In practice, most moderation is via removed:true.

API Frontend Description By The Backend Architect

Rest Route

The deleteLobbyMessage API REST controller can be triggered via the following route:

/v1/lobbymessages/:lobbyMessageId

Rest Request Parameters

The deleteLobbyMessage api has got 1 regular request parameter

Parameter Type Required Population
lobbyMessageId ID true request.params?.[“lobbyMessageId”]
lobbyMessageId : 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/lobbymessages/:lobbyMessageId

  axios({
    method: 'DELETE',
    url: `/v1/lobbymessages/${lobbyMessageId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "lobbyMessage",
	"method": "DELETE",
	"action": "delete",
	"appVersion": "Version",
	"rowCount": 1,
	"lobbyMessage": {
		"id": "ID",
		"senderId": "ID",
		"senderDisplayName": "String",
		"content": "String",
		"sentAt": "Date",
		"reportStatus": "Enum",
		"reportStatus_idx": "Integer",
		"mutedUntil": "Date",
		"removed": "Boolean",
		"roomId": "String",
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"isActive": false
	}
}

Ensure Lobbyroom API

Rest Route

The ensureLobbyRoom API REST controller can be triggered via the following route:

/v1/ensurelobbyroom

Rest Request Parameters

The ensureLobbyRoom api has got 1 regular request parameter

Parameter Type Required Population
roomId String true request.body?.[“roomId”]
roomId : Room identifier, e.g. lobby-2026-03-10

REST Request To access the api you can use the REST controller with the path POST /v1/ensurelobbyroom

  axios({
    method: 'POST',
    url: '/v1/ensurelobbyroom',
    data: {
            roomId:"String",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "lobbyRoom",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"lobbyRoom": {
		"id": "ID",
		"roomId": "String",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

List Lobbyrooms API

Rest Route

The listLobbyRooms API REST controller can be triggered via the following route:

/v1/listlobbyrooms/:roomId

Rest Request Parameters

The listLobbyRooms api has got 1 regular request parameter

Parameter Type Required Population
roomId String true request.params?.[“roomId”]
roomId : Room identifier, e.g. lobby-2026-03-10. The parameter is used to query data.

REST Request To access the api you can use the REST controller with the path GET /v1/listlobbyrooms/:roomId

  axios({
    method: 'GET',
    url: `/v1/listlobbyrooms/${roomId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "lobbyRooms",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"lobbyRooms": [
		{
			"id": "ID",
			"roomId": "String",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID"
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

List Lobbychathubmessages API

[Default list API] — This is the designated default list API for the lobbyChatHubMessage data object. Frontend generators and AI agents should use this API for standard CRUD operations. List messages in a lobbyChatHub hub room. Accessible by admins and room participants.

Rest Route

The listLobbyChatHubMessages API REST controller can be triggered via the following route:

/v1/v1/lobbyChatHub-messages

Rest Request Parameters

Filter Parameters

The listLobbyChatHubMessages api supports 9 optional filter parameters for filtering list results:

roomId (ID): Reference to the room this message belongs to

senderId (ID): Reference to the user who sent this message

senderName (String): Display name of the sender (denormalized from user profile at send time)

senderAvatar (String): Avatar URL of the sender (denormalized from user profile at send time)

messageType (Enum): Content type discriminator for this message

content (Object): Type-specific content payload (structure depends on messageType)

timestamp (String): Message creation time

status (Enum): Message moderation status

reaction (Object): Emoji reactions [{ emoji, userId, timestamp }]

REST Request To access the api you can use the REST controller with the path GET /v1/v1/lobbyChatHub-messages

  axios({
    method: 'GET',
    url: '/v1/v1/lobbyChatHub-messages',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section above)
        // roomId: '<value>' // Filter by roomId
        // senderId: '<value>' // Filter by senderId
        // senderName: '<value>' // Filter by senderName
        // senderAvatar: '<value>' // Filter by senderAvatar
        // messageType: '<value>' // Filter by messageType
        // content: '<value>' // Filter by content
        // timestamp: '<value>' // Filter by timestamp
        // status: '<value>' // Filter by status
        // reaction: '<value>' // Filter by reaction
            }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "lobbyChatHubMessages",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"lobbyChatHubMessages": [
		{
			"id": "ID",
			"roomId": "ID",
			"senderId": "ID",
			"senderName": "String",
			"senderAvatar": "String",
			"messageType": "Enum",
			"messageType_idx": "Integer",
			"content": "Object",
			"timestamp": null,
			"status": "Enum",
			"status_idx": "Integer",
			"reaction": "Object",
			"isActive": true,
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID"
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Get Lobbychathubmessage API

[Default get API] — This is the designated default get API for the lobbyChatHubMessage data object. Frontend generators and AI agents should use this API for standard CRUD operations. Get a single lobbyChatHub hub message by ID.

Rest Route

The getLobbyChatHubMessage API REST controller can be triggered via the following route:

/v1/v1/lobbyChatHub-messages/:id

Rest Request Parameters

The getLobbyChatHubMessage api has got 2 regular request parameters

Parameter Type Required Population
lobbyChatHubMessageId ID true request.params?.[“lobbyChatHubMessageId”]
id String true request.params?.[“id”]
lobbyChatHubMessageId : 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/v1/lobbyChatHub-messages/:id

  axios({
    method: 'GET',
    url: `/v1/v1/lobbyChatHub-messages/${id}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "lobbyChatHubMessage",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"lobbyChatHubMessage": {
		"id": "ID",
		"roomId": "ID",
		"senderId": "ID",
		"senderName": "String",
		"senderAvatar": "String",
		"messageType": "Enum",
		"messageType_idx": "Integer",
		"content": "Object",
		"timestamp": null,
		"status": "Enum",
		"status_idx": "Integer",
		"reaction": "Object",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Delete Lobbychathubmessage API

[Default delete API] — This is the designated default delete API for the lobbyChatHubMessage data object. Frontend generators and AI agents should use this API for standard CRUD operations. Delete a lobbyChatHub hub message. Admins can delete any message; users can delete their own.

Rest Route

The deleteLobbyChatHubMessage API REST controller can be triggered via the following route:

/v1/v1/lobbyChatHub-messages/:id

Rest Request Parameters

The deleteLobbyChatHubMessage api has got 2 regular request parameters

Parameter Type Required Population
lobbyChatHubMessageId ID true request.params?.[“lobbyChatHubMessageId”]
id String true request.params?.[“id”]
lobbyChatHubMessageId : This id paremeter is used to select the required data object that will be deleted
id : This parameter will be used to select the data object that want to be deleted

REST Request To access the api you can use the REST controller with the path DELETE /v1/v1/lobbyChatHub-messages/:id

  axios({
    method: 'DELETE',
    url: `/v1/v1/lobbyChatHub-messages/${id}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "lobbyChatHubMessage",
	"method": "DELETE",
	"action": "delete",
	"appVersion": "Version",
	"rowCount": 1,
	"lobbyChatHubMessage": {
		"id": "ID",
		"roomId": "ID",
		"senderId": "ID",
		"senderName": "String",
		"senderAvatar": "String",
		"messageType": "Enum",
		"messageType_idx": "Integer",
		"content": "Object",
		"timestamp": null,
		"status": "Enum",
		"status_idx": "Integer",
		"reaction": "Object",
		"isActive": false,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Update Lobbychathubmessage API

[Default update API] — This is the designated default update API for the lobbyChatHubMessage data object. Frontend generators and AI agents should use this API for standard CRUD operations. Update a lobbyChatHub hub message content. Only the message sender or admins can edit.

Rest Route

The updateLobbyChatHubMessage API REST controller can be triggered via the following route:

/v1/v1/lobbyChatHub-messages/:id

Rest Request Parameters

The updateLobbyChatHubMessage api has got 5 regular request parameters

Parameter Type Required Population
lobbyChatHubMessageId ID true request.params?.[“lobbyChatHubMessageId”]
content Object false request.body?.[“content”]
status Enum false request.body?.[“status”]
reaction Object false request.body?.[“reaction”]
id String true request.params?.[“id”]
lobbyChatHubMessageId : This id paremeter is used to select the required data object that will be updated
content : Type-specific content payload (structure depends on messageType)
status : Message moderation status
reaction : Emoji reactions [{ emoji, userId, timestamp }]
id : This parameter will be used to select the data object that want to be updated

REST Request To access the api you can use the REST controller with the path PATCH /v1/v1/lobbyChatHub-messages/:id

  axios({
    method: 'PATCH',
    url: `/v1/v1/lobbyChatHub-messages/${id}`,
    data: {
            content:"Object",  
            status:"Enum",  
            reaction:"Object",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "lobbyChatHubMessage",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"lobbyChatHubMessage": {
		"id": "ID",
		"roomId": "ID",
		"senderId": "ID",
		"senderName": "String",
		"senderAvatar": "String",
		"messageType": "Enum",
		"messageType_idx": "Integer",
		"content": "Object",
		"timestamp": null,
		"status": "Enum",
		"status_idx": "Integer",
		"reaction": "Object",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Authentication Specific Routes

Common Routes

Route: currentuser

Route Definition: Retrieves the currently authenticated user’s session information.

Route Type: sessionInfo

Access Route: GET /currentuser

Parameters

This route does not require any request parameters.

Behavior

// Sample GET /currentuser call
axios.get("/currentuser", {
  headers: {
    "Authorization": "Bearer your-jwt-token"
  }
});

Success Response Returns the session object, including user-related data and token information.

{
  "sessionId": "9cf23fa8-07d4-4e7c-80a6-ec6d6ac96bb9",
  "userId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38",
  "email": "user@example.com",
  "fullname": "John Doe",
  "roleId": "user",
  "tenantId": "abc123",
  "accessToken": "jwt-token-string",
  ...
}

Error Response 401 Unauthorized: No active session found.

{
  "status": "ERR",
  "message": "No login found"
}

Notes

Route: permissions

*Route Definition*: Retrieves all effective permission records assigned to the currently authenticated user.

*Route Type*: permissionFetch

Access Route: GET /permissions

Parameters

This route does not require any request parameters.

Behavior

// Sample GET /permissions call
axios.get("/permissions", {
  headers: {
    "Authorization": "Bearer your-jwt-token"
  }
});

Success Response

Returns an array of permission objects.

[
  {
    "id": "perm1",
    "permissionName": "adminPanel.access",
    "roleId": "admin",
    "subjectUserId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38",
    "subjectUserGroupId": null,
    "objectId": null,
    "canDo": true,
    "tenantCodename": "store123"
  },
  {
    "id": "perm2",
    "permissionName": "orders.manage",
    "roleId": null,
    "subjectUserId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38",
    "subjectUserGroupId": null,
    "objectId": null,
    "canDo": true,
    "tenantCodename": "store123"
  }
]

Each object reflects a single permission grant, aligned with the givenPermissions model:

Error Responses

{
  "status": "ERR",
  "message": "No login found"
}

Notes

Tip: Applications can cache permission results client-side or server-side, but should occasionally refresh by calling this endpoint, especially after login or permission-changing operations.

Route: permissions/:permissionName

Route Definition: Checks whether the current user has access to a specific permission, and provides a list of scoped object exceptions or inclusions.

Route Type: permissionScopeCheck

Access Route: GET /permissions/:permissionName

Parameters

Parameter Type Required Population
permissionName String Yes request.params.permissionName

Behavior

// Sample GET /permissions/orders.manage
axios.get("/permissions/orders.manage", {
  headers: {
    "Authorization": "Bearer your-jwt-token"
  }
});

Success Response

{
  "canDo": true,
  "exceptions": [
    "a1f2e3d4-xxxx-yyyy-zzzz-object1",
    "b2c3d4e5-xxxx-yyyy-zzzz-object2"
  ]
}

Copyright

All sources, documents and other digital materials are copyright of .

About Us

For more information please visit our website: .

. .


EVENT GUIDE

EVENT GUIDE

wechess-lobbychat-service

Public lobby chat microservice. Manages create, list, reporting, moderation, and 24-hour message expiry for guest/registered users.

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 LobbyChat Service Event descriptions. This guide is dedicated to detailing how to subscribe to and listen for state changes within the LobbyChat Service, offering an exclusive focus on event subscription mechanisms.

Intended Audience

This documentation is aimed at developers and integrators looking to monitor LobbyChat Service state changes. It is especially relevant for those wishing to implement or enhance business logic based on interactions with LobbyChat 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 LobbyChat 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 lobbyMessage-created

Event topic: wechess-lobbychat-service-dbevent-lobbymessage-created

This event is triggered upon the creation of a lobbyMessage data object in the database. The event payload encompasses the newly created data, encapsulated within the root of the paylod.

Event payload:

{"id":"ID","senderId":"ID","senderDisplayName":"String","content":"String","sentAt":"Date","reportStatus":"Enum","reportStatus_idx":"Integer","mutedUntil":"Date","removed":"Boolean","roomId":"String","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

DbEvent lobbyMessage-updated

Event topic: wechess-lobbychat-service-dbevent-lobbymessage-updated

Activation of this event follows the update of a lobbyMessage data object. The payload contains the updated information under the lobbyMessage attribute, along with the original data prior to update, labeled as old_lobbyMessage and also you can find the old and new versions of updated-only portion of the data…

Event payload:

{
old_lobbyMessage:{"id":"ID","senderId":"ID","senderDisplayName":"String","content":"String","sentAt":"Date","reportStatus":"Enum","reportStatus_idx":"Integer","mutedUntil":"Date","removed":"Boolean","roomId":"String","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},
lobbyMessage:{"id":"ID","senderId":"ID","senderDisplayName":"String","content":"String","sentAt":"Date","reportStatus":"Enum","reportStatus_idx":"Integer","mutedUntil":"Date","removed":"Boolean","roomId":"String","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},
oldDataValues,
newDataValues
}

DbEvent lobbyMessage-deleted

Event topic: wechess-lobbychat-service-dbevent-lobbymessage-deleted

This event announces the deletion of a lobbyMessage 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","senderId":"ID","senderDisplayName":"String","content":"String","sentAt":"Date","reportStatus":"Enum","reportStatus_idx":"Integer","mutedUntil":"Date","removed":"Boolean","roomId":"String","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":false}

DbEvent lobbyRoom-created

Event topic: wechess-lobbychat-service-dbevent-lobbyroom-created

This event is triggered upon the creation of a lobbyRoom data object in the database. The event payload encompasses the newly created data, encapsulated within the root of the paylod.

Event payload:

{"id":"ID","roomId":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

DbEvent lobbyRoom-updated

Event topic: wechess-lobbychat-service-dbevent-lobbyroom-updated

Activation of this event follows the update of a lobbyRoom data object. The payload contains the updated information under the lobbyRoom attribute, along with the original data prior to update, labeled as old_lobbyRoom and also you can find the old and new versions of updated-only portion of the data…

Event payload:

{
old_lobbyRoom:{"id":"ID","roomId":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},
lobbyRoom:{"id":"ID","roomId":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},
oldDataValues,
newDataValues
}

DbEvent lobbyRoom-deleted

Event topic: wechess-lobbychat-service-dbevent-lobbyroom-deleted

This event announces the deletion of a lobbyRoom 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","roomId":"String","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

DbEvent lobbyChatHubMessage-created

Event topic: wechess-lobbychat-service-dbevent-lobbychathubmessage-created

This event is triggered upon the creation of a lobbyChatHubMessage data object in the database. The event payload encompasses the newly created data, encapsulated within the root of the paylod.

Event payload:

{"id":"ID","roomId":"ID","senderId":"ID","senderName":"String","senderAvatar":"String","messageType":"Enum","messageType_idx":"Integer","content":"Object","timestamp":null,"status":"Enum","status_idx":"Integer","reaction":"Object","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

DbEvent lobbyChatHubMessage-updated

Event topic: wechess-lobbychat-service-dbevent-lobbychathubmessage-updated

Activation of this event follows the update of a lobbyChatHubMessage data object. The payload contains the updated information under the lobbyChatHubMessage attribute, along with the original data prior to update, labeled as old_lobbyChatHubMessage and also you can find the old and new versions of updated-only portion of the data…

Event payload:

{
old_lobbyChatHubMessage:{"id":"ID","roomId":"ID","senderId":"ID","senderName":"String","senderAvatar":"String","messageType":"Enum","messageType_idx":"Integer","content":"Object","timestamp":null,"status":"Enum","status_idx":"Integer","reaction":"Object","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},
lobbyChatHubMessage:{"id":"ID","roomId":"ID","senderId":"ID","senderName":"String","senderAvatar":"String","messageType":"Enum","messageType_idx":"Integer","content":"Object","timestamp":null,"status":"Enum","status_idx":"Integer","reaction":"Object","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},
oldDataValues,
newDataValues
}

DbEvent lobbyChatHubMessage-deleted

Event topic: wechess-lobbychat-service-dbevent-lobbychathubmessage-deleted

This event announces the deletion of a lobbyChatHubMessage 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","roomId":"ID","senderId":"ID","senderName":"String","senderAvatar":"String","messageType":"Enum","messageType_idx":"Integer","content":"Object","timestamp":null,"status":"Enum","status_idx":"Integer","reaction":"Object","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

DbEvent lobbyChatHubModeration-created

Event topic: wechess-lobbychat-service-dbevent-lobbychathubmoderation-created

This event is triggered upon the creation of a lobbyChatHubModeration data object in the database. The event payload encompasses the newly created data, encapsulated within the root of the paylod.

Event payload:

{"id":"ID","roomId":"ID","userId":"ID","action":"Enum","action_idx":"Integer","reason":"Text","duration":"Integer","expiresAt":null,"issuedBy":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

DbEvent lobbyChatHubModeration-updated

Event topic: wechess-lobbychat-service-dbevent-lobbychathubmoderation-updated

Activation of this event follows the update of a lobbyChatHubModeration data object. The payload contains the updated information under the lobbyChatHubModeration attribute, along with the original data prior to update, labeled as old_lobbyChatHubModeration and also you can find the old and new versions of updated-only portion of the data…

Event payload:

{
old_lobbyChatHubModeration:{"id":"ID","roomId":"ID","userId":"ID","action":"Enum","action_idx":"Integer","reason":"Text","duration":"Integer","expiresAt":null,"issuedBy":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},
lobbyChatHubModeration:{"id":"ID","roomId":"ID","userId":"ID","action":"Enum","action_idx":"Integer","reason":"Text","duration":"Integer","expiresAt":null,"issuedBy":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},
oldDataValues,
newDataValues
}

DbEvent lobbyChatHubModeration-deleted

Event topic: wechess-lobbychat-service-dbevent-lobbychathubmoderation-deleted

This event announces the deletion of a lobbyChatHubModeration 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","roomId":"ID","userId":"ID","action":"Enum","action_idx":"Integer","reason":"Text","duration":"Integer","expiresAt":null,"issuedBy":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":false}

ElasticSearch Index Events

Within the LobbyChat 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 lobbymessage-created

Event topic: elastic-index-wechess_lobbymessage-created

Event payload:

{"id":"ID","senderId":"ID","senderDisplayName":"String","content":"String","sentAt":"Date","reportStatus":"Enum","reportStatus_idx":"Integer","mutedUntil":"Date","removed":"Boolean","roomId":"String","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event lobbymessage-updated

Event topic: elastic-index-wechess_lobbymessage-created

Event payload:

{"id":"ID","senderId":"ID","senderDisplayName":"String","content":"String","sentAt":"Date","reportStatus":"Enum","reportStatus_idx":"Integer","mutedUntil":"Date","removed":"Boolean","roomId":"String","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event lobbymessage-deleted

Event topic: elastic-index-wechess_lobbymessage-deleted

Event payload:

{"id":"ID","senderId":"ID","senderDisplayName":"String","content":"String","sentAt":"Date","reportStatus":"Enum","reportStatus_idx":"Integer","mutedUntil":"Date","removed":"Boolean","roomId":"String","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event lobbymessage-extended

Event topic: elastic-index-wechess_lobbymessage-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 lobbymessage-created

Event topic : wechess-lobbychat-service-lobbymessage-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 lobbyMessage data object itself.

The following JSON included in the payload illustrates the fullest representation of the lobbyMessage 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":"lobbyMessage","method":"POST","action":"create","appVersion":"Version","rowCount":1,"lobbyMessage":{"id":"ID","senderId":"ID","senderDisplayName":"String","content":"String","sentAt":"Date","reportStatus":"Enum","reportStatus_idx":"Integer","mutedUntil":"Date","removed":"Boolean","roomId":"String","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true}}

Route Event lobbymessagemoderation-updated

Event topic : wechess-lobbychat-service-lobbymessagemoderation-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 lobbyMessage data object itself.

The following JSON included in the payload illustrates the fullest representation of the lobbyMessage 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":"lobbyMessage","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"lobbyMessage":{"id":"ID","senderId":"ID","senderDisplayName":"String","content":"String","sentAt":"Date","reportStatus":"Enum","reportStatus_idx":"Integer","mutedUntil":"Date","removed":"Boolean","roomId":"String","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true}}

Route Event lobbymessage-deleted

Event topic : wechess-lobbychat-service-lobbymessage-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 lobbyMessage data object itself.

The following JSON included in the payload illustrates the fullest representation of the lobbyMessage 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":"lobbyMessage","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"lobbyMessage":{"id":"ID","senderId":"ID","senderDisplayName":"String","content":"String","sentAt":"Date","reportStatus":"Enum","reportStatus_idx":"Integer","mutedUntil":"Date","removed":"Boolean","roomId":"String","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":false}}

Route Event lobbyroom-ensured

Event topic : wechess-lobbychat-service-lobbyroom-ensured

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the lobbyRoom data object itself.

The following JSON included in the payload illustrates the fullest representation of the lobbyRoom 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":"lobbyRoom","method":"POST","action":"create","appVersion":"Version","rowCount":1,"lobbyRoom":{"id":"ID","roomId":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event lobbyrooms-listed

Event topic : wechess-lobbychat-service-lobbyrooms-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 lobbyRooms data object itself.

The following JSON included in the payload illustrates the fullest representation of the lobbyRooms 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":"lobbyRooms","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","lobbyRooms":[{"id":"ID","roomId":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]}

Route Event lobbychathubmessage-deleted

Event topic : wechess-lobbychat-service-lobbychathubmessage-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 lobbyChatHubMessage data object itself.

The following JSON included in the payload illustrates the fullest representation of the lobbyChatHubMessage 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":"lobbyChatHubMessage","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"lobbyChatHubMessage":{"id":"ID","roomId":"ID","senderId":"ID","senderName":"String","senderAvatar":"String","messageType":"Enum","messageType_idx":"Integer","content":"Object","timestamp":null,"status":"Enum","status_idx":"Integer","reaction":"Object","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event lobbychathubmessage-updated

Event topic : wechess-lobbychat-service-lobbychathubmessage-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 lobbyChatHubMessage data object itself.

The following JSON included in the payload illustrates the fullest representation of the lobbyChatHubMessage 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":"lobbyChatHubMessage","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"lobbyChatHubMessage":{"id":"ID","roomId":"ID","senderId":"ID","senderName":"String","senderAvatar":"String","messageType":"Enum","messageType_idx":"Integer","content":"Object","timestamp":null,"status":"Enum","status_idx":"Integer","reaction":"Object","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Index Event lobbyroom-created

Event topic: elastic-index-wechess_lobbyroom-created

Event payload:

{"id":"ID","roomId":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event lobbyroom-updated

Event topic: elastic-index-wechess_lobbyroom-created

Event payload:

{"id":"ID","roomId":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event lobbyroom-deleted

Event topic: elastic-index-wechess_lobbyroom-deleted

Event payload:

{"id":"ID","roomId":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event lobbyroom-extended

Event topic: elastic-index-wechess_lobbyroom-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 lobbymessage-created

Event topic : wechess-lobbychat-service-lobbymessage-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 lobbyMessage data object itself.

The following JSON included in the payload illustrates the fullest representation of the lobbyMessage 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":"lobbyMessage","method":"POST","action":"create","appVersion":"Version","rowCount":1,"lobbyMessage":{"id":"ID","senderId":"ID","senderDisplayName":"String","content":"String","sentAt":"Date","reportStatus":"Enum","reportStatus_idx":"Integer","mutedUntil":"Date","removed":"Boolean","roomId":"String","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true}}

Route Event lobbymessagemoderation-updated

Event topic : wechess-lobbychat-service-lobbymessagemoderation-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 lobbyMessage data object itself.

The following JSON included in the payload illustrates the fullest representation of the lobbyMessage 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":"lobbyMessage","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"lobbyMessage":{"id":"ID","senderId":"ID","senderDisplayName":"String","content":"String","sentAt":"Date","reportStatus":"Enum","reportStatus_idx":"Integer","mutedUntil":"Date","removed":"Boolean","roomId":"String","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true}}

Route Event lobbymessage-deleted

Event topic : wechess-lobbychat-service-lobbymessage-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 lobbyMessage data object itself.

The following JSON included in the payload illustrates the fullest representation of the lobbyMessage 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":"lobbyMessage","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"lobbyMessage":{"id":"ID","senderId":"ID","senderDisplayName":"String","content":"String","sentAt":"Date","reportStatus":"Enum","reportStatus_idx":"Integer","mutedUntil":"Date","removed":"Boolean","roomId":"String","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":false}}

Route Event lobbyroom-ensured

Event topic : wechess-lobbychat-service-lobbyroom-ensured

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the lobbyRoom data object itself.

The following JSON included in the payload illustrates the fullest representation of the lobbyRoom 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":"lobbyRoom","method":"POST","action":"create","appVersion":"Version","rowCount":1,"lobbyRoom":{"id":"ID","roomId":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event lobbyrooms-listed

Event topic : wechess-lobbychat-service-lobbyrooms-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 lobbyRooms data object itself.

The following JSON included in the payload illustrates the fullest representation of the lobbyRooms 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":"lobbyRooms","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","lobbyRooms":[{"id":"ID","roomId":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]}

Route Event lobbychathubmessage-deleted

Event topic : wechess-lobbychat-service-lobbychathubmessage-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 lobbyChatHubMessage data object itself.

The following JSON included in the payload illustrates the fullest representation of the lobbyChatHubMessage 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":"lobbyChatHubMessage","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"lobbyChatHubMessage":{"id":"ID","roomId":"ID","senderId":"ID","senderName":"String","senderAvatar":"String","messageType":"Enum","messageType_idx":"Integer","content":"Object","timestamp":null,"status":"Enum","status_idx":"Integer","reaction":"Object","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event lobbychathubmessage-updated

Event topic : wechess-lobbychat-service-lobbychathubmessage-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 lobbyChatHubMessage data object itself.

The following JSON included in the payload illustrates the fullest representation of the lobbyChatHubMessage 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":"lobbyChatHubMessage","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"lobbyChatHubMessage":{"id":"ID","roomId":"ID","senderId":"ID","senderName":"String","senderAvatar":"String","messageType":"Enum","messageType_idx":"Integer","content":"Object","timestamp":null,"status":"Enum","status_idx":"Integer","reaction":"Object","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Index Event lobbychathubmessage-created

Event topic: elastic-index-wechess_lobbychathubmessage-created

Event payload:

{"id":"ID","roomId":"ID","senderId":"ID","senderName":"String","senderAvatar":"String","messageType":"Enum","messageType_idx":"Integer","content":"Object","timestamp":null,"status":"Enum","status_idx":"Integer","reaction":"Object","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event lobbychathubmessage-updated

Event topic: elastic-index-wechess_lobbychathubmessage-created

Event payload:

{"id":"ID","roomId":"ID","senderId":"ID","senderName":"String","senderAvatar":"String","messageType":"Enum","messageType_idx":"Integer","content":"Object","timestamp":null,"status":"Enum","status_idx":"Integer","reaction":"Object","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event lobbychathubmessage-deleted

Event topic: elastic-index-wechess_lobbychathubmessage-deleted

Event payload:

{"id":"ID","roomId":"ID","senderId":"ID","senderName":"String","senderAvatar":"String","messageType":"Enum","messageType_idx":"Integer","content":"Object","timestamp":null,"status":"Enum","status_idx":"Integer","reaction":"Object","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event lobbychathubmessage-extended

Event topic: elastic-index-wechess_lobbychathubmessage-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 lobbymessage-created

Event topic : wechess-lobbychat-service-lobbymessage-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 lobbyMessage data object itself.

The following JSON included in the payload illustrates the fullest representation of the lobbyMessage 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":"lobbyMessage","method":"POST","action":"create","appVersion":"Version","rowCount":1,"lobbyMessage":{"id":"ID","senderId":"ID","senderDisplayName":"String","content":"String","sentAt":"Date","reportStatus":"Enum","reportStatus_idx":"Integer","mutedUntil":"Date","removed":"Boolean","roomId":"String","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true}}

Route Event lobbymessagemoderation-updated

Event topic : wechess-lobbychat-service-lobbymessagemoderation-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 lobbyMessage data object itself.

The following JSON included in the payload illustrates the fullest representation of the lobbyMessage 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":"lobbyMessage","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"lobbyMessage":{"id":"ID","senderId":"ID","senderDisplayName":"String","content":"String","sentAt":"Date","reportStatus":"Enum","reportStatus_idx":"Integer","mutedUntil":"Date","removed":"Boolean","roomId":"String","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true}}

Route Event lobbymessage-deleted

Event topic : wechess-lobbychat-service-lobbymessage-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 lobbyMessage data object itself.

The following JSON included in the payload illustrates the fullest representation of the lobbyMessage 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":"lobbyMessage","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"lobbyMessage":{"id":"ID","senderId":"ID","senderDisplayName":"String","content":"String","sentAt":"Date","reportStatus":"Enum","reportStatus_idx":"Integer","mutedUntil":"Date","removed":"Boolean","roomId":"String","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":false}}

Route Event lobbyroom-ensured

Event topic : wechess-lobbychat-service-lobbyroom-ensured

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the lobbyRoom data object itself.

The following JSON included in the payload illustrates the fullest representation of the lobbyRoom 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":"lobbyRoom","method":"POST","action":"create","appVersion":"Version","rowCount":1,"lobbyRoom":{"id":"ID","roomId":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event lobbyrooms-listed

Event topic : wechess-lobbychat-service-lobbyrooms-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 lobbyRooms data object itself.

The following JSON included in the payload illustrates the fullest representation of the lobbyRooms 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":"lobbyRooms","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","lobbyRooms":[{"id":"ID","roomId":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]}

Route Event lobbychathubmessage-deleted

Event topic : wechess-lobbychat-service-lobbychathubmessage-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 lobbyChatHubMessage data object itself.

The following JSON included in the payload illustrates the fullest representation of the lobbyChatHubMessage 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":"lobbyChatHubMessage","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"lobbyChatHubMessage":{"id":"ID","roomId":"ID","senderId":"ID","senderName":"String","senderAvatar":"String","messageType":"Enum","messageType_idx":"Integer","content":"Object","timestamp":null,"status":"Enum","status_idx":"Integer","reaction":"Object","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event lobbychathubmessage-updated

Event topic : wechess-lobbychat-service-lobbychathubmessage-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 lobbyChatHubMessage data object itself.

The following JSON included in the payload illustrates the fullest representation of the lobbyChatHubMessage 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":"lobbyChatHubMessage","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"lobbyChatHubMessage":{"id":"ID","roomId":"ID","senderId":"ID","senderName":"String","senderAvatar":"String","messageType":"Enum","messageType_idx":"Integer","content":"Object","timestamp":null,"status":"Enum","status_idx":"Integer","reaction":"Object","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Index Event lobbychathubmoderation-created

Event topic: elastic-index-wechess_lobbychathubmoderation-created

Event payload:

{"id":"ID","roomId":"ID","userId":"ID","action":"Enum","action_idx":"Integer","reason":"Text","duration":"Integer","expiresAt":null,"issuedBy":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event lobbychathubmoderation-updated

Event topic: elastic-index-wechess_lobbychathubmoderation-created

Event payload:

{"id":"ID","roomId":"ID","userId":"ID","action":"Enum","action_idx":"Integer","reason":"Text","duration":"Integer","expiresAt":null,"issuedBy":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event lobbychathubmoderation-deleted

Event topic: elastic-index-wechess_lobbychathubmoderation-deleted

Event payload:

{"id":"ID","roomId":"ID","userId":"ID","action":"Enum","action_idx":"Integer","reason":"Text","duration":"Integer","expiresAt":null,"issuedBy":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event lobbychathubmoderation-extended

Event topic: elastic-index-wechess_lobbychathubmoderation-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 lobbymessage-created

Event topic : wechess-lobbychat-service-lobbymessage-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 lobbyMessage data object itself.

The following JSON included in the payload illustrates the fullest representation of the lobbyMessage 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":"lobbyMessage","method":"POST","action":"create","appVersion":"Version","rowCount":1,"lobbyMessage":{"id":"ID","senderId":"ID","senderDisplayName":"String","content":"String","sentAt":"Date","reportStatus":"Enum","reportStatus_idx":"Integer","mutedUntil":"Date","removed":"Boolean","roomId":"String","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true}}

Route Event lobbymessagemoderation-updated

Event topic : wechess-lobbychat-service-lobbymessagemoderation-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 lobbyMessage data object itself.

The following JSON included in the payload illustrates the fullest representation of the lobbyMessage 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":"lobbyMessage","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"lobbyMessage":{"id":"ID","senderId":"ID","senderDisplayName":"String","content":"String","sentAt":"Date","reportStatus":"Enum","reportStatus_idx":"Integer","mutedUntil":"Date","removed":"Boolean","roomId":"String","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true}}

Route Event lobbymessage-deleted

Event topic : wechess-lobbychat-service-lobbymessage-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 lobbyMessage data object itself.

The following JSON included in the payload illustrates the fullest representation of the lobbyMessage 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":"lobbyMessage","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"lobbyMessage":{"id":"ID","senderId":"ID","senderDisplayName":"String","content":"String","sentAt":"Date","reportStatus":"Enum","reportStatus_idx":"Integer","mutedUntil":"Date","removed":"Boolean","roomId":"String","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":false}}

Route Event lobbyroom-ensured

Event topic : wechess-lobbychat-service-lobbyroom-ensured

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the lobbyRoom data object itself.

The following JSON included in the payload illustrates the fullest representation of the lobbyRoom 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":"lobbyRoom","method":"POST","action":"create","appVersion":"Version","rowCount":1,"lobbyRoom":{"id":"ID","roomId":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event lobbyrooms-listed

Event topic : wechess-lobbychat-service-lobbyrooms-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 lobbyRooms data object itself.

The following JSON included in the payload illustrates the fullest representation of the lobbyRooms 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":"lobbyRooms","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","lobbyRooms":[{"id":"ID","roomId":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]}

Route Event lobbychathubmessage-deleted

Event topic : wechess-lobbychat-service-lobbychathubmessage-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 lobbyChatHubMessage data object itself.

The following JSON included in the payload illustrates the fullest representation of the lobbyChatHubMessage 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":"lobbyChatHubMessage","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"lobbyChatHubMessage":{"id":"ID","roomId":"ID","senderId":"ID","senderName":"String","senderAvatar":"String","messageType":"Enum","messageType_idx":"Integer","content":"Object","timestamp":null,"status":"Enum","status_idx":"Integer","reaction":"Object","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event lobbychathubmessage-updated

Event topic : wechess-lobbychat-service-lobbychathubmessage-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 lobbyChatHubMessage data object itself.

The following JSON included in the payload illustrates the fullest representation of the lobbyChatHubMessage 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":"lobbyChatHubMessage","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"lobbyChatHubMessage":{"id":"ID","roomId":"ID","senderId":"ID","senderName":"String","senderAvatar":"String","messageType":"Enum","messageType_idx":"Integer","content":"Object","timestamp":null,"status":"Enum","status_idx":"Integer","reaction":"Object","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 lobbyMessage

Service Design Specification - Object Design for lobbyMessage

wechess-lobbychat-service documentation

Document Overview

This document outlines the object design for the lobbyMessage model in our application. It includes details about the model’s attributes, relationships, and any specific validation or business logic that applies.

lobbyMessage Data Object

Object Overview

Description: A single lobby/public chat message between any logged-in user (guest, registered, admin). Ephemeral (24h retention), with reporting and moderation support. Muting is tracked by senderId+mutedUntil for punishment 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

Properties Schema

Property Type Required Description
senderId ID Yes User ID (guest or registered) who sent the message. References auth:user.id.
senderDisplayName String Yes Display name (from user fullname at send time; allows historical display even if name changes).
content String Yes Chat message body (limited at UI, backend-enforces not empty; max 500 chars).
sentAt Date Yes UTC timestamp when message was sent. Used to enforce 24h retention and sorting.
reportStatus Enum Yes Moderation/report workflow state: none (default), reported (user), underReview (admin).
mutedUntil Date No If set, the message sender is muted in the lobby until this timestamp. Only admins may set. Used with senderId for lookup on enforcement.
removed Boolean Yes If true, message is hidden/removed by admin moderation (soft-remove).
roomId String Yes Daily room identifier (lobby-YYYY-MM-DD). Scopes message to that day.

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

senderId senderDisplayName content 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

reportStatus mutedUntil removed roomId

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

senderId senderDisplayName content sentAt reportStatus mutedUntil removed roomId

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

senderId roomId

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

roomId

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

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

Filter Properties

senderId reportStatus removed

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 lobbyRoom

Service Design Specification - Object Design for lobbyRoom

wechess-lobbychat-service documentation

Document Overview

This document outlines the object design for the lobbyRoom model in our application. It includes details about the model’s attributes, relationships, and any specific validation or business logic that applies.

lobbyRoom Data Object

Object Overview

Description: Daily lobby chat room. One record per day (roomId format: lobby-YYYY-MM-DD). Older rooms kept as history.

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
roomId String Yes Room identifier, e.g. lobby-2026-03-10

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

roomId

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

roomId

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

roomId

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

roomId

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.


Service Design Specification - Object Design for lobbyChatHubMessage

Service Design Specification - Object Design for lobbyChatHubMessage

wechess-lobbychat-service documentation

Document Overview

This document outlines the object design for the lobbyChatHubMessage model in our application. It includes details about the model’s attributes, relationships, and any specific validation or business logic that applies.

lobbyChatHubMessage Data Object

Object Overview

Description: Auto-generated message DataObject for the lobbyChatHub RealtimeHub. Stores all messages with typed content payloads.

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
roomId ID Yes Reference to the room this message belongs to
senderId ID No Reference to the user who sent this message
senderName String No Display name of the sender (denormalized from user profile at send time)
senderAvatar String No Avatar URL of the sender (denormalized from user profile at send time)
messageType Enum Yes Content type discriminator for this message
content Object Yes Type-specific content payload (structure depends on messageType)
timestamp No Message creation time
status Enum No Message moderation status
reaction Object No Emoji reactions [{ emoji, userId, timestamp }]

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

roomId senderId senderName senderAvatar messageType timestamp

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

roomId senderId senderName senderAvatar messageType content timestamp status reaction

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

roomId senderId senderName senderAvatar messageType content timestamp status reaction

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

roomId senderId senderName senderAvatar messageType content timestamp status reaction

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

roomId

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

senderId

Session data properties are used to store data that is specific to the user session, allowing for personalized experiences and temporary data storage. If a property is configured as session data, it will be automatically mapped to the related field in the user session during CRUD operations. Note that session data properties can not be mutated by the user, but only by the system.

Filter Properties

roomId senderId senderName senderAvatar messageType content timestamp status reaction

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 lobbyChatHubModeration

Service Design Specification - Object Design for lobbyChatHubModeration

wechess-lobbychat-service documentation

Document Overview

This document outlines the object design for the lobbyChatHubModeration model in our application. It includes details about the model’s attributes, relationships, and any specific validation or business logic that applies.

lobbyChatHubModeration Data Object

Object Overview

Description: Auto-generated moderation DataObject for the lobbyChatHub RealtimeHub. Stores block and silence actions for room-level user moderation.

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
roomId ID Yes Reference to the room where the moderation action applies
userId ID Yes The user who is blocked or silenced
action Enum Yes Moderation action type
reason Text No Optional reason for the moderation action
duration Integer No Duration in seconds. 0 means permanent
expiresAt No Expiry timestamp. Null means permanent
issuedBy ID No The moderator who issued the action

Default Values

Default values are automatically assigned to properties when a new object is created, if no value is provided in the request body. Since default values are applied on db level, they should be literal values, not expressions.If you want to use expressions, you can use transposed parameters in any business API to set default values dynamically.

Constant Properties

roomId userId action duration expiresAt issuedBy

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

roomId userId action reason duration expiresAt issuedBy

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

roomId userId action reason duration expiresAt issuedBy

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

roomId userId action reason duration expiresAt issuedBy

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

roomId userId

Secondary key properties are used to create an additional indexed identifiers for the data object, allowing for alternative access patterns. Different than normal indexed properties, secondary keys will act as primary keys and Mindbricks will provide automatic secondary key db utility functions to access the data object by the secondary key.

Relation Properties

roomId

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

issuedBy

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

roomId userId action reason duration expiresAt issuedBy

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 Lobbymessage

Business API Design Specification - Create Lobbymessage

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 createLobbyMessage 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 createLobbyMessage Business API is designed to handle a create operation on the LobbyMessage data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

Post a new lobby chat message. Enforces mute (mutedUntil > now), ensures message is not empty and under 500 chars. SenderId and senderDisplayName are populated from session.

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 createLobbyMessage Business API includes a REST controller that can be triggered via the following route:

/v1/lobbymessages

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 createLobbyMessage Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The createLobbyMessage Business API has 9 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client.

Business API parameters can be:

Regular Parameters

Name Type Required Default Location Data Path
lobbyMessageId ID No - body lobbyMessageId
Description: This id paremeter is used to create the data object with a given specific id. Leave null for automatic id.
senderId ID Yes - body senderId
Description: User ID (guest or registered) who sent the message. References auth:user.id.
senderDisplayName String Yes - body senderDisplayName
Description: Display name (from user fullname at send time; allows historical display even if name changes).
content String Yes - body content
Description: Chat message body (limited at UI, backend-enforces not empty; max 500 chars).
sentAt Date Yes - body sentAt
Description: UTC timestamp when message was sent. Used to enforce 24h retention and sorting.
reportStatus Enum Yes - body reportStatus
Description: Moderation/report workflow state: none (default), reported (user), underReview (admin).
mutedUntil Date No - body mutedUntil
Description: If set, the message sender is muted in the lobby until this timestamp. Only admins may set. Used with senderId for lookup on enforcement.
removed Boolean Yes - body removed
Description: If true, message is hidden/removed by admin moderation (soft-remove).
roomId String Yes - body roomId
Description: Daily room identifier (lobby-YYYY-MM-DD). Scopes message to that day.

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 createLobbyMessage 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

{
    roomId: runMScript(() => (this.request.body.roomId), {"path":"services[2].businessLogic[0].dataClause.customData[0].value"}),
   
}

Actual Data Clause

The business api will use the following data clause. Note that any calculated value will be added to the data clause in the api manager.

{
  id: this.lobbyMessageId,
  senderId: this.senderId,
  senderDisplayName: this.senderDisplayName,
  content: this.content,
  sentAt: this.sentAt,
  reportStatus: this.reportStatus,
  mutedUntil: this.mutedUntil,
  removed: this.removed,
  roomId: runMScript(() => (this.request.body.roomId), {"path":"services[2].businessLogic[0].dataClause.customData[0].value"}),
}

Business Logic Workflow

[1] Step : startBusinessApi

Manager initializes context, populates session and request objects, prepares internal structures for parameter handling and workflow execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Manager reads input parameters, normalizes missing values, applies default type casting, and stores them in the API context.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Manager transforms parameters, computes derived values, flattens or remaps arrays/objects, and adjusts formats for downstream processing.


[4] Step : checkParameters

Manager executes built-in validations: required field checks, type enforcement, and basic business rules. Prevents operation if validation fails.


[5] Action : validateMuteAndContent

Action Type: FunctionCallAction

Pre-send logic: throw error if user is muted (any unexpired mute found for sender) and check content meets requirements.

class Api {
  async validateMuteAndContent() {
    try {
      return runMScript(() => LIB.lobbyChatValidateMuteAndContent(this), {
        path: "services[2].businessLogic[0].actions.functionCallActions[0].callScript",
      });
    } catch (err) {
      console.error("Error in FunctionCallAction validateMuteAndContent:", err);
      throw err;
    }
  }
}

[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 createLobbyMessage api has got 8 regular client parameters

Parameter Type Required Population
senderId ID true request.body?.[“senderId”]
senderDisplayName String true request.body?.[“senderDisplayName”]
content String true request.body?.[“content”]
sentAt Date true request.body?.[“sentAt”]
reportStatus Enum true request.body?.[“reportStatus”]
mutedUntil Date false request.body?.[“mutedUntil”]
removed Boolean true request.body?.[“removed”]
roomId String true request.body?.[“roomId”]

REST Request

To access the api you can use the REST controller with the path POST /v1/lobbymessages

  axios({
    method: 'POST',
    url: '/v1/lobbymessages',
    data: {
            senderId:"ID",  
            senderDisplayName:"String",  
            content:"String",  
            sentAt:"Date",  
            reportStatus:"Enum",  
            mutedUntil:"Date",  
            removed:"Boolean",  
            roomId:"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 lobbyMessage 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": "lobbyMessage",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"lobbyMessage": {
		"id": "ID",
		"senderId": "ID",
		"senderDisplayName": "String",
		"content": "String",
		"sentAt": "Date",
		"reportStatus": "Enum",
		"reportStatus_idx": "Integer",
		"mutedUntil": "Date",
		"removed": "Boolean",
		"roomId": "String",
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"isActive": true
	}
}

Business API Design Specification - List Lobbymessages

Business API Design Specification - List Lobbymessages

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 listLobbyMessages 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 listLobbyMessages Business API is designed to handle a list operation on the LobbyMessage data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

Fetch latest lobby chat messages from the last 24 hours (not removed). Sorted sentAt desc. Paginated by default (50 per page).

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 listLobbyMessages Business API includes a REST controller that can be triggered via the following route:

/v1/listlobbymessages/:roomId

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 listLobbyMessages Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The listLobbyMessages 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
roomId String Yes - urlpath roomId
Description: Daily room identifier (lobby-YYYY-MM-DD). Scopes message to that day… 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 listLobbyMessages 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,roomId,senderId,senderDisplayName,content,sentAt,reportStatus,mutedUntil,removed

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 :

{removed: false, sentAt: { $gte: (new Date(Date.now() - 24*60*60*1000)).toISOString() }}

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({removed: false, sentAt: { $gte: (new Date(Date.now() - 24*60*60*1000)).toISOString() }}), {"path":"services[2].businessLogic[1].whereClause.fullWhereClause"})

List Options

Defines list-specific options including filtering logic, default sorting, and result customization for APIs that return multiple records.

List Sort By Sort order definitions for the result set. Multiple fields can be provided with direction (asc/desc).

[ sentAt desc ]

List Group By Grouping definitions for the result set. This is typically used for visual or report-based grouping.

The list is not grouped.

setAsRead: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed.

No setAsread field-value pair is configured.

Permission Filter Optional filter that applies permission constraints dynamically based on session or object roles. So that the list items are filtered by the user’s OBAC or ABAC permissions.

Permission filter is not active at the moment. Follow Mindbricks updates to be able to use it.

Pagination Options

Contains settings to configure pagination behavior for list APIs. Includes options like page size, offset, cursor support, and total count inclusion.

Business Logic Workflow

[1] Step : startBusinessApi

Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Reads request and Redis parameters, applies defaults, and writes them to context for downstream processing.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Transforms and normalizes parameters, derives dependent values, and reshapes inputs for the main list query.


[4] Step : checkParameters

Executes validation logic on required and custom parameters, enforcing business rules and cross-field consistency.


[5] Step : checkBasicAuth

Performs role-based access checks and applies dynamic membership or session-based restrictions.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildWhereClause

Constructs the main query WHERE clause and applies optional filters or scoped access controls.

You can use the following settings to change some behavior of this step. whereClause

[7] Step : mainListOperation

Executes the paginated database query, retrieves the list, and stores results in context for enrichment.

You can use the following settings to change some behavior of this step. selectClause, listOptions, paginationOptions

[8] Step : buildOutput

Assembles the list response, sanitizes sensitive fields, applies transformations, and injects extra context if needed.


[9] Step : sendResponse

Sends the paginated list to the client through the controller.


[10] Step : raiseApiEvent

Triggers optional post-workflow events, such as Kafka messages, logs, or system notifications.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The listLobbyMessages api has got 1 regular client parameter

Parameter Type Required Population
roomId String true request.params?.[“roomId”]

REST Request

To access the api you can use the REST controller with the path GET /v1/listlobbymessages/:roomId

  axios({
    method: 'GET',
    url: `/v1/listlobbymessages/${roomId}`,
    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 lobbyMessages 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": "lobbyMessages",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"lobbyMessages": [
		{
			"isActive": true
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Business API Design Specification - Update Lobbymessagemoderation

Business API Design Specification - Update Lobbymessagemoderation

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 updateLobbyMessageModeration 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 updateLobbyMessageModeration Business API is designed to handle a update operation on the LobbyMessage data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

Update message for moderation: only admins may set removed (true), mutedUntil, or set reportStatus to underReview. All users may set reportStatus to reported on a message they wish to report. Message owner may not update content or displayName.

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 updateLobbyMessageModeration Business API includes a REST controller that can be triggered via the following route:

/v1/lobbymessagemoderation/:lobbyMessageId

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 updateLobbyMessageModeration Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The updateLobbyMessageModeration 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
lobbyMessageId ID Yes - urlpath lobbyMessageId
Description: This id paremeter is used to select the required data object that will be updated
reportStatus Enum No - body reportStatus
Description: Moderation/report workflow state: none (default), reported (user), underReview (admin).
mutedUntil Date No - body mutedUntil
Description: If set, the message sender is muted in the lobby until this timestamp. Only admins may set. Used with senderId for lookup on enforcement.
removed Boolean No - body removed
Description: If true, message is hidden/removed by admin moderation (soft-remove).
roomId String No - body roomId
Description: Daily room identifier (lobby-YYYY-MM-DD). Scopes message to that day.

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 updateLobbyMessageModeration Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({id:this.lobbyMessageId}), {"path":"services[2].businessLogic[2].whereClause.fullWhereClause"})

Data Clause

Defines custom field-value assignments used to modify or augment the default payload for create and update operations. These settings override values derived from the session or parameters if explicitly provided.", Note that a default data clause is always prepared by Mindbricks using data property settings, however any property in the data clause can be override by Data Clause Settings.

An update data clause populates all update-allowed properties of a data object, however the null properties (that are not provided by client) are ignored in db layer.

Custom Data Clause Override No custom data clause override configured

Actual Data Clause

The business api will use the following data clause. Note that any calculated value will be added to the data clause in the api manager.

{
  reportStatus: this.reportStatus,
  mutedUntil: this.mutedUntil,
  removed: this.removed,
  roomId: this.roomId,
}

Business Logic Workflow

[1] Step : startBusinessApi

Manager initializes context, prepares request and session objects, and sets up internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Manager reads parameters from the request or Redis, applies defaults, and writes them into context for downstream milestones.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Manager executes parameter transform scripts and derives any helper values or reshaped payloads into the context.


[4] Step : checkParameters

Manager validates required parameters, checks ID formats (UUID/ObjectId), and ensures all preconditions for update are met.


[5] Action : validateModerationUpdate

Action Type: FunctionCallAction

Disallow update of content or displayName; enforce only allowed fields (removed, mutedUntil, reportStatus).

class Api {
  async validateModerationUpdate() {
    try {
      return runMScript(() => LIB.lobbyChatValidateModerationUpdate(this), {
        path: "services[2].businessLogic[2].actions.functionCallActions[0].callScript",
      });
    } catch (err) {
      console.error(
        "Error in FunctionCallAction validateModerationUpdate:",
        err,
      );
      throw err;
    }
  }
}

[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 updateLobbyMessageModeration api has got 5 regular client parameters

Parameter Type Required Population
lobbyMessageId ID true request.params?.[“lobbyMessageId”]
reportStatus Enum false request.body?.[“reportStatus”]
mutedUntil Date false request.body?.[“mutedUntil”]
removed Boolean false request.body?.[“removed”]
roomId String false request.body?.[“roomId”]

REST Request

To access the api you can use the REST controller with the path PATCH /v1/lobbymessagemoderation/:lobbyMessageId

  axios({
    method: 'PATCH',
    url: `/v1/lobbymessagemoderation/${lobbyMessageId}`,
    data: {
            reportStatus:"Enum",  
            mutedUntil:"Date",  
            removed:"Boolean",  
            roomId:"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 lobbyMessage 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": "lobbyMessage",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"lobbyMessage": {
		"id": "ID",
		"senderId": "ID",
		"senderDisplayName": "String",
		"content": "String",
		"sentAt": "Date",
		"reportStatus": "Enum",
		"reportStatus_idx": "Integer",
		"mutedUntil": "Date",
		"removed": "Boolean",
		"roomId": "String",
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"isActive": true
	}
}

Business API Design Specification - Delete Lobbymessage

Business API Design Specification - Delete Lobbymessage

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 deleteLobbyMessage 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 deleteLobbyMessage Business API is designed to handle a delete operation on the LobbyMessage data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

Physical delete of a lobby message (should only be possible for admin batch/cleanup or hard moderation). In practice, most moderation is via removed:true.

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 deleteLobbyMessage Business API includes a REST controller that can be triggered via the following route:

/v1/lobbymessages/:lobbyMessageId

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 deleteLobbyMessage Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The deleteLobbyMessage 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
lobbyMessageId ID Yes - urlpath lobbyMessageId
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 deleteLobbyMessage Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({id:this.lobbyMessageId}), {"path":"services[2].businessLogic[3].whereClause.fullWhereClause"})

Delete Options

Use these options to set delete specific settings.

useSoftDelete: false If true, the record will be marked as deleted (isActive: false) instead of removed. The implementation depends on the data object’s soft delete configuration.

Business Logic Workflow

[1] Step : startBusinessApi

Manager initializes context, prepares request/session objects, and sets up internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Manager reads and normalizes parameters, applies defaults, and stores them in the context for downstream steps.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Manager executes parameter transform scripts, computes derived values, and remaps objects or arrays as needed for later processing.


[4] Step : checkParameters

Manager runs built-in validations including required field checks, type enforcement, and deletion preconditions. Stops execution if validation fails.


[5] Step : checkBasicAuth

Manager validates session, user roles, permissions, and tenant-specific access rules to enforce basic auth restrictions.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildWhereClause

Manager generates the query conditions, applies ownership and parent checks, and ensures the clause is correct for the delete operation.

You can use the following settings to change some behavior of this step. whereClause

[7] Step : fetchInstance

Manager fetches the target record, applies filters from WHERE clause, and writes the instance to the context for further checks.


[8] Step : checkInstance

Manager performs object-level validations such as lock status, soft-delete eligibility, and multi-step approval enforcement.


[9] Step : mainDeleteOperation

Manager executes the delete query, updates related indexes/caches, and handles soft/hard delete logic according to configuration.

You can use the following settings to change some behavior of this step. deleteOptions

[10] Step : buildOutput

Manager shapes the response payload, masks sensitive fields, and formats related cleanup results for output.


[11] Step : sendResponse

Manager delivers the response to the client and finalizes any temporary internal structures.


[12] Step : raiseApiEvent

Manager triggers asynchronous API events, notifies queues or streams, and performs final cleanup for the workflow.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The deleteLobbyMessage api has got 1 regular client parameter

Parameter Type Required Population
lobbyMessageId ID true request.params?.[“lobbyMessageId”]

REST Request

To access the api you can use the REST controller with the path DELETE /v1/lobbymessages/:lobbyMessageId

  axios({
    method: 'DELETE',
    url: `/v1/lobbymessages/${lobbyMessageId}`,
    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 lobbyMessage 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": "lobbyMessage",
	"method": "DELETE",
	"action": "delete",
	"appVersion": "Version",
	"rowCount": 1,
	"lobbyMessage": {
		"id": "ID",
		"senderId": "ID",
		"senderDisplayName": "String",
		"content": "String",
		"sentAt": "Date",
		"reportStatus": "Enum",
		"reportStatus_idx": "Integer",
		"mutedUntil": "Date",
		"removed": "Boolean",
		"roomId": "String",
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"isActive": false
	}
}

Business API Design Specification - Ensure Lobbyroom

Business API Design Specification - Ensure Lobbyroom

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 ensureLobbyRoom 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 ensureLobbyRoom Business API is designed to handle a create operation on the LobbyRoom data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The ensureLobbyRoom Business API includes a REST controller that can be triggered via the following route:

/v1/ensurelobbyroom

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 ensureLobbyRoom Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The ensureLobbyRoom 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
lobbyRoomId ID No - body lobbyRoomId
Description: This id paremeter is used to create the data object with a given specific id. Leave null for automatic id.
roomId String Yes - body roomId
Description: Room identifier, e.g. lobby-2026-03-10

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 ensureLobbyRoom 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

{
    roomId: runMScript(() => (this.request.body.roomId), {"path":"services[2].businessLogic[4].dataClause.customData[0].value"}),
   
}

Actual Data Clause

The business api will use the following data clause. Note that any calculated value will be added to the data clause in the api manager.

{
  id: this.lobbyRoomId,
  roomId: runMScript(() => (this.request.body.roomId), {"path":"services[2].businessLogic[4].dataClause.customData[0].value"}),
  isActive: true,
  _archivedAt: null,
}

Business Logic Workflow

[1] Step : startBusinessApi

Manager initializes context, populates session and request objects, prepares internal structures for parameter handling and workflow execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Manager reads input parameters, normalizes missing values, applies default type casting, and stores them in the API context.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Manager transforms parameters, computes derived values, flattens or remaps arrays/objects, and adjusts formats for downstream processing.


[4] Step : checkParameters

Manager executes built-in validations: required field checks, type enforcement, and basic business rules. Prevents operation if validation fails.


[5] Step : checkBasicAuth

Manager performs authentication and authorization checks: verifies session, user roles, permissions, and tenant restrictions.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildDataClause

Manager constructs the final data object for creation, fills auto-generated fields (IDs, timestamps, owner fields), and ensures schema consistency.

You can use the following settings to change some behavior of this step. dataClause

[7] Step : mainCreateOperation

Manager executes the database insert operation, updates indexes/caches, and triggers internal post-processing like linked default records.


[8] Step : buildOutput

Manager shapes the response: masks sensitive fields, resolves linked references, and formats output according to API contract.


[9] Step : sendResponse

Manager sends the response to the client and finalizes internal tasks like flushing logs or updating session state.


[10] Step : raiseApiEvent

Manager triggers API-level events (Kafka, WebSocket, async workflows) as the final internal step.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The ensureLobbyRoom api has got 1 regular client parameter

Parameter Type Required Population
roomId String true request.body?.[“roomId”]

REST Request

To access the api you can use the REST controller with the path POST /v1/ensurelobbyroom

  axios({
    method: 'POST',
    url: '/v1/ensurelobbyroom',
    data: {
            roomId:"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 lobbyRoom 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": "lobbyRoom",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"lobbyRoom": {
		"id": "ID",
		"roomId": "String",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Business API Design Specification - List Lobbyrooms

Business API Design Specification - List Lobbyrooms

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 listLobbyRooms 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 listLobbyRooms Business API is designed to handle a list operation on the LobbyRoom data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The listLobbyRooms Business API includes a REST controller that can be triggered via the following route:

/v1/listlobbyrooms/:roomId

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 listLobbyRooms Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The listLobbyRooms 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
roomId String Yes - urlpath roomId
Description: Room identifier, e.g. lobby-2026-03-10. 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 listLobbyRooms 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.

runMScript(() => ({$and:[{roomId:{"$eq":this.roomId}},{isActive:true}]}), {"path":"services[2].businessLogic[5].whereClause.fullWhereClause"})

List Options

Defines list-specific options including filtering logic, default sorting, and result customization for APIs that return multiple records.

List Sort By Sort order definitions for the result set. Multiple fields can be provided with direction (asc/desc).

Specific sort order is not configure, natural order (ascending id) will be used.

List Group By Grouping definitions for the result set. This is typically used for visual or report-based grouping.

The list is not grouped.

setAsRead: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed.

No setAsread field-value pair is configured.

Permission Filter Optional filter that applies permission constraints dynamically based on session or object roles. So that the list items are filtered by the user’s OBAC or ABAC permissions.

Permission filter is not active at the moment. Follow Mindbricks updates to be able to use it.

Pagination Options

Contains settings to configure pagination behavior for list APIs. Includes options like page size, offset, cursor support, and total count inclusion.

Business Logic Workflow

[1] Step : startBusinessApi

Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Reads request and Redis parameters, applies defaults, and writes them to context for downstream processing.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Transforms and normalizes parameters, derives dependent values, and reshapes inputs for the main list query.


[4] Step : checkParameters

Executes validation logic on required and custom parameters, enforcing business rules and cross-field consistency.


[5] Step : checkBasicAuth

Performs role-based access checks and applies dynamic membership or session-based restrictions.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildWhereClause

Constructs the main query WHERE clause and applies optional filters or scoped access controls.

You can use the following settings to change some behavior of this step. whereClause

[7] Step : mainListOperation

Executes the paginated database query, retrieves the list, and stores results in context for enrichment.

You can use the following settings to change some behavior of this step. selectClause, listOptions, paginationOptions

[8] Step : buildOutput

Assembles the list response, sanitizes sensitive fields, applies transformations, and injects extra context if needed.


[9] Step : sendResponse

Sends the paginated list to the client through the controller.


[10] Step : raiseApiEvent

Triggers optional post-workflow events, such as Kafka messages, logs, or system notifications.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The listLobbyRooms api has got 1 regular client parameter

Parameter Type Required Population
roomId String true request.params?.[“roomId”]

REST Request

To access the api you can use the REST controller with the path GET /v1/listlobbyrooms/:roomId

  axios({
    method: 'GET',
    url: `/v1/listlobbyrooms/${roomId}`,
    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 lobbyRooms 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": "lobbyRooms",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"lobbyRooms": [
		{
			"id": "ID",
			"roomId": "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 Lobbychathubmessages

Business API Design Specification - List Lobbychathubmessages

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 listLobbyChatHubMessages 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 listLobbyChatHubMessages Business API is designed to handle a list operation on the LobbyChatHubMessage data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

List messages in a lobbyChatHub hub room. Accessible by admins and room participants.

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 listLobbyChatHubMessages Business API includes a REST controller that can be triggered via the following route:

/v1/v1/lobbyChatHub-messages

By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the Parameters section.

MCP Tool

REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This listLobbyChatHubMessages Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The listLobbyChatHubMessages Business API has 9 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client.

Business API parameters can be:

Filter Parameters

The listLobbyChatHubMessages api supports 9 optional filter parameters for filtering list results using URL query parameters. These parameters are only available for list type APIs.

roomId Filter

Type: ID
Description: Reference to the room this message belongs to
Location: Query Parameter

Usage:

Non-Array Property:

Examples:

// Get records with a specific ID
GET /v1/v1/lobbyChatHub-messages?roomId=550e8400-e29b-41d4-a716-446655440000

// Get records with multiple IDs (use multiple parameters)
GET /v1/v1/lobbyChatHub-messages?roomId=550e8400-e29b-41d4-a716-446655440000&roomId=660e8400-e29b-41d4-a716-446655440001

// Get records without this field
GET /v1/v1/lobbyChatHub-messages?roomId=null

senderId Filter

Type: ID
Description: Reference to the user who sent this message
Location: Query Parameter

Usage:

Non-Array Property:

Examples:

// Get records with a specific ID
GET /v1/v1/lobbyChatHub-messages?senderId=550e8400-e29b-41d4-a716-446655440000

// Get records with multiple IDs (use multiple parameters)
GET /v1/v1/lobbyChatHub-messages?senderId=550e8400-e29b-41d4-a716-446655440000&senderId=660e8400-e29b-41d4-a716-446655440001

// Get records without this field
GET /v1/v1/lobbyChatHub-messages?senderId=null

senderName Filter

Type: String
Description: Display name of the sender (denormalized from user profile at send time)
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/v1/lobbyChatHub-messages?senderName=john
// Matches: "John", "Johnny", "johnson", "McJohn", etc.

// Find records with multiple values (use multiple parameters)
GET /v1/v1/lobbyChatHub-messages?senderName=laptop&senderName=phone&senderName=tablet
// Matches records containing "laptop", "phone", or "tablet" anywhere in the field

// Find records without this field
GET /v1/v1/lobbyChatHub-messages?senderName=null

senderAvatar Filter

Type: String
Description: Avatar URL of the sender (denormalized from user profile at send time)
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/v1/lobbyChatHub-messages?senderAvatar=john
// Matches: "John", "Johnny", "johnson", "McJohn", etc.

// Find records with multiple values (use multiple parameters)
GET /v1/v1/lobbyChatHub-messages?senderAvatar=laptop&senderAvatar=phone&senderAvatar=tablet
// Matches records containing "laptop", "phone", or "tablet" anywhere in the field

// Find records without this field
GET /v1/v1/lobbyChatHub-messages?senderAvatar=null

messageType Filter

Type: Enum
Description: Content type discriminator for this message
Location: Query Parameter

Usage:

Examples:

// Get records with specific enum value
GET /v1/v1/lobbyChatHub-messages?messageType=active

// Get records with multiple enum values (use multiple parameters)
GET /v1/v1/lobbyChatHub-messages?messageType=active&messageType=pending

// Get records without this field
GET /v1/v1/lobbyChatHub-messages?messageType=null

content Filter

Type: Object
Description: Type-specific content payload (structure depends on messageType)
Location: Query Parameter

Usage:

Examples:

// Get records with specific value
GET /v1/v1/lobbyChatHub-messages?content=<value>

// Get records with multiple values (use multiple parameters)
GET /v1/v1/lobbyChatHub-messages?content=<value1>&content=<value2>

// Get records without this field
GET /v1/v1/lobbyChatHub-messages?content=null

timestamp Filter

Type: String
Description: Message creation time
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/v1/lobbyChatHub-messages?timestamp=john
// Matches: "John", "Johnny", "johnson", "McJohn", etc.

// Find records with multiple values (use multiple parameters)
GET /v1/v1/lobbyChatHub-messages?timestamp=laptop&timestamp=phone&timestamp=tablet
// Matches records containing "laptop", "phone", or "tablet" anywhere in the field

// Find records without this field
GET /v1/v1/lobbyChatHub-messages?timestamp=null

status Filter

Type: Enum
Description: Message moderation status
Location: Query Parameter

Usage:

Examples:

// Get records with specific enum value
GET /v1/v1/lobbyChatHub-messages?status=active

// Get records with multiple enum values (use multiple parameters)
GET /v1/v1/lobbyChatHub-messages?status=active&status=pending

// Get records without this field
GET /v1/v1/lobbyChatHub-messages?status=null

reaction Filter

Type: Object
Description: Emoji reactions [{ emoji, userId, timestamp }]
Location: Query Parameter

Usage:

Examples:

// Get records with specific value
GET /v1/v1/lobbyChatHub-messages?reaction=<value>

// Get records with multiple values (use multiple parameters)
GET /v1/v1/lobbyChatHub-messages?reaction=<value1>&reaction=<value2>

// Get records without this field
GET /v1/v1/lobbyChatHub-messages?reaction=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 listLobbyChatHubMessages Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Select Clause

Specifies which fields will be selected from the main data object during a get or list operation. Leave blank to select all properties. This applies only to get and list type APIs.",

``

Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({isActive:true}), {"path":"services[2].businessLogic[6].whereClause.fullWhereClause"})

List Options

Defines list-specific options including filtering logic, default sorting, and result customization for APIs that return multiple records.

List Sort By Sort order definitions for the result set. Multiple fields can be provided with direction (asc/desc).

[ timestamp desc ]

List Group By Grouping definitions for the result set. This is typically used for visual or report-based grouping.

The list is not grouped.

setAsRead: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed.

No setAsread field-value pair is configured.

Permission Filter Optional filter that applies permission constraints dynamically based on session or object roles. So that the list items are filtered by the user’s OBAC or ABAC permissions.

Permission filter is not active at the moment. Follow Mindbricks updates to be able to use it.

Pagination Options

Contains settings to configure pagination behavior for list APIs. Includes options like page size, offset, cursor support, and total count inclusion.

Business Logic Workflow

[1] Step : startBusinessApi

Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Reads request and Redis parameters, applies defaults, and writes them to context for downstream processing.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Transforms and normalizes parameters, derives dependent values, and reshapes inputs for the main list query.


[4] Step : checkParameters

Executes validation logic on required and custom parameters, enforcing business rules and cross-field consistency.


[5] Step : checkBasicAuth

Performs role-based access checks and applies dynamic membership or session-based restrictions.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildWhereClause

Constructs the main query WHERE clause and applies optional filters or scoped access controls.

You can use the following settings to change some behavior of this step. whereClause

[7] Step : mainListOperation

Executes the paginated database query, retrieves the list, and stores results in context for enrichment.

You can use the following settings to change some behavior of this step. selectClause, listOptions, paginationOptions

[8] Step : buildOutput

Assembles the list response, sanitizes sensitive fields, applies transformations, and injects extra context if needed.


[9] Step : sendResponse

Sends the paginated list to the client through the controller.


[10] Step : raiseApiEvent

Triggers optional post-workflow events, such as Kafka messages, logs, or system notifications.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The listLobbyChatHubMessages api has 9 filter parameters available for filtering list results. See the Filter Parameters section above for detailed usage examples.

Filter Parameter Type Array Property Description
roomId ID No Reference to the room this message belongs to
senderId ID No Reference to the user who sent this message
senderName String No Display name of the sender (denormalized from user profile at send time)
senderAvatar String No Avatar URL of the sender (denormalized from user profile at send time)
messageType Enum No Content type discriminator for this message
content Object No Type-specific content payload (structure depends on messageType)
timestamp String No Message creation time
status Enum No Message moderation status
reaction Object No Emoji reactions [{ emoji, userId, timestamp }]

REST Request

To access the api you can use the REST controller with the path GET /v1/v1/lobbyChatHub-messages

  axios({
    method: 'GET',
    url: '/v1/v1/lobbyChatHub-messages',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section for usage examples)
        // roomId: '<value>' // Filter by roomId
        // senderId: '<value>' // Filter by senderId
        // senderName: '<value>' // Filter by senderName
        // senderAvatar: '<value>' // Filter by senderAvatar
        // messageType: '<value>' // Filter by messageType
        // content: '<value>' // Filter by content
        // timestamp: '<value>' // Filter by timestamp
        // status: '<value>' // Filter by status
        // reaction: '<value>' // Filter by reaction
            }
  });

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 lobbyChatHubMessages 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": "lobbyChatHubMessages",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"lobbyChatHubMessages": [
		{
			"id": "ID",
			"roomId": "ID",
			"senderId": "ID",
			"senderName": "String",
			"senderAvatar": "String",
			"messageType": "Enum",
			"messageType_idx": "Integer",
			"content": "Object",
			"timestamp": null,
			"status": "Enum",
			"status_idx": "Integer",
			"reaction": "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 - Get Lobbychathubmessage

Business API Design Specification - Get Lobbychathubmessage

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 getLobbyChatHubMessage 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 getLobbyChatHubMessage Business API is designed to handle a get operation on the LobbyChatHubMessage data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

Get a single lobbyChatHub hub message 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 getLobbyChatHubMessage Business API includes a REST controller that can be triggered via the following route:

/v1/v1/lobbyChatHub-messages/: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 getLobbyChatHubMessage Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The getLobbyChatHubMessage 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
lobbyChatHubMessageId ID Yes - urlpath lobbyChatHubMessageId
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 getLobbyChatHubMessage Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Select Clause

Specifies which fields will be selected from the main data object during a get or list operation. Leave blank to select all properties. This applies only to get and list type APIs.",

``

Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({$and:[{id:this.lobbyChatHubMessageId},{isActive:true}]}), {"path":"services[2].businessLogic[7].whereClause.fullWhereClause"})

Get Options

Use these options to set get specific settings.

setAsRead: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed.

No setAsread field-value pair is configured.

Business Logic Workflow

[1] Step : startBusinessApi

Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Extracts parameters from request and Redis, applies defaults, and writes them to context.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Executes parameter transformation scripts, applies type coercion, merges derived values, and reshapes inputs for downstream milestones.


[4] Step : checkParameters

Validates required and custom parameters, enforcing business-specific rules and constraints.


[5] Step : checkBasicAuth

Performs login, role, and permission checks, and applies dynamic object-level access rules.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildWhereClause

Builds the WHERE clause for fetching the object and applies additional scoped filters if configured.

You can use the following settings to change some behavior of this step. whereClause

[7] Step : mainGetOperation

Executes the database fetch, retrieves the object, and stores it in context for enrichment or further checks.

You can use the following settings to change some behavior of this step. selectClause, getOptions

[8] Step : checkInstance

Performs instance-level validations, such as ownership, existence, or access conditions.


[9] Step : buildOutput

Assembles the response from the object, applies masking, formatting, and injects additional metadata if needed.


[10] Step : sendResponse

Delivers the response to the controller for client delivery.


[11] Step : raiseApiEvent

Triggers optional API-level events after workflow completion, sending messages to integrations like Kafka if configured.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The getLobbyChatHubMessage api has got 2 regular client parameters

Parameter Type Required Population
lobbyChatHubMessageId ID true request.params?.[“lobbyChatHubMessageId”]
id String true request.params?.[“id”]

REST Request

To access the api you can use the REST controller with the path GET /v1/v1/lobbyChatHub-messages/:id

  axios({
    method: 'GET',
    url: `/v1/v1/lobbyChatHub-messages/${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 lobbyChatHubMessage 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": "lobbyChatHubMessage",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"lobbyChatHubMessage": {
		"id": "ID",
		"roomId": "ID",
		"senderId": "ID",
		"senderName": "String",
		"senderAvatar": "String",
		"messageType": "Enum",
		"messageType_idx": "Integer",
		"content": "Object",
		"timestamp": null,
		"status": "Enum",
		"status_idx": "Integer",
		"reaction": "Object",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Business API Design Specification - Delete Lobbychathubmessage

Business API Design Specification - Delete Lobbychathubmessage

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 deleteLobbyChatHubMessage 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 deleteLobbyChatHubMessage Business API is designed to handle a delete operation on the LobbyChatHubMessage 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 lobbyChatHub hub message. Admins can delete any message; users can delete their own.

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The deleteLobbyChatHubMessage Business API includes a REST controller that can be triggered via the following route:

/v1/v1/lobbyChatHub-messages/: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 deleteLobbyChatHubMessage Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The deleteLobbyChatHubMessage 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
lobbyChatHubMessageId ID Yes - urlpath lobbyChatHubMessageId
Description: This id paremeter is used to select the required data object that will be deleted
id String Yes - urlpath id
Description: This parameter will be used to select the data object that want to 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 deleteLobbyChatHubMessage Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({$and:[{id:this.lobbyChatHubMessageId},{isActive:true}]}), {"path":"services[2].businessLogic[8].whereClause.fullWhereClause"})

Delete Options

Use these options to set delete specific settings.

useSoftDelete: If true, the record will be marked as deleted (isActive: false) instead of removed. The implementation depends on the data object’s soft delete configuration.

Business Logic Workflow

[1] Step : startBusinessApi

Manager initializes context, prepares request/session objects, and sets up internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Manager reads and normalizes parameters, applies defaults, and stores them in the context for downstream steps.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Manager executes parameter transform scripts, computes derived values, and remaps objects or arrays as needed for later processing.


[4] Step : checkParameters

Manager runs built-in validations including required field checks, type enforcement, and deletion preconditions. Stops execution if validation fails.


[5] Step : checkBasicAuth

Manager validates session, user roles, permissions, and tenant-specific access rules to enforce basic auth restrictions.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildWhereClause

Manager generates the query conditions, applies ownership and parent checks, and ensures the clause is correct for the delete operation.

You can use the following settings to change some behavior of this step. whereClause

[7] Step : fetchInstance

Manager fetches the target record, applies filters from WHERE clause, and writes the instance to the context for further checks.


[8] Step : checkInstance

Manager performs object-level validations such as lock status, soft-delete eligibility, and multi-step approval enforcement.


[9] Step : mainDeleteOperation

Manager executes the delete query, updates related indexes/caches, and handles soft/hard delete logic according to configuration.

You can use the following settings to change some behavior of this step. deleteOptions

[10] Step : buildOutput

Manager shapes the response payload, masks sensitive fields, and formats related cleanup results for output.


[11] Step : sendResponse

Manager delivers the response to the client and finalizes any temporary internal structures.


[12] Step : raiseApiEvent

Manager triggers asynchronous API events, notifies queues or streams, and performs final cleanup for the workflow.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The deleteLobbyChatHubMessage api has got 2 regular client parameters

Parameter Type Required Population
lobbyChatHubMessageId ID true request.params?.[“lobbyChatHubMessageId”]
id String true request.params?.[“id”]

REST Request

To access the api you can use the REST controller with the path DELETE /v1/v1/lobbyChatHub-messages/:id

  axios({
    method: 'DELETE',
    url: `/v1/v1/lobbyChatHub-messages/${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 lobbyChatHubMessage 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": "lobbyChatHubMessage",
	"method": "DELETE",
	"action": "delete",
	"appVersion": "Version",
	"rowCount": 1,
	"lobbyChatHubMessage": {
		"id": "ID",
		"roomId": "ID",
		"senderId": "ID",
		"senderName": "String",
		"senderAvatar": "String",
		"messageType": "Enum",
		"messageType_idx": "Integer",
		"content": "Object",
		"timestamp": null,
		"status": "Enum",
		"status_idx": "Integer",
		"reaction": "Object",
		"isActive": false,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Business API Design Specification - Update Lobbychathubmessage

Business API Design Specification - Update Lobbychathubmessage

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 updateLobbyChatHubMessage 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 updateLobbyChatHubMessage Business API is designed to handle a update operation on the LobbyChatHubMessage data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

Update a lobbyChatHub hub message content. Only the message sender or admins can edit.

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 updateLobbyChatHubMessage Business API includes a REST controller that can be triggered via the following route:

/v1/v1/lobbyChatHub-messages/: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 updateLobbyChatHubMessage Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The updateLobbyChatHubMessage 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
lobbyChatHubMessageId ID Yes - urlpath lobbyChatHubMessageId
Description: This id paremeter is used to select the required data object that will be updated
content Object No - body content
Description: Type-specific content payload (structure depends on messageType)
status Enum No - body status
Description: Message moderation status
reaction Object No - body reaction
Description: Emoji reactions [{ emoji, userId, timestamp }]
id String Yes - urlpath id
Description: This parameter will be used to select the data object that want 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 updateLobbyChatHubMessage Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({$and:[{id:this.lobbyChatHubMessageId},{isActive:true}]}), {"path":"services[2].businessLogic[9].whereClause.fullWhereClause"})

Data Clause

Defines custom field-value assignments used to modify or augment the default payload for create and update operations. These settings override values derived from the session or parameters if explicitly provided.", Note that a default data clause is always prepared by Mindbricks using data property settings, however any property in the data clause can be override by Data Clause Settings.

An update data clause populates all update-allowed properties of a data object, however the null properties (that are not provided by client) are ignored in db layer.

Custom Data Clause Override No custom data clause override configured

Actual Data Clause

The business api will use the following data clause. Note that any calculated value will be added to the data clause in the api manager.

{
  content: this.content ? (typeof this.content == 'string' ? JSON.parse(this.content) : this.content) : null,
  status: this.status,
  reaction: this.reaction ? (typeof this.reaction == 'string' ? JSON.parse(this.reaction) : this.reaction) : null,
}

Business Logic Workflow

[1] Step : startBusinessApi

Manager initializes context, prepares request and session objects, and sets up internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Manager reads parameters from the request or Redis, applies defaults, and writes them into context for downstream milestones.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Manager executes parameter transform scripts and derives any helper values or reshaped payloads into the context.


[4] Step : checkParameters

Manager validates required parameters, checks ID formats (UUID/ObjectId), and ensures all preconditions for update are met.


[5] Step : checkBasicAuth

Manager performs login verification, role, and permission checks, enforcing tenant and access rules before update.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildWhereClause

Manager constructs the WHERE clause used to identify the record to update, applying ownership and parent checks if necessary.

You can use the following settings to change some behavior of this step. whereClause

[7] Step : fetchInstance

Manager fetches the existing record from the database and writes it to the context for validation or enrichment.


[8] Step : checkInstance

Manager performs instance-level validations, including ownership, existence, lock status, or other pre-update checks.


[9] Step : buildDataClause

Manager prepares the data clause for the update, applying transformations or enhancements before persisting.

You can use the following settings to change some behavior of this step. dataClause

[10] Step : mainUpdateOperation

Manager executes the update operation with the WHERE and data clauses. Database-level events are raised if configured.


[11] Step : buildOutput

Manager assembles the response object from the update result, masking fields or injecting additional metadata.


[12] Step : sendResponse

Manager sends the response back to the controller for delivery to the client.


[13] Step : raiseApiEvent

Manager triggers API-level events, sending relevant messages to Kafka or other integrations if configured.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The updateLobbyChatHubMessage api has got 5 regular client parameters

Parameter Type Required Population
lobbyChatHubMessageId ID true request.params?.[“lobbyChatHubMessageId”]
content Object false request.body?.[“content”]
status Enum false request.body?.[“status”]
reaction Object false request.body?.[“reaction”]
id String true request.params?.[“id”]

REST Request

To access the api you can use the REST controller with the path PATCH /v1/v1/lobbyChatHub-messages/:id

  axios({
    method: 'PATCH',
    url: `/v1/v1/lobbyChatHub-messages/${id}`,
    data: {
            content:"Object",  
            status:"Enum",  
            reaction:"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 lobbyChatHubMessage 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": "lobbyChatHubMessage",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"lobbyChatHubMessage": {
		"id": "ID",
		"roomId": "ID",
		"senderId": "ID",
		"senderName": "String",
		"senderAvatar": "String",
		"messageType": "Enum",
		"messageType_idx": "Integer",
		"content": "Object",
		"timestamp": null,
		"status": "Enum",
		"status_idx": "Integer",
		"reaction": "Object",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Realtime Hubs

Realtime Hub Design Specification - lobbyChatHub

Realtime Hub Design Specification - lobbyChatHub

This document provides a detailed architectural overview of the lobbyChatHub realtime hub within the lobbyChat service. It covers the hub’s room management, message handling, role-based authorization, event system, and server-side logic.

Hub Overview

Description: Public lobby chat hub. A single shared room where all authenticated users (guests and registered) can chat in real-time. Messages have 24-hour retention. Supports moderation: report, mute, and admin removal.

Room Settings

Rooms are backed by the lobbyRoom DataObject. Each record in this object represents a room that users can join.

Authorization Flow

The hub uses a layered authorization flow to determine each user’s role when joining a room:

  1. Absolute Roles: Users with roles administrator bypass all checks and receive the system hub role with full permissions.

  2. Auth Sources: The following DataObject-based authorization sources are checked in order. The first match determines the user’s hub role:

    1. allowAllAuthenticated

Hub Roles

Role Read Send Moderate Delete Any Manage Room Moderated
lobbyUser Yes Yes No No No No
moderator Yes Yes Yes Yes No No

Message Settings

Built-in Message Types

The following message types are supported:

Cross-Cutting Features

Event Settings

Standard Events

Event Enabled Type
Typing Indicator Yes Ephemeral
Recording Indicator No Ephemeral
Read Receipts No Persisted
Delivery Receipts No Persisted
Presence Yes Ephemeral

Auto-Bridged DataObject Events

CRUD events from the room, membership, and message DataObjects are automatically bridged via Kafka and broadcast to connected clients. This includes events like memberJoined, messageEdited, roomUpdated, etc.

Custom Events

History Settings

Guardrails

Setting Value
Max Users Per Room 1000
Max Rooms Per User 3
Message Rate Limit 20 msg/min
Max Message Size 4096 bytes
Connection Timeout 300000 ms
Auth Cache TTL 300 seconds
Global Moderation No
Default Silenced No

Server-Side Logic


This document was generated from the realtime hub configuration and should be kept in sync with design changes.


Service Library - lobbyChat

Service Library - lobbyChat

This document provides a complete reference of the custom code library for the lobbyChat service. It includes all library functions, edge functions with their REST endpoints, templates, and assets.

Library Functions

Library functions are reusable modules available to all business APIs and other custom code within the service via require("lib/<moduleName>").

lobbyChatValidateMuteAndContent.js

module.exports = async function lobbyChatValidateMuteAndContent(context) {
  // context.session.userId is the sender
  const senderId = context.session.userId;
  if (!senderId) throw new Error('You must be logged in to send messages.');

  // Collect active mute(s) for this sender (any lobbyMessage with mutedUntil > now for this sender)
  const { getLobbyMessageListByQuery } = require("dbLayer");
  const now = new Date();
  const mutedMsgs = await getLobbyMessageListByQuery({ senderId, mutedUntil: { $notnull: true } });
  if (mutedMsgs && mutedMsgs.length > 0) {
    // Muted if *any* applicable unexpired mute exists
    const isMuted = mutedMsgs.some(msg => msg.mutedUntil && new Date(msg.mutedUntil) > now);
    if (isMuted) throw new Error('You are currently muted and cannot send lobby messages.');
  }
  // Content validation
  const body = context.content ?? context.request?.body?.content;
  if (!body || typeof body !== 'string' || !body.trim()) {
    throw new Error('Message content cannot be empty.');
  }
  if (body.length > 500) {
    throw new Error('Message content exceeds 500 character limit.');
  }
  // Attach displayName
  context.senderDisplayName = context.session.fullname || 'Anonymous';
  return true;
}

lobbyChatValidateModerationUpdate.js

module.exports = function lobbyChatValidateModerationUpdate(context) {
  // Only allowed to update: removed, mutedUntil, reportStatus (never content, senderDisplayName)
  const allowed = ['removed','mutedUntil','reportStatus'];
  const updating = Object.keys(context.updateData || {});
  if (updating.some(f => !allowed.includes(f))) {
    throw new Error('Only moderation fields may be changed: removed, mutedUntil, reportStatus.');
  }
  return true;
}

Edge Functions

Edge functions are custom HTTP endpoint handlers that run outside the standard Business API pipeline. Each edge function is paired with an Edge Controller that defines its REST endpoint.

purgeExpiredLobbyMessages.js

Edge Controller:

module.exports = async () => {
  // Physically remove all messages older than 24h
  const { deleteLobbyMessageByQuery } = require("dbLayer");
  const cutoff = new Date(Date.now() - 24*60*60*1000);
  const where = { sentAt: { $lt: cutoff.toISOString() } };
  const deleted = await deleteLobbyMessageByQuery(where);
  return { status: 200, deletedCount: deleted.length, cutoff: cutoff.toISOString() };
}

Edge Controllers Summary

Function Name Method Path Login Required
purgeExpiredLobbyMessages GET /admin/purge-expired-lobby-messages Yes

This document was generated from the service library configuration and should be kept in sync with design changes.


Leaderboard Service

Service Design Specification

Service Design Specification

wechess-leaderboard-service documentation Version: 1.0.21

Scope

This document provides a structured architectural overview of the leaderboard 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.

Leaderboard Service Settings

Handles ELO/stat computation and leaderboard management for registered players only. Excludes guest users entirely.

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 wechess-leaderboard-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 wechess-leaderboard-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
playerStats Stores aggregate stats for a registered chess player: ELO, win/loss history, streak, last game, etc. Excludes guests. One per registered user. accessPrivate
leaderboardEntry Holds global leaderboard standings for registered players. Rank, ELO, and season support. Excludes guests. accessProtected

playerStats Data Object

Object Overview

Description: Stores aggregate stats for a registered chess player: ELO, win/loss history, streak, last game, etc. Excludes guests. One per registered user.

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
userId ID Yes The registered user this record belongs to (auth:user.id).
eloRating Integer Yes Current ELO rating for registered player.
totalGames Integer Yes Total completed games (wins + losses + draws) for this player.
wins Integer Yes Number of games won by the player.
losses Integer Yes Number of games lost by the player.
draws Integer Yes Number of drawn games by the player.
streak Integer Yes Current win or loss streak. Positive=win streak, negative=loss streak, 0=none/neutral.
lastGameAt Date No Timestamp of last completed game for user.
username String No Display name for the player, publicly visible.

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

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

eloRating totalGames wins losses draws streak lastGameAt username

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 eloRating totalGames wins losses draws streak lastGameAt username

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 eloRating totalGames wins losses draws streak

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

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

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

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

leaderboardEntry Data Object

Object Overview

Description: Holds global leaderboard standings for registered players. Rank, ELO, and season support. Excludes guests.

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
userId ID Yes The registered user this leaderboard entry represents.
currentRank Integer Yes Current leaderboard rank (1=top). Lower is better.
eloRating Integer Yes Player's current ELO rating (copy from playerStats).
season String No Leaderboard season identifier (null for all-time/global, can be set for seasonal leaderboards as needed).
lastRankChangeAt Date No Timestamp of last rank change/leaderboard update.
username String No Display name for the player, publicly visible on leaderboard.

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

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

currentRank eloRating season lastRankChangeAt username

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 currentRank eloRating season lastRankChangeAt username

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 currentRank eloRating

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

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

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

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

Business Logic

leaderboard has got 6 Business APIs to manage its internal and crud logic. For the details of each business API refer to its chapter.

Event Subscriptions

leaderboard has 1 Event Subscription configured. Clients connect via WebSocket (Socket.IO) or SSE to receive real-time Kafka event streams with authorization-driven access control.

Subscription Name Transport Topics Namespace / Endpoint
gameEvents websocket 1 /events/gameEvents

For detailed documentation on each subscription, refer to:

Service Library

Functions

failIfNotRegisteredPlayer.js

module.exports = async function failIfNotRegisteredPlayer(userId, context=null) {
    // fetch user role via serviceCommon helper
    const { fetchRemoteObjectByMQuery } = require("serviceCommon");
    const user = await fetchRemoteObjectByMQuery("User", { id: userId });
    if (!user) throw new Error("User does not exist.");
    if (user.roleId !== "registeredPlayer" && user.roleId !== "administrator") throw new Error("Leaderboard and stats are only for registered users.");
    return true;
}

This document was generated from the service architecture definition and should be kept in sync with implementation changes.


REST API GUIDE

REST API GUIDE

wechess-leaderboard-service

Version: 1.0.21

Handles ELO/stat computation and leaderboard management for registered players only. Excludes guest users entirely.

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 Leaderboard Service’s REST API. This document is designed to provide a comprehensive guide to interfacing with our Leaderboard Service exclusively through RESTful API endpoints.

Intended Audience

This documentation is intended for developers and integrators who are looking to interact with the Leaderboard Service via HTTP requests for purposes such as creating, updating, deleting and querying Leaderboard 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 Leaderboard 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 Leaderboard 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 wechess-access-token
Cookie wechess-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 Leaderboard 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 Leaderboard 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 Leaderboard 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 Leaderboard 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 Leaderboard 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 Leaderboard 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

Leaderboard 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.

PlayerStats resource

Resource Definition : Stores aggregate stats for a registered chess player: ELO, win/loss history, streak, last game, etc. Excludes guests. One per registered user. PlayerStats Resource Properties

Name Type Required Default Definition
userId ID The registered user this record belongs to (auth:user.id).
eloRating Integer Current ELO rating for registered player.
totalGames Integer Total completed games (wins + losses + draws) for this player.
wins Integer Number of games won by the player.
losses Integer Number of games lost by the player.
draws Integer Number of drawn games by the player.
streak Integer Current win or loss streak. Positive=win streak, negative=loss streak, 0=none/neutral.
lastGameAt Date Timestamp of last completed game for user.
username String Display name for the player, publicly visible.

LeaderboardEntry resource

Resource Definition : Holds global leaderboard standings for registered players. Rank, ELO, and season support. Excludes guests. LeaderboardEntry Resource Properties

Name Type Required Default Definition
userId ID The registered user this leaderboard entry represents.
currentRank Integer Current leaderboard rank (1=top). Lower is better.
eloRating Integer Player's current ELO rating (copy from playerStats).
season String Leaderboard season identifier (null for all-time/global, can be set for seasonal leaderboards as needed).
lastRankChangeAt Date Timestamp of last rank change/leaderboard update.
username String Display name for the player, publicly visible on leaderboard.

Business Api

Create Playerstats API

[Default create API] — This is the designated default create API for the playerStats data object. Frontend generators and AI agents should use this API for standard CRUD operations. Create a player stats record for a newly registered player. Only registered users (never guests) should have this object. Typically used at registration or conversion.

API Frontend Description By The Backend Architect

Called only at registration or on converting guest to registered. Prepares stats for profile display.

Rest Route

The createPlayerStats API REST controller can be triggered via the following route:

/v1/playerstatses

Rest Request Parameters

The createPlayerStats api has got 9 regular request parameters

Parameter Type Required Population
userId ID true request.body?.[“userId”]
eloRating Integer true request.body?.[“eloRating”]
totalGames Integer true request.body?.[“totalGames”]
wins Integer true request.body?.[“wins”]
losses Integer true request.body?.[“losses”]
draws Integer true request.body?.[“draws”]
streak Integer true request.body?.[“streak”]
lastGameAt Date false request.body?.[“lastGameAt”]
username String false request.body?.[“username”]
userId : The registered user this record belongs to (auth:user.id).
eloRating : Current ELO rating for registered player.
totalGames : Total completed games (wins + losses + draws) for this player.
wins : Number of games won by the player.
losses : Number of games lost by the player.
draws : Number of drawn games by the player.
streak : Current win or loss streak. Positive=win streak, negative=loss streak, 0=none/neutral.
lastGameAt : Timestamp of last completed game for user.
username : Display name for the player, publicly visible.

REST Request To access the api you can use the REST controller with the path POST /v1/playerstatses

  axios({
    method: 'POST',
    url: '/v1/playerstatses',
    data: {
            userId:"ID",  
            eloRating:"Integer",  
            totalGames:"Integer",  
            wins:"Integer",  
            losses:"Integer",  
            draws:"Integer",  
            streak:"Integer",  
            lastGameAt:"Date",  
            username:"String",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "playerStats",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"playerStats": {
		"id": "ID",
		"userId": "ID",
		"eloRating": "Integer",
		"totalGames": "Integer",
		"wins": "Integer",
		"losses": "Integer",
		"draws": "Integer",
		"streak": "Integer",
		"lastGameAt": "Date",
		"username": "String",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Update Playerstats API

[Default update API] — This is the designated default update API for the playerStats data object. Frontend generators and AI agents should use this API for standard CRUD operations. Update player statistics when a game completes. Only called for registered users by gameplay service (M2M) or admin; guests not allowed.

API Frontend Description By The Backend Architect

System/gameplay triggers this to update stats at game end. Never called for guests.

Rest Route

The updatePlayerStats API REST controller can be triggered via the following route:

/v1/playerstatses/:playerStatsId

Rest Request Parameters

The updatePlayerStats api has got 9 regular request parameters

Parameter Type Required Population
playerStatsId ID true request.params?.[“playerStatsId”]
eloRating Integer true request.body?.[“eloRating”]
totalGames Integer true request.body?.[“totalGames”]
wins Integer true request.body?.[“wins”]
losses Integer true request.body?.[“losses”]
draws Integer true request.body?.[“draws”]
streak Integer true request.body?.[“streak”]
lastGameAt Date false request.body?.[“lastGameAt”]
username String false request.body?.[“username”]
playerStatsId : This id paremeter is used to select the required data object that will be updated
eloRating : Current ELO rating for registered player.
totalGames : Total completed games (wins + losses + draws) for this player.
wins : Number of games won by the player.
losses : Number of games lost by the player.
draws : Number of drawn games by the player.
streak : Current win or loss streak. Positive=win streak, negative=loss streak, 0=none/neutral.
lastGameAt : Timestamp of last completed game for user.
username : Display name for the player, publicly visible.

REST Request To access the api you can use the REST controller with the path PATCH /v1/playerstatses/:playerStatsId

  axios({
    method: 'PATCH',
    url: `/v1/playerstatses/${playerStatsId}`,
    data: {
            eloRating:"Integer",  
            totalGames:"Integer",  
            wins:"Integer",  
            losses:"Integer",  
            draws:"Integer",  
            streak:"Integer",  
            lastGameAt:"Date",  
            username:"String",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "playerStats",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"playerStats": {
		"id": "ID",
		"userId": "ID",
		"eloRating": "Integer",
		"totalGames": "Integer",
		"wins": "Integer",
		"losses": "Integer",
		"draws": "Integer",
		"streak": "Integer",
		"lastGameAt": "Date",
		"username": "String",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Get Playerstats API

[Default get API] — This is the designated default get API for the playerStats data object. Frontend generators and AI agents should use this API for standard CRUD operations. Fetch a single registered user’s player stats (private to user or admin).

API Frontend Description By The Backend Architect

Used to display profile stats. User can only view own; admin can view any.

Rest Route

The getPlayerStats API REST controller can be triggered via the following route:

/v1/playerstatses/:userId

Rest Request Parameters

The getPlayerStats api has got 1 regular request parameter

Parameter Type Required Population
userId ID true request.params?.[“userId”]
userId : The registered user this record belongs to (auth:user.id)… The parameter is used to query data.

REST Request To access the api you can use the REST controller with the path GET /v1/playerstatses/:userId

  axios({
    method: 'GET',
    url: `/v1/playerstatses/${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": "playerStats",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"playerStats": {
		"isActive": true
	}
}

Get Leaderboardentry API

[Default get API] — This is the designated default get API for the leaderboardEntry data object. Frontend generators and AI agents should use this API for standard CRUD operations. Fetch this player’s leaderboard rank entry (registered users only).

API Frontend Description By The Backend Architect

Allow user to view their own leaderboard position (or admin to view any user). Entry includes user info for display.

Rest Route

The getLeaderboardEntry API REST controller can be triggered via the following route:

/v1/leaderboardentries/:userId

Rest Request Parameters

The getLeaderboardEntry api has got 1 regular request parameter

Parameter Type Required Population
userId ID true request.params?.[“userId”]
userId : The registered user this leaderboard entry represents… The parameter is used to query data.

REST Request To access the api you can use the REST controller with the path GET /v1/leaderboardentries/:userId

  axios({
    method: 'GET',
    url: `/v1/leaderboardentries/${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": "leaderboardEntry",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"leaderboardEntry": {
		"isActive": true
	}
}

List Leaderboardtopn API

[Default list API] — This is the designated default list API for the leaderboardEntry data object. Frontend generators and AI agents should use this API for standard CRUD operations. List top N players for leaderboard display (e.g., leaderboard page top 100). Sorted by currentRank ascending (best = 1).

API Frontend Description By The Backend Architect

Leaderboard screen populates using this API; accessible to all authenticated users (guests see empty/null result).

Rest Route

The listLeaderboardTopN API REST controller can be triggered via the following route:

/v1/leaderboardtopn

Rest Request Parameters

The listLeaderboardTopN api has got 1 regular request parameter

Parameter Type Required Population
topN Integer false request.query?.[“topN”]
topN : Number of top players to return (max 500)

REST Request To access the api you can use the REST controller with the path GET /v1/leaderboardtopn

  axios({
    method: 'GET',
    url: '/v1/leaderboardtopn',
    data: {
    
    },
    params: {
             topN:'"Integer"',  
    
        }
  });

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": "leaderboardEntries",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"leaderboardEntries": [
		{
			"isActive": true
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Create Leaderboardentry API

Create a leaderboard entry for a registered player. Called when PlayerStats exists but LeaderboardEntry is missing.

API Frontend Description By The Backend Architect

Called by ensureLeaderboardEntry when a user has PlayerStats but no LeaderboardEntry.

Rest Route

The createLeaderboardEntry API REST controller can be triggered via the following route:

/v1/leaderboardentries

Rest Request Parameters

The createLeaderboardEntry api has got 6 regular request parameters

Parameter Type Required Population
userId ID true request.body?.[“userId”]
currentRank Integer true request.body?.[“currentRank”]
eloRating Integer true request.body?.[“eloRating”]
season String false request.body?.[“season”]
lastRankChangeAt Date false request.body?.[“lastRankChangeAt”]
username String false request.body?.[“username”]
userId : The registered user this leaderboard entry represents.
currentRank : Current leaderboard rank (1=top). Lower is better.
eloRating : Player’s current ELO rating (copy from playerStats).
season : Leaderboard season identifier (null for all-time/global, can be set for seasonal leaderboards as needed).
lastRankChangeAt : Timestamp of last rank change/leaderboard update.
username : Display name for the player, publicly visible on leaderboard.

REST Request To access the api you can use the REST controller with the path POST /v1/leaderboardentries

  axios({
    method: 'POST',
    url: '/v1/leaderboardentries',
    data: {
            userId:"ID",  
            currentRank:"Integer",  
            eloRating:"Integer",  
            season:"String",  
            lastRankChangeAt:"Date",  
            username:"String",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "leaderboardEntry",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"leaderboardEntry": {
		"id": "ID",
		"userId": "ID",
		"currentRank": "Integer",
		"eloRating": "Integer",
		"season": "String",
		"lastRankChangeAt": "Date",
		"username": "String",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Authentication Specific Routes

Common Routes

Route: currentuser

Route Definition: Retrieves the currently authenticated user’s session information.

Route Type: sessionInfo

Access Route: GET /currentuser

Parameters

This route does not require any request parameters.

Behavior

// Sample GET /currentuser call
axios.get("/currentuser", {
  headers: {
    "Authorization": "Bearer your-jwt-token"
  }
});

Success Response Returns the session object, including user-related data and token information.

{
  "sessionId": "9cf23fa8-07d4-4e7c-80a6-ec6d6ac96bb9",
  "userId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38",
  "email": "user@example.com",
  "fullname": "John Doe",
  "roleId": "user",
  "tenantId": "abc123",
  "accessToken": "jwt-token-string",
  ...
}

Error Response 401 Unauthorized: No active session found.

{
  "status": "ERR",
  "message": "No login found"
}

Notes

Route: permissions

*Route Definition*: Retrieves all effective permission records assigned to the currently authenticated user.

*Route Type*: permissionFetch

Access Route: GET /permissions

Parameters

This route does not require any request parameters.

Behavior

// Sample GET /permissions call
axios.get("/permissions", {
  headers: {
    "Authorization": "Bearer your-jwt-token"
  }
});

Success Response

Returns an array of permission objects.

[
  {
    "id": "perm1",
    "permissionName": "adminPanel.access",
    "roleId": "admin",
    "subjectUserId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38",
    "subjectUserGroupId": null,
    "objectId": null,
    "canDo": true,
    "tenantCodename": "store123"
  },
  {
    "id": "perm2",
    "permissionName": "orders.manage",
    "roleId": null,
    "subjectUserId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38",
    "subjectUserGroupId": null,
    "objectId": null,
    "canDo": true,
    "tenantCodename": "store123"
  }
]

Each object reflects a single permission grant, aligned with the givenPermissions model:

Error Responses

{
  "status": "ERR",
  "message": "No login found"
}

Notes

Tip: Applications can cache permission results client-side or server-side, but should occasionally refresh by calling this endpoint, especially after login or permission-changing operations.

Route: permissions/:permissionName

Route Definition: Checks whether the current user has access to a specific permission, and provides a list of scoped object exceptions or inclusions.

Route Type: permissionScopeCheck

Access Route: GET /permissions/:permissionName

Parameters

Parameter Type Required Population
permissionName String Yes request.params.permissionName

Behavior

// Sample GET /permissions/orders.manage
axios.get("/permissions/orders.manage", {
  headers: {
    "Authorization": "Bearer your-jwt-token"
  }
});

Success Response

{
  "canDo": true,
  "exceptions": [
    "a1f2e3d4-xxxx-yyyy-zzzz-object1",
    "b2c3d4e5-xxxx-yyyy-zzzz-object2"
  ]
}

Copyright

All sources, documents and other digital materials are copyright of .

About Us

For more information please visit our website: .

. .


EVENT GUIDE

EVENT GUIDE

wechess-leaderboard-service

Handles ELO/stat computation and leaderboard management for registered players only. Excludes guest users entirely.

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 Leaderboard Service Event descriptions. This guide is dedicated to detailing how to subscribe to and listen for state changes within the Leaderboard Service, offering an exclusive focus on event subscription mechanisms.

Intended Audience

This documentation is aimed at developers and integrators looking to monitor Leaderboard Service state changes. It is especially relevant for those wishing to implement or enhance business logic based on interactions with Leaderboard 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 Leaderboard 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 playerStats-created

Event topic: wechess-leaderboard-service-dbevent-playerstats-created

This event is triggered upon the creation of a playerStats 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","eloRating":"Integer","totalGames":"Integer","wins":"Integer","losses":"Integer","draws":"Integer","streak":"Integer","lastGameAt":"Date","username":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

DbEvent playerStats-updated

Event topic: wechess-leaderboard-service-dbevent-playerstats-updated

Activation of this event follows the update of a playerStats data object. The payload contains the updated information under the playerStats attribute, along with the original data prior to update, labeled as old_playerStats and also you can find the old and new versions of updated-only portion of the data…

Event payload:

{
old_playerStats:{"id":"ID","userId":"ID","eloRating":"Integer","totalGames":"Integer","wins":"Integer","losses":"Integer","draws":"Integer","streak":"Integer","lastGameAt":"Date","username":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},
playerStats:{"id":"ID","userId":"ID","eloRating":"Integer","totalGames":"Integer","wins":"Integer","losses":"Integer","draws":"Integer","streak":"Integer","lastGameAt":"Date","username":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},
oldDataValues,
newDataValues
}

DbEvent playerStats-deleted

Event topic: wechess-leaderboard-service-dbevent-playerstats-deleted

This event announces the deletion of a playerStats 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","eloRating":"Integer","totalGames":"Integer","wins":"Integer","losses":"Integer","draws":"Integer","streak":"Integer","lastGameAt":"Date","username":"String","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

DbEvent leaderboardEntry-created

Event topic: wechess-leaderboard-service-dbevent-leaderboardentry-created

This event is triggered upon the creation of a leaderboardEntry 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","currentRank":"Integer","eloRating":"Integer","season":"String","lastRankChangeAt":"Date","username":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

DbEvent leaderboardEntry-updated

Event topic: wechess-leaderboard-service-dbevent-leaderboardentry-updated

Activation of this event follows the update of a leaderboardEntry data object. The payload contains the updated information under the leaderboardEntry attribute, along with the original data prior to update, labeled as old_leaderboardEntry and also you can find the old and new versions of updated-only portion of the data…

Event payload:

{
old_leaderboardEntry:{"id":"ID","userId":"ID","currentRank":"Integer","eloRating":"Integer","season":"String","lastRankChangeAt":"Date","username":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},
leaderboardEntry:{"id":"ID","userId":"ID","currentRank":"Integer","eloRating":"Integer","season":"String","lastRankChangeAt":"Date","username":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},
oldDataValues,
newDataValues
}

DbEvent leaderboardEntry-deleted

Event topic: wechess-leaderboard-service-dbevent-leaderboardentry-deleted

This event announces the deletion of a leaderboardEntry 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","currentRank":"Integer","eloRating":"Integer","season":"String","lastRankChangeAt":"Date","username":"String","isActive":false,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

ElasticSearch Index Events

Within the Leaderboard 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 playerstats-created

Event topic: elastic-index-wechess_playerstats-created

Event payload:

{"id":"ID","userId":"ID","eloRating":"Integer","totalGames":"Integer","wins":"Integer","losses":"Integer","draws":"Integer","streak":"Integer","lastGameAt":"Date","username":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event playerstats-updated

Event topic: elastic-index-wechess_playerstats-created

Event payload:

{"id":"ID","userId":"ID","eloRating":"Integer","totalGames":"Integer","wins":"Integer","losses":"Integer","draws":"Integer","streak":"Integer","lastGameAt":"Date","username":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event playerstats-deleted

Event topic: elastic-index-wechess_playerstats-deleted

Event payload:

{"id":"ID","userId":"ID","eloRating":"Integer","totalGames":"Integer","wins":"Integer","losses":"Integer","draws":"Integer","streak":"Integer","lastGameAt":"Date","username":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event playerstats-extended

Event topic: elastic-index-wechess_playerstats-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 playerstats-created

Event topic : wechess-leaderboard-service-playerstats-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 playerStats data object itself.

The following JSON included in the payload illustrates the fullest representation of the playerStats 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":"playerStats","method":"POST","action":"create","appVersion":"Version","rowCount":1,"playerStats":{"id":"ID","userId":"ID","eloRating":"Integer","totalGames":"Integer","wins":"Integer","losses":"Integer","draws":"Integer","streak":"Integer","lastGameAt":"Date","username":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event playerstats-updated

Event topic : wechess-leaderboard-service-playerstats-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 playerStats data object itself.

The following JSON included in the payload illustrates the fullest representation of the playerStats 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":"playerStats","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"playerStats":{"id":"ID","userId":"ID","eloRating":"Integer","totalGames":"Integer","wins":"Integer","losses":"Integer","draws":"Integer","streak":"Integer","lastGameAt":"Date","username":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Index Event leaderboardentry-created

Event topic: elastic-index-wechess_leaderboardentry-created

Event payload:

{"id":"ID","userId":"ID","currentRank":"Integer","eloRating":"Integer","season":"String","lastRankChangeAt":"Date","username":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event leaderboardentry-updated

Event topic: elastic-index-wechess_leaderboardentry-created

Event payload:

{"id":"ID","userId":"ID","currentRank":"Integer","eloRating":"Integer","season":"String","lastRankChangeAt":"Date","username":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event leaderboardentry-deleted

Event topic: elastic-index-wechess_leaderboardentry-deleted

Event payload:

{"id":"ID","userId":"ID","currentRank":"Integer","eloRating":"Integer","season":"String","lastRankChangeAt":"Date","username":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event leaderboardentry-extended

Event topic: elastic-index-wechess_leaderboardentry-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 playerstats-created

Event topic : wechess-leaderboard-service-playerstats-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 playerStats data object itself.

The following JSON included in the payload illustrates the fullest representation of the playerStats 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":"playerStats","method":"POST","action":"create","appVersion":"Version","rowCount":1,"playerStats":{"id":"ID","userId":"ID","eloRating":"Integer","totalGames":"Integer","wins":"Integer","losses":"Integer","draws":"Integer","streak":"Integer","lastGameAt":"Date","username":"String","isActive":true,"recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}}

Route Event playerstats-updated

Event topic : wechess-leaderboard-service-playerstats-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 playerStats data object itself.

The following JSON included in the payload illustrates the fullest representation of the playerStats 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":"playerStats","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"playerStats":{"id":"ID","userId":"ID","eloRating":"Integer","totalGames":"Integer","wins":"Integer","losses":"Integer","draws":"Integer","streak":"Integer","lastGameAt":"Date","username":"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 playerStats

Service Design Specification - Object Design for playerStats

wechess-leaderboard-service documentation

Document Overview

This document outlines the object design for the playerStats model in our application. It includes details about the model’s attributes, relationships, and any specific validation or business logic that applies.

playerStats Data Object

Object Overview

Description: Stores aggregate stats for a registered chess player: ELO, win/loss history, streak, last game, etc. Excludes guests. One per registered user.

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
userId ID Yes The registered user this record belongs to (auth:user.id).
eloRating Integer Yes Current ELO rating for registered player.
totalGames Integer Yes Total completed games (wins + losses + draws) for this player.
wins Integer Yes Number of games won by the player.
losses Integer Yes Number of games lost by the player.
draws Integer Yes Number of drawn games by the player.
streak Integer Yes Current win or loss streak. Positive=win streak, negative=loss streak, 0=none/neutral.
lastGameAt Date No Timestamp of last completed game for user.
username String No Display name for the player, publicly visible.

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

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

eloRating totalGames wins losses draws streak lastGameAt username

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 eloRating totalGames wins losses draws streak lastGameAt username

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 eloRating totalGames wins losses draws streak

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

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

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

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


Service Design Specification - Object Design for leaderboardEntry

Service Design Specification - Object Design for leaderboardEntry

wechess-leaderboard-service documentation

Document Overview

This document outlines the object design for the leaderboardEntry model in our application. It includes details about the model’s attributes, relationships, and any specific validation or business logic that applies.

leaderboardEntry Data Object

Object Overview

Description: Holds global leaderboard standings for registered players. Rank, ELO, and season support. Excludes guests.

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
userId ID Yes The registered user this leaderboard entry represents.
currentRank Integer Yes Current leaderboard rank (1=top). Lower is better.
eloRating Integer Yes Player's current ELO rating (copy from playerStats).
season String No Leaderboard season identifier (null for all-time/global, can be set for seasonal leaderboards as needed).
lastRankChangeAt Date No Timestamp of last rank change/leaderboard update.
username String No Display name for the player, publicly visible on leaderboard.

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

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

currentRank eloRating season lastRankChangeAt username

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 currentRank eloRating season lastRankChangeAt username

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 currentRank eloRating

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

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

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

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


Business APIs

Business API Design Specification - Create Playerstats

Business API Design Specification - Create Playerstats

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 createPlayerStats 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 createPlayerStats Business API is designed to handle a create operation on the PlayerStats 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 player stats record for a newly registered player. Only registered users (never guests) should have this object. Typically used at registration or conversion.

API Frontend Description By The Backend Architect

Called only at registration or on converting guest to registered. Prepares stats for profile display.

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 createPlayerStats Business API includes a REST controller that can be triggered via the following route:

/v1/playerstatses

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 createPlayerStats Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The createPlayerStats Business API has 10 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
playerStatsId ID No - body playerStatsId
Description: This id paremeter is used to create the data object with a given specific id. Leave null for automatic id.
userId ID Yes - body userId
Description: The registered user this record belongs to (auth:user.id).
eloRating Integer Yes - body eloRating
Description: Current ELO rating for registered player.
totalGames Integer Yes - body totalGames
Description: Total completed games (wins + losses + draws) for this player.
wins Integer Yes - body wins
Description: Number of games won by the player.
losses Integer Yes - body losses
Description: Number of games lost by the player.
draws Integer Yes - body draws
Description: Number of drawn games by the player.
streak Integer Yes - body streak
Description: Current win or loss streak. Positive=win streak, negative=loss streak, 0=none/neutral.
lastGameAt Date No - body lastGameAt
Description: Timestamp of last completed game for user.
username String No - body username
Description: Display name for the player, publicly visible.

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 createPlayerStats 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.playerStatsId,
  userId: this.userId,
  eloRating: this.eloRating,
  totalGames: this.totalGames,
  wins: this.wins,
  losses: this.losses,
  draws: this.draws,
  streak: this.streak,
  lastGameAt: this.lastGameAt,
  username: this.username,
  isActive: true,
  _archivedAt: null,
}

Business Logic Workflow

[1] Step : startBusinessApi

Manager initializes context, populates session and request objects, prepares internal structures for parameter handling and workflow execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Manager reads input parameters, normalizes missing values, applies default type casting, and stores them in the API context.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Manager transforms parameters, computes derived values, flattens or remaps arrays/objects, and adjusts formats for downstream processing.


[4] Step : checkParameters

Manager executes built-in validations: required field checks, type enforcement, and basic business rules. Prevents operation if validation fails.


[5] Step : checkBasicAuth

Manager performs authentication and authorization checks: verifies session, user roles, permissions, and tenant restrictions.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildDataClause

Manager constructs the final data object for creation, fills auto-generated fields (IDs, timestamps, owner fields), and ensures schema consistency.

You can use the following settings to change some behavior of this step. dataClause

[7] Step : mainCreateOperation

Manager executes the database insert operation, updates indexes/caches, and triggers internal post-processing like linked default records.


[8] Action : createLeaderboardEntry

Action Type: CreateCrudAction

Auto-create a leaderboard entry when player stats are created so the player appears on the leaderboard.

class Api {
  async createLeaderboardEntry() {
    // Aggregated Update Operation on childObject leaderboardEntry

    const params = {
      userId: runMScript(() => this.userId, {
        path: "services[3].businessLogic[0].actions.createCrudActions[0].dataClause[0].dataValue",
      }),
      currentRank: runMScript(() => 9999, {
        path: "services[3].businessLogic[0].actions.createCrudActions[0].dataClause[1].dataValue",
      }),
      eloRating: runMScript(() => this.eloRating, {
        path: "services[3].businessLogic[0].actions.createCrudActions[0].dataClause[2].dataValue",
      }),
      username: runMScript(() => this.username, {
        path: "services[3].businessLogic[0].actions.createCrudActions[0].dataClause[3].dataValue",
      }),
    };

    return await createLeaderboardEntry(params, this);
  }
}

[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 createPlayerStats api has got 9 regular client parameters

Parameter Type Required Population
userId ID true request.body?.[“userId”]
eloRating Integer true request.body?.[“eloRating”]
totalGames Integer true request.body?.[“totalGames”]
wins Integer true request.body?.[“wins”]
losses Integer true request.body?.[“losses”]
draws Integer true request.body?.[“draws”]
streak Integer true request.body?.[“streak”]
lastGameAt Date false request.body?.[“lastGameAt”]
username String false request.body?.[“username”]

REST Request

To access the api you can use the REST controller with the path POST /v1/playerstatses

  axios({
    method: 'POST',
    url: '/v1/playerstatses',
    data: {
            userId:"ID",  
            eloRating:"Integer",  
            totalGames:"Integer",  
            wins:"Integer",  
            losses:"Integer",  
            draws:"Integer",  
            streak:"Integer",  
            lastGameAt:"Date",  
            username:"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 playerStats 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": "playerStats",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"playerStats": {
		"id": "ID",
		"userId": "ID",
		"eloRating": "Integer",
		"totalGames": "Integer",
		"wins": "Integer",
		"losses": "Integer",
		"draws": "Integer",
		"streak": "Integer",
		"lastGameAt": "Date",
		"username": "String",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Business API Design Specification - Update Playerstats

Business API Design Specification - Update Playerstats

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 updatePlayerStats 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 updatePlayerStats Business API is designed to handle a update operation on the PlayerStats data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

Update player statistics when a game completes. Only called for registered users by gameplay service (M2M) or admin; guests not allowed.

API Frontend Description By The Backend Architect

System/gameplay triggers this to update stats at game end. Never called for guests.

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 updatePlayerStats Business API includes a REST controller that can be triggered via the following route:

/v1/playerstatses/:playerStatsId

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 updatePlayerStats Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The updatePlayerStats Business API has 9 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client.

Business API parameters can be:

Regular Parameters

Name Type Required Default Location Data Path
playerStatsId ID Yes - urlpath playerStatsId
Description: This id paremeter is used to select the required data object that will be updated
eloRating Integer Yes - body eloRating
Description: Current ELO rating for registered player.
totalGames Integer Yes - body totalGames
Description: Total completed games (wins + losses + draws) for this player.
wins Integer Yes - body wins
Description: Number of games won by the player.
losses Integer Yes - body losses
Description: Number of games lost by the player.
draws Integer Yes - body draws
Description: Number of drawn games by the player.
streak Integer Yes - body streak
Description: Current win or loss streak. Positive=win streak, negative=loss streak, 0=none/neutral.
lastGameAt Date No - body lastGameAt
Description: Timestamp of last completed game for user.
username String No - body username
Description: Display name for the player, publicly visible.

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 updatePlayerStats Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({$and:[{id:this.playerStatsId},{isActive:true}]}), {"path":"services[3].businessLogic[1].whereClause.fullWhereClause"})

Data Clause

Defines custom field-value assignments used to modify or augment the default payload for create and update operations. These settings override values derived from the session or parameters if explicitly provided.", Note that a default data clause is always prepared by Mindbricks using data property settings, however any property in the data clause can be override by Data Clause Settings.

An update data clause populates all update-allowed properties of a data object, however the null properties (that are not provided by client) are ignored in db layer.

Custom Data Clause Override No custom data clause override configured

Actual Data Clause

The business api will use the following data clause. Note that any calculated value will be added to the data clause in the api manager.

{
  eloRating: this.eloRating,
  totalGames: this.totalGames,
  wins: this.wins,
  losses: this.losses,
  draws: this.draws,
  streak: this.streak,
  lastGameAt: this.lastGameAt,
  username: this.username,
}

Business Logic Workflow

[1] Step : startBusinessApi

Manager initializes context, prepares request and session objects, and sets up internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Action : checkUserIsRegisteredPlayer

Action Type: FunctionCallAction

Fails if target userId is not registeredPlayer (prevents guests being updated).

class Api {
  async checkUserIsRegisteredPlayer() {
    try {
      return runMScript(() => LIB.failIfNotRegisteredPlayer(this.userId), {
        path: "services[3].businessLogic[1].actions.functionCallActions[0].callScript",
      });
    } catch (err) {
      console.error(
        "Error in FunctionCallAction checkUserIsRegisteredPlayer:",
        err,
      );
      throw err;
    }
  }
}

[3] Step : readParameters

Manager reads parameters from the request or Redis, applies defaults, and writes them into context for downstream milestones.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[4] Step : transposeParameters

Manager executes parameter transform scripts and derives any helper values or reshaped payloads into the context.


[5] Step : checkParameters

Manager validates required parameters, checks ID formats (UUID/ObjectId), and ensures all preconditions for update are met.


[6] Step : checkBasicAuth

Manager performs login verification, role, and permission checks, enforcing tenant and access rules before update.

You can use the following settings to change some behavior of this step. authOptions

[7] Step : buildWhereClause

Manager constructs the WHERE clause used to identify the record to update, applying ownership and parent checks if necessary.

You can use the following settings to change some behavior of this step. whereClause

[8] Step : fetchInstance

Manager fetches the existing record from the database and writes it to the context for validation or enrichment.


[9] Step : checkInstance

Manager performs instance-level validations, including ownership, existence, lock status, or other pre-update checks.


[10] Step : buildDataClause

Manager prepares the data clause for the update, applying transformations or enhancements before persisting.

You can use the following settings to change some behavior of this step. dataClause

[11] Step : mainUpdateOperation

Manager executes the update operation with the WHERE and data clauses. Database-level events are raised if configured.


[12] Action : syncLeaderboardElo

Action Type: UpdateCrudAction

Sync the updated ELO rating into the player’s leaderboardEntry so rankings stay up to date.

class Api {
  async syncLeaderboardElo() {
    // Aggregated Update Operation on childObject leaderboardEntry

    const params = {
      eloRating: runMScript(() => this.eloRating, {
        path: "services[3].businessLogic[1].actions.updateCrudActions[0].dataClause[0].dataValue",
      }),
      lastRankChangeAt: runMScript(() => new Date(), {
        path: "services[3].businessLogic[1].actions.updateCrudActions[0].dataClause[1].dataValue",
      }),
      username: runMScript(() => this.username || this.playerStats.username, {
        path: "services[3].businessLogic[1].actions.updateCrudActions[0].dataClause[2].dataValue",
      }),
    };
    const userQuery = runMScript(() => ({ userId: this.playerStats.userId }), {
      path: "services[3].businessLogic[1].actions.updateCrudActions[0].whereClause",
    });

    const { convertUserQueryToSequelizeQuery } = require("common");
    const query = convertUserQueryToSequelizeQuery(userQuery);

    const result = await updateLeaderboardEntryByQuery(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.playerStats = this.dbResult;
        }
      }
    }
    if (result.length == 0) return null;
    if (result.length == 1) return result[0];
    return result;
  }
}

[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 updatePlayerStats api has got 9 regular client parameters

Parameter Type Required Population
playerStatsId ID true request.params?.[“playerStatsId”]
eloRating Integer true request.body?.[“eloRating”]
totalGames Integer true request.body?.[“totalGames”]
wins Integer true request.body?.[“wins”]
losses Integer true request.body?.[“losses”]
draws Integer true request.body?.[“draws”]
streak Integer true request.body?.[“streak”]
lastGameAt Date false request.body?.[“lastGameAt”]
username String false request.body?.[“username”]

REST Request

To access the api you can use the REST controller with the path PATCH /v1/playerstatses/:playerStatsId

  axios({
    method: 'PATCH',
    url: `/v1/playerstatses/${playerStatsId}`,
    data: {
            eloRating:"Integer",  
            totalGames:"Integer",  
            wins:"Integer",  
            losses:"Integer",  
            draws:"Integer",  
            streak:"Integer",  
            lastGameAt:"Date",  
            username:"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 playerStats 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": "playerStats",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"playerStats": {
		"id": "ID",
		"userId": "ID",
		"eloRating": "Integer",
		"totalGames": "Integer",
		"wins": "Integer",
		"losses": "Integer",
		"draws": "Integer",
		"streak": "Integer",
		"lastGameAt": "Date",
		"username": "String",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Business API Design Specification - Get Playerstats

Business API Design Specification - Get Playerstats

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 getPlayerStats 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 getPlayerStats Business API is designed to handle a get operation on the PlayerStats 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 registered user’s player stats (private to user or admin).

API Frontend Description By The Backend Architect

Used to display profile stats. User can only view own; admin can view any.

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 getPlayerStats Business API includes a REST controller that can be triggered via the following route:

/v1/playerstatses/: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 getPlayerStats Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The getPlayerStats 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: The registered user this record belongs to (auth:user.id)… 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 getPlayerStats 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,username,eloRating,totalGames,wins,losses,draws,streak,lastGameAt

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.

runMScript(() => ({$and:[{userId:{"$eq":this.userId}},{isActive:true}]}), {"path":"services[3].businessLogic[2].whereClause.fullWhereClause"})

Get Options

Use these options to set get specific settings.

setAsRead: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed.

No setAsread field-value pair is configured.

Business Logic Workflow

[1] Step : startBusinessApi

Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Extracts parameters from request and Redis, applies defaults, and writes them to context.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Executes parameter transformation scripts, applies type coercion, merges derived values, and reshapes inputs for downstream milestones.


[4] Step : checkParameters

Validates required and custom parameters, enforcing business-specific rules and constraints.


[5] Step : checkBasicAuth

Performs login, role, and permission checks, and applies dynamic object-level access rules.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildWhereClause

Builds the WHERE clause for fetching the object and applies additional scoped filters if configured.

You can use the following settings to change some behavior of this step. whereClause

[7] Step : mainGetOperation

Executes the database fetch, retrieves the object, and stores it in context for enrichment or further checks.

You can use the following settings to change some behavior of this step. selectClause, getOptions

[8] Step : checkInstance

Performs instance-level validations, such as ownership, existence, or access conditions.


[9] Step : buildOutput

Assembles the response from the object, applies masking, formatting, and injects additional metadata if needed.


[10] Step : sendResponse

Delivers the response to the controller for client delivery.


[11] Step : raiseApiEvent

Triggers optional API-level events after workflow completion, sending messages to integrations like Kafka if configured.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The getPlayerStats 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/playerstatses/:userId

  axios({
    method: 'GET',
    url: `/v1/playerstatses/${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 playerStats 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": "playerStats",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"playerStats": {
		"isActive": true
	}
}

Business API Design Specification - Get Leaderboardentry

Business API Design Specification - Get Leaderboardentry

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 getLeaderboardEntry 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 getLeaderboardEntry Business API is designed to handle a get operation on the LeaderboardEntry data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

Fetch this player’s leaderboard rank entry (registered users only).

API Frontend Description By The Backend Architect

Allow user to view their own leaderboard position (or admin to view any user). Entry includes user info for display.

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 getLeaderboardEntry Business API includes a REST controller that can be triggered via the following route:

/v1/leaderboardentries/: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 getLeaderboardEntry Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The getLeaderboardEntry 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: The registered user this leaderboard entry represents… 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 getLeaderboardEntry 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,username,currentRank,eloRating,season,lastRankChangeAt

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.

runMScript(() => ({$and:[{userId:{"$eq":this.userId}},{isActive:true}]}), {"path":"services[3].businessLogic[3].whereClause.fullWhereClause"})

Get Options

Use these options to set get specific settings.

setAsRead: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed.

No setAsread field-value pair is configured.

Business Logic Workflow

[1] Step : startBusinessApi

Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Extracts parameters from request and Redis, applies defaults, and writes them to context.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Executes parameter transformation scripts, applies type coercion, merges derived values, and reshapes inputs for downstream milestones.


[4] Step : checkParameters

Validates required and custom parameters, enforcing business-specific rules and constraints.


[5] Step : checkBasicAuth

Performs login, role, and permission checks, and applies dynamic object-level access rules.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildWhereClause

Builds the WHERE clause for fetching the object and applies additional scoped filters if configured.

You can use the following settings to change some behavior of this step. whereClause

[7] Step : mainGetOperation

Executes the database fetch, retrieves the object, and stores it in context for enrichment or further checks.

You can use the following settings to change some behavior of this step. selectClause, getOptions

[8] Step : checkInstance

Performs instance-level validations, such as ownership, existence, or access conditions.


[9] Step : buildOutput

Assembles the response from the object, applies masking, formatting, and injects additional metadata if needed.


[10] Step : sendResponse

Delivers the response to the controller for client delivery.


[11] Step : raiseApiEvent

Triggers optional API-level events after workflow completion, sending messages to integrations like Kafka if configured.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The getLeaderboardEntry 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/leaderboardentries/:userId

  axios({
    method: 'GET',
    url: `/v1/leaderboardentries/${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 leaderboardEntry 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": "leaderboardEntry",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"leaderboardEntry": {
		"isActive": true
	}
}

Business API Design Specification - List Leaderboardtopn

Business API Design Specification - List Leaderboardtopn

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 listLeaderboardTopN 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 listLeaderboardTopN Business API is designed to handle a list operation on the LeaderboardEntry data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

List top N players for leaderboard display (e.g., leaderboard page top 100). Sorted by currentRank ascending (best = 1).

API Frontend Description By The Backend Architect

Leaderboard screen populates using this API; accessible to all authenticated users (guests see empty/null result).

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 listLeaderboardTopN Business API includes a REST controller that can be triggered via the following route:

/v1/leaderboardtopn

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 listLeaderboardTopN Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The listLeaderboardTopN 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
topN Integer No 100 query topN
Description: Number of top players to return (max 500)

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 listLeaderboardTopN 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,username,currentRank,eloRating,season,lastRankChangeAt

Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({isActive:true}), {"path":"services[3].businessLogic[4].whereClause.fullWhereClause"})

List Options

Defines list-specific options including filtering logic, default sorting, and result customization for APIs that return multiple records.

List Sort By Sort order definitions for the result set. Multiple fields can be provided with direction (asc/desc).

[ eloRating desc,currentRank asc ]

List Group By Grouping definitions for the result set. This is typically used for visual or report-based grouping.

The list is not grouped.

setAsRead: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed.

No setAsread field-value pair is configured.

Permission Filter Optional filter that applies permission constraints dynamically based on session or object roles. So that the list items are filtered by the user’s OBAC or ABAC permissions.

Permission filter is not active at the moment. Follow Mindbricks updates to be able to use it.

Pagination Options

Contains settings to configure pagination behavior for list APIs. Includes options like page size, offset, cursor support, and total count inclusion.

Business Logic Workflow

[1] Step : startBusinessApi

Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Reads request and Redis parameters, applies defaults, and writes them to context for downstream processing.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Transforms and normalizes parameters, derives dependent values, and reshapes inputs for the main list query.


[4] Step : checkParameters

Executes validation logic on required and custom parameters, enforcing business rules and cross-field consistency.


[5] Step : checkBasicAuth

Performs role-based access checks and applies dynamic membership or session-based restrictions.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildWhereClause

Constructs the main query WHERE clause and applies optional filters or scoped access controls.

You can use the following settings to change some behavior of this step. whereClause

[7] Step : mainListOperation

Executes the paginated database query, retrieves the list, and stores results in context for enrichment.

You can use the following settings to change some behavior of this step. selectClause, listOptions, paginationOptions

[8] Step : buildOutput

Assembles the list response, sanitizes sensitive fields, applies transformations, and injects extra context if needed.


[9] Step : sendResponse

Sends the paginated list to the client through the controller.


[10] Step : raiseApiEvent

Triggers optional post-workflow events, such as Kafka messages, logs, or system notifications.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The listLeaderboardTopN api has got 1 regular client parameter

Parameter Type Required Population
topN Integer false request.query?.[“topN”]

REST Request

To access the api you can use the REST controller with the path GET /v1/leaderboardtopn

  axios({
    method: 'GET',
    url: '/v1/leaderboardtopn',
    data: {
    
    },
    params: {
             topN:'"Integer"',  
    
        }
  });

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 leaderboardEntries 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": "leaderboardEntries",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"leaderboardEntries": [
		{
			"isActive": true
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Business API Design Specification - Create Leaderboardentry

Business API Design Specification - Create Leaderboardentry

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 createLeaderboardEntry 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 createLeaderboardEntry Business API is designed to handle a create operation on the LeaderboardEntry 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 leaderboard entry for a registered player. Called when PlayerStats exists but LeaderboardEntry is missing.

API Frontend Description By The Backend Architect

Called by ensureLeaderboardEntry when a user has PlayerStats but no LeaderboardEntry.

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 createLeaderboardEntry Business API includes a REST controller that can be triggered via the following route:

/v1/leaderboardentries

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 createLeaderboardEntry Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The createLeaderboardEntry 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
leaderboardEntryId ID No - body leaderboardEntryId
Description: This id paremeter is used to create the data object with a given specific id. Leave null for automatic id.
userId ID Yes - body userId
Description: The registered user this leaderboard entry represents.
currentRank Integer Yes - body currentRank
Description: Current leaderboard rank (1=top). Lower is better.
eloRating Integer Yes - body eloRating
Description: Player’s current ELO rating (copy from playerStats).
season String No - body season
Description: Leaderboard season identifier (null for all-time/global, can be set for seasonal leaderboards as needed).
lastRankChangeAt Date No - body lastRankChangeAt
Description: Timestamp of last rank change/leaderboard update.
username String No - body username
Description: Display name for the player, publicly visible on leaderboard.

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 createLeaderboardEntry 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.leaderboardEntryId,
  userId: this.userId,
  currentRank: this.currentRank,
  eloRating: this.eloRating,
  season: this.season,
  lastRankChangeAt: this.lastRankChangeAt,
  username: this.username,
  isActive: true,
  _archivedAt: null,
}

Business Logic Workflow

[1] Step : startBusinessApi

Manager initializes context, populates session and request objects, prepares internal structures for parameter handling and workflow execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Manager reads input parameters, normalizes missing values, applies default type casting, and stores them in the API context.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Manager transforms parameters, computes derived values, flattens or remaps arrays/objects, and adjusts formats for downstream processing.


[4] Step : checkParameters

Manager executes built-in validations: required field checks, type enforcement, and basic business rules. Prevents operation if validation fails.


[5] Step : checkBasicAuth

Manager performs authentication and authorization checks: verifies session, user roles, permissions, and tenant restrictions.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildDataClause

Manager constructs the final data object for creation, fills auto-generated fields (IDs, timestamps, owner fields), and ensures schema consistency.

You can use the following settings to change some behavior of this step. dataClause

[7] Step : mainCreateOperation

Manager executes the database insert operation, updates indexes/caches, and triggers internal post-processing like linked default records.


[8] Step : buildOutput

Manager shapes the response: masks sensitive fields, resolves linked references, and formats output according to API contract.


[9] Step : sendResponse

Manager sends the response to the client and finalizes internal tasks like flushing logs or updating session state.


[10] Step : raiseApiEvent

Manager triggers API-level events (Kafka, WebSocket, async workflows) as the final internal step.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The createLeaderboardEntry api has got 6 regular client parameters

Parameter Type Required Population
userId ID true request.body?.[“userId”]
currentRank Integer true request.body?.[“currentRank”]
eloRating Integer true request.body?.[“eloRating”]
season String false request.body?.[“season”]
lastRankChangeAt Date false request.body?.[“lastRankChangeAt”]
username String false request.body?.[“username”]

REST Request

To access the api you can use the REST controller with the path POST /v1/leaderboardentries

  axios({
    method: 'POST',
    url: '/v1/leaderboardentries',
    data: {
            userId:"ID",  
            currentRank:"Integer",  
            eloRating:"Integer",  
            season:"String",  
            lastRankChangeAt:"Date",  
            username:"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 leaderboardEntry 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": "leaderboardEntry",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"leaderboardEntry": {
		"id": "ID",
		"userId": "ID",
		"currentRank": "Integer",
		"eloRating": "Integer",
		"season": "String",
		"lastRankChangeAt": "Date",
		"username": "String",
		"isActive": true,
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID"
	}
}

Event Subscriptions

Event Subscription Design Specification - gameEvents

Event Subscription Design Specification - gameEvents

This document provides a detailed architectural overview of the gameEvents event subscription within the leaderboard service. It covers the subscription’s transport configuration, topic definitions, authorization model, and payload transformations.

Subscription Overview

Description: Subscribes to gameplay events so the leaderboard can update ELO ratings, player stats, and rankings when games are completed.

Topics

This subscription exposes 1 Kafka topic to connected clients:

gameCompleted

Fires when a chess game is updated (status changes to completed/terminated). Used to trigger ELO recalculation and leaderboard rank updates for both players.

Excluded Fields

The following fields are stripped from the payload before sending to clients: invitationCode

Authorization

The subscription uses a layered authorization model that controls which users can connect and which topics they receive:

Absolute Roles

Users with roles administrator bypass all authorization checks and receive all topics without filtering.

Event Filter Script

Evaluated for each incoming Kafka event before delivery. Returns false to skip the event for the user:

data.result != null && (data.status == 'completed' || data.status == 'terminated')

Context variables: session, topicName, dataObjectName, data

Client Integration

WebSocket Connection (Socket.IO)

import { io } from 'socket.io-client';

const socket = io('/events/gameEvents', {
  auth: { token: 'your-jwt-token' }
});

// Subscribe to specific topics
socket.on('gameCompleted', (data) => {
  console.log('gameCompleted event:', data);
});


socket.on('connect', () => console.log('Connected to gameEvents'));
socket.on('disconnect', () => console.log('Disconnected from gameEvents'));

This document was generated from the event subscription configuration and should be kept in sync with design changes.


Service Library - leaderboard

Service Library - leaderboard

This document provides a complete reference of the custom code library for the leaderboard service. It includes all library functions, edge functions with their REST endpoints, templates, and assets.

Library Functions

Library functions are reusable modules available to all business APIs and other custom code within the service via require("lib/<moduleName>").

failIfNotRegisteredPlayer.js

module.exports = async function failIfNotRegisteredPlayer(userId, context=null) {
    // fetch user role via serviceCommon helper
    const { fetchRemoteObjectByMQuery } = require("serviceCommon");
    const user = await fetchRemoteObjectByMQuery("User", { id: userId });
    if (!user) throw new Error("User does not exist.");
    if (user.roleId !== "registeredPlayer" && user.roleId !== "administrator") throw new Error("Leaderboard and stats are only for registered users.");
    return true;
}

This document was generated from the service library configuration and should be kept in sync with design changes.


AgentHub Service

Service Design Specification

Service Design Specification

wechess-agenthub-service documentation Version: 1.0.0

Scope

This document provides a structured architectural overview of the agentHub microservice, detailing its configuration, data model, authorization logic, business rules, and API design. It has been automatically generated based on the service definition within Mindbricks, ensuring that the information reflects the source of truth used during code generation and deployment.

The document is intended to serve multiple audiences:

Note for Frontend Developers: While this document is valuable for understanding business logic and data interactions, please refer to the Service API Documentation for endpoint-level specifications and integration details.

Note for Backend Developers: Since the code for this service is automatically generated by Mindbricks, you typically won’t need to implement or modify it manually. However, this document is especially valuable when you’re building other services—whether within Mindbricks or externally—that need to interact with or depend on this service. It provides a clear reference to the service’s data contracts, business rules, and API structure, helping ensure compatibility and correct integration.

AgentHub Service Settings

AI Agent Hub

Service Overview

This service is configured to listen for HTTP requests on port 3006, serving both the main API interface and default administrative endpoints.

The following routes are available by default:

The service uses a PostgreSQL database for data storage, with the database name set to wechess-agenthub-service.

This service is accessible via the following environment-specific URLs:

Authentication & Security

This service requires user authentication for access. It supports both JWT and RSA-based authentication mechanisms, ensuring secure user sessions and data integrity. If a crud route also is configured to require login, it will check a valid JWT token in the request query/header/bearer/cookie. If the token is valid, it will extract the user information from the token and make the fetched session data available in the request context.

Service Data Objects

The service uses a PostgreSQL database for data storage, with the database name set to wechess-agenthub-service.

Data deletion is managed using a soft delete strategy. Instead of removing records from the database, they are flagged as inactive by setting the isActive field to false.

Object Name Description Public Access
sys_agentOverride Runtime overrides for design-time agents. Null fields use the design default. accessProtected
sys_agentExecution Agent execution log. Records each agent invocation with input, output, and performance metrics. accessProtected
sys_toolCatalog Cached tool catalog discovered from project services. Refreshed periodically. accessProtected

sys_agentOverride Data Object

Object Overview

Description: Runtime overrides for design-time agents. Null fields use the design default.

This object represents a core data structure within the service and acts as the blueprint for database interaction, API generation, and business logic enforcement. It is defined using the ObjectSettings pattern, which governs its behavior, access control, caching strategy, and integration points with other systems such as Stripe and Redis.

Core Configuration

Properties Schema

Property Type Required Description
agentName String Yes Design-time agent name this override applies to.
provider String No Override AI provider (e.g., openai, anthropic).
model String No Override model name.
systemPrompt Text No Override system prompt.
temperature Double No Override temperature (0-2).
maxTokens Integer No Override max tokens.
responseFormat String No Override response format (text/json).
selectedTools Object No Array of tool names from the catalog that this agent can use.
guardrails Object No Override guardrails: { maxToolCalls, timeout, maxTokenBudget }.
enabled Boolean Yes Enable or disable this agent.
updatedBy ID No User who last updated this override.

Default Values

Default values are automatically assigned to properties when a new object is created, if no value is provided in the request body. Since default values are applied on db level, they should be literal values, not expressions.If you want to use expressions, you can use transposed parameters in any business API to set default values dynamically.

Always Create with Default Values

Some of the default values are set to be always used when creating a new object, even if the property value is provided in the request body. It ensures that the property is always initialized with a default value when the object is created.

Constant Properties

agentName

Constant properties are defined to be immutable after creation, meaning they cannot be updated or changed once set. They are typically used for properties that should remain constant throughout the object’s lifecycle. A property is set to be constant if the Allow Update option is set to false.

Auto Update Properties

agentName provider model systemPrompt temperature maxTokens responseFormat selectedTools guardrails enabled updatedBy

An update crud API created with the option Auto Params enabled will automatically update these properties with the provided values in the request body. If you want to update any property in your own business logic not by user input, you can set the Allow Auto Update option to false. These properties will be added to the update API’s body parameters and can be updated by the user if any value is provided in the request body.

Elastic Search Indexing

agentName enabled

Properties that are indexed in Elastic Search will be searchable via the Elastic Search API. While all properties are stored in the elastic search index of the data object, only those marked for Elastic Search indexing will be available for search queries.

Database Indexing

agentName enabled

Properties that are indexed in the database will be optimized for query performance, allowing for faster data retrieval. Make a property indexed in the database if you want to use it frequently in query filters or sorting.

Unique Properties

agentName

Unique properties are enforced to have distinct values across all instances of the data object, preventing duplicate entries. Note that a unique property is automatically indexed in the database so you will not need to set the Indexed in DB option.

Session Data Properties

updatedBy

Session data properties are used to store data that is specific to the user session, allowing for personalized experiences and temporary data storage. If a property is configured as session data, it will be automatically mapped to the related field in the user session during CRUD operations. Note that session data properties can not be mutated by the user, but only by the system.

sys_agentExecution Data Object

Object Overview

Description: Agent execution log. Records each agent invocation with input, output, and performance metrics.

This object represents a core data structure within the service and acts as the blueprint for database interaction, API generation, and business logic enforcement. It is defined using the ObjectSettings pattern, which governs its behavior, access control, caching strategy, and integration points with other systems such as Stripe and Redis.

Core Configuration

Properties Schema

Property Type Required Description
agentName String Yes Agent that was executed.
agentType Enum Yes Whether this was a design-time or dynamic agent.
source Enum Yes How the agent was triggered.
userId ID No User who triggered the execution.
input Object No Request input (truncated for large payloads).
output Object No Response output (truncated for large payloads).
toolCalls Integer No Number of tool calls made during execution.
tokenUsage Object No Token usage: { prompt, completion, total }.
durationMs Integer No Execution time in milliseconds.
status Enum Yes Execution status.
error Text No Error message if execution failed.

Default Values

Default values are automatically assigned to properties when a new object is created, if no value is provided in the request body. Since default values are applied on db level, they should be literal values, not expressions.If you want to use expressions, you can use transposed parameters in any business API to set default values dynamically.

Constant Properties

agentName agentType source userId input output toolCalls tokenUsage durationMs status error

Constant properties are defined to be immutable after creation, meaning they cannot be updated or changed once set. They are typically used for properties that should remain constant throughout the object’s lifecycle. A property is set to be constant if the Allow Update option is set to false.

Auto Update Properties

agentName agentType source userId input output toolCalls tokenUsage durationMs status error

An update crud API created with the option Auto Params enabled will automatically update these properties with the provided values in the request body. If you want to update any property in your own business logic not by user input, you can set the Allow Auto Update option to false. These properties will be added to the update API’s body parameters and can be updated by the user if any value is provided in the request body.

Enum Properties

Enum properties are defined with a set of allowed values, ensuring that only valid options can be assigned to them. The enum options value will be stored as strings in the database, but when a data object is created an addtional property with the same name plus an idx suffix will be created, which will hold the index of the selected enum option. You can use the index property to sort by the enum value or when your enum options represent a sequence of values.

Elastic Search Indexing

agentName agentType source userId toolCalls durationMs status

Properties that are indexed in Elastic Search will be searchable via the Elastic Search API. While all properties are stored in the elastic search index of the data object, only those marked for Elastic Search indexing will be available for search queries.

Database Indexing

agentName agentType source userId status

Properties that are indexed in the database will be optimized for query performance, allowing for faster data retrieval. Make a property indexed in the database if you want to use it frequently in query filters or sorting.

Filter Properties

agentName agentType source userId status

Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API’s that have “Auto Params” enabled.

sys_toolCatalog Data Object

Object Overview

Description: Cached tool catalog discovered from project services. Refreshed periodically.

This object represents a core data structure within the service and acts as the blueprint for database interaction, API generation, and business logic enforcement. It is defined using the ObjectSettings pattern, which governs its behavior, access control, caching strategy, and integration points with other systems such as Stripe and Redis.

Core Configuration

Properties Schema

Property Type Required Description
toolName String Yes Full tool name (e.g., service:apiName).
serviceName String Yes Source service name.
description Text No Tool description.
parameters Object No JSON Schema of tool parameters.
lastRefreshed Date No When this tool was last discovered/refreshed.

Default Values

Default values are automatically assigned to properties when a new object is created, if no value is provided in the request body. Since default values are applied on db level, they should be literal values, not expressions.If you want to use expressions, you can use transposed parameters in any business API to set default values dynamically.

Auto Update Properties

toolName serviceName description parameters lastRefreshed

An update crud API created with the option Auto Params enabled will automatically update these properties with the provided values in the request body. If you want to update any property in your own business logic not by user input, you can set the Allow Auto Update option to false. These properties will be added to the update API’s body parameters and can be updated by the user if any value is provided in the request body.

Elastic Search Indexing

toolName serviceName description

Properties that are indexed in Elastic Search will be searchable via the Elastic Search API. While all properties are stored in the elastic search index of the data object, only those marked for Elastic Search indexing will be available for search queries.

Database Indexing

toolName serviceName

Properties that are indexed in the database will be optimized for query performance, allowing for faster data retrieval. Make a property indexed in the database if you want to use it frequently in query filters or sorting.

Unique Properties

toolName

Unique properties are enforced to have distinct values across all instances of the data object, preventing duplicate entries. Note that a unique property is automatically indexed in the database so you will not need to set the Indexed in DB option.

Filter Properties

serviceName

Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API’s that have “Auto Params” enabled.

Business Logic

agentHub has got 9 Business APIs to manage its internal and crud logic. For the details of each business API refer to its chapter.


This document was generated from the service architecture definition and should be kept in sync with implementation changes.


REST API GUIDE

REST API GUIDE

wechess-agenthub-service

Version: 1.0.0

AI Agent Hub

Architectural Design Credit and Contact Information

The architectural design of this microservice is credited to . For inquiries, feedback, or further information regarding the architecture, please direct your communication to:

Email:

We encourage open communication and welcome any questions or discussions related to the architectural aspects of this microservice.

Documentation Scope

Welcome to the official documentation for the AgentHub Service’s REST API. This document is designed to provide a comprehensive guide to interfacing with our AgentHub Service exclusively through RESTful API endpoints.

Intended Audience

This documentation is intended for developers and integrators who are looking to interact with the AgentHub Service via HTTP requests for purposes such as creating, updating, deleting and querying AgentHub objects.

Overview

Within these pages, you will find detailed information on how to effectively utilize the REST API, including authentication methods, request and response formats, endpoint descriptions, and examples of common use cases.

Beyond REST It’s important to note that the AgentHub Service also supports alternative methods of interaction, such as gRPC and messaging via a Message Broker. These communication methods are beyond the scope of this document. For information regarding these protocols, please refer to their respective documentation.

Authentication And Authorization

To ensure secure access to the AgentHub service’s protected endpoints, a project-wide access token is required. This token serves as the primary method for authenticating requests to our service. However, it’s important to note that access control varies across different routes:

Protected API: Certain API (routes) require specific authorization levels. Access to these routes is contingent upon the possession of a valid access token that meets the route-specific authorization criteria. Unauthorized requests to these routes will be rejected.

**Public API **: The service also includes public API (routes) that are accessible without authentication. These public endpoints are designed for open access and do not require an access token.

Token Locations

When including your access token in a request, ensure it is placed in one of the following specified locations. The service will sequentially search these locations for the token, utilizing the first one it encounters.

Location Token Name / Param Name
Query access_token
Authorization Header Bearer
Header wechess-access-token
Cookie wechess-access-token

Please ensure the token is correctly placed in one of these locations, using the appropriate label as indicated. The service prioritizes these locations in the order listed, processing the first token it successfully identifies.

Api Definitions

This section outlines the API endpoints available within the AgentHub service. Each endpoint can receive parameters through various methods, meticulously described in the following definitions. It’s important to understand the flexibility in how parameters can be included in requests to effectively interact with the AgentHub service.

This service is configured to listen for HTTP requests on port 3006, serving both the main API interface and default administrative endpoints.

The following routes are available by default:

This service is accessible via the following environment-specific URLs:

Parameter Inclusion Methods: Parameters can be incorporated into API requests in several ways, each with its designated location. Understanding these methods is crucial for correctly constructing your requests:

Query Parameters: Included directly in the URL’s query string.

Path Parameters: Embedded within the URL’s path.

Body Parameters: Sent within the JSON body of the request.

Session Parameters: Automatically read from the session object. This method is used for parameters that are intrinsic to the user’s session, such as userId. When using an API that involves session parameters, you can omit these from your request. The service will automatically bind them to the API layer, provided that a session is associated with your request.

Note on Session Parameters: Session parameters represent a unique method of parameter inclusion, relying on the context of the user’s session. A common example of a session parameter is userId, which the service automatically associates with your request when a session exists. This feature ensures seamless integration of user-specific data without manual input for each request.

By adhering to the specified parameter inclusion methods, you can effectively utilize the AgentHub service’s API endpoints. For detailed information on each endpoint, including required parameters and their accepted locations, refer to the individual API definitions below.

Common Parameters

The AgentHub service’s business API support several common parameters designed to modify and enhance the behavior of API requests. These parameters are not individually listed in the API route definitions to avoid repetition. Instead, refer to this section to understand how to leverage these common behaviors across different routes. Note that all common parameters should be included in the query part of the URL.

Supported Common Parameters:

By utilizing these common parameters, you can tailor the behavior of API requests to suit your specific requirements, ensuring optimal performance and usability of the AgentHub service.

Error Response

If a request encounters an issue, whether due to a logical fault or a technical problem, the service responds with a standardized JSON error structure. The HTTP status code within this response indicates the nature of the error, utilizing commonly recognized codes for clarity:

Each error response is structured to provide meaningful insight into the problem, assisting in diagnosing and resolving issues efficiently.

{
  "result": "ERR",
  "status": 400,
  "message": "errMsg_organizationIdisNotAValidID",
  "errCode": 400,
  "date": "2024-03-19T12:13:54.124Z",
  "detail": "String"
}

Object Structure of a Successfull Response

When the AgentHub service processes requests successfully, it wraps the requested resource(s) within a JSON envelope. This envelope not only contains the data but also includes essential metadata, such as configuration details and pagination information, to enrich the response and provide context to the client.

Key Characteristics of the Response Envelope:

Design Considerations: The structure of a API’s response data is meticulously crafted during the service’s architectural planning. This design ensures that responses adequately reflect the intended data relationships and service logic, providing clients with rich and meaningful information.

Brief Data: Certain API’s return a condensed version of the object data, intentionally selecting only specific fields deemed useful for that request. In such instances, the API documentation will detail the properties included in the response, guiding developers on what to expect.

API Response Structure

The API utilizes a standardized JSON envelope to encapsulate responses. This envelope is designed to consistently deliver both the requested data and essential metadata, ensuring that clients can efficiently interpret and utilize the response.

HTTP Status Codes:

Success Response Format:

For successful operations, the response includes a "status": "OK" property, signaling the successful execution of the request. The structure of a successful response is outlined below:

{
  "status":"OK",
  "statusCode": 200,   
  "elapsedMs":126,
  "ssoTime":120,
  "source": "db",
  "cacheKey": "hexCode",
  "userId": "ID",
  "sessionId": "ID",
  "requestId": "ID",
  "dataName":"products",
  "method":"GET",
  "action":"list",
  "appVersion":"Version",
  "rowCount":3
  "products":[{},{},{}],
  "paging": {
    "pageNumber":1, 
    "pageRowCount":25, 
    "totalRowCount":3,
    "pageCount":1
  },
  "filters": [],
  "uiPermissions": []
}

Handling Errors:

For details on handling error scenarios and understanding the structure of error responses, please refer to the “Error Response” section provided earlier in this documentation. It outlines how error conditions are communicated, including the use of HTTP status codes and standardized JSON structures for error messages.

Resources

AgentHub service provides the following resources which are stored in its own database as a data object. Note that a resource for an api access is a data object for the service.

Sys_agentOverride resource

Resource Definition : Runtime overrides for design-time agents. Null fields use the design default. Sys_agentOverride Resource Properties

Name Type Required Default Definition
agentName String Design-time agent name this override applies to.
provider String Override AI provider (e.g., openai, anthropic).
model String Override model name.
systemPrompt Text Override system prompt.
temperature Double Override temperature (0-2).
maxTokens Integer Override max tokens.
responseFormat String Override response format (text/json).
selectedTools Object Array of tool names from the catalog that this agent can use.
guardrails Object Override guardrails: { maxToolCalls, timeout, maxTokenBudget }.
enabled Boolean Enable or disable this agent.
updatedBy ID User who last updated this override.

Sys_agentExecution resource

Resource Definition : Agent execution log. Records each agent invocation with input, output, and performance metrics. Sys_agentExecution Resource Properties

Name Type Required Default Definition
agentName String Agent that was executed.
agentType Enum Whether this was a design-time or dynamic agent.
source Enum How the agent was triggered.
userId ID User who triggered the execution.
input Object Request input (truncated for large payloads).
output Object Response output (truncated for large payloads).
toolCalls Integer Number of tool calls made during execution.
tokenUsage Object Token usage: { prompt, completion, total }.
durationMs Integer Execution time in milliseconds.
status Enum Execution status.
error Text Error message if execution failed.

Enum Properties

Enum properties are represented as strings in the database. The values are mapped to their corresponding names in the application layer.

agentType Enum Property

Property Definition : Whether this was a design-time or dynamic agent.Enum Options

Name Value Index
design "design"" 0
dynamic "dynamic"" 1
source Enum Property

Property Definition : How the agent was triggered.Enum Options

Name Value Index
rest "rest"" 0
sse "sse"" 1
kafka "kafka"" 2
agent "agent"" 3
status Enum Property

Property Definition : Execution status.Enum Options

Name Value Index
success "success"" 0
error "error"" 1
timeout "timeout"" 2

Sys_toolCatalog resource

Resource Definition : Cached tool catalog discovered from project services. Refreshed periodically. Sys_toolCatalog Resource Properties

Name Type Required Default Definition
toolName String Full tool name (e.g., service:apiName).
serviceName String Source service name.
description Text Tool description.
parameters Object JSON Schema of tool parameters.
lastRefreshed Date When this tool was last discovered/refreshed.

Business Api

Get Agentoverride API

[Default get API] — This is the designated default get API for the sys_agentOverride data object. Frontend generators and AI agents should use this API for standard CRUD operations.

Rest Route

The getAgentOverride API REST controller can be triggered via the following route:

/v1/agentoverride/:sys_agentOverrideId

Rest Request Parameters

The getAgentOverride api has got 1 regular request parameter

Parameter Type Required Population
sys_agentOverrideId ID true request.params?.[“sys_agentOverrideId”]
sys_agentOverrideId : This id paremeter is used to query the required data object.

REST Request To access the api you can use the REST controller with the path GET /v1/agentoverride/:sys_agentOverrideId

  axios({
    method: 'GET',
    url: `/v1/agentoverride/${sys_agentOverrideId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_agentOverride",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"sys_agentOverride": {
		"id": "ID",
		"agentName": "String",
		"provider": "String",
		"model": "String",
		"systemPrompt": "Text",
		"temperature": "Double",
		"maxTokens": "Integer",
		"responseFormat": "String",
		"selectedTools": "Object",
		"guardrails": "Object",
		"enabled": "Boolean",
		"updatedBy": "ID",
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"isActive": true
	}
}

List Agentoverrides API

[Default list API] — This is the designated default list API for the sys_agentOverride data object. Frontend generators and AI agents should use this API for standard CRUD operations.

Rest Route

The listAgentOverrides API REST controller can be triggered via the following route:

/v1/agentoverrides

Rest Request Parameters The listAgentOverrides api has got no request parameters.

REST Request To access the api you can use the REST controller with the path GET /v1/agentoverrides

  axios({
    method: 'GET',
    url: '/v1/agentoverrides',
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_agentOverrides",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"sys_agentOverrides": [
		{
			"id": "ID",
			"agentName": "String",
			"provider": "String",
			"model": "String",
			"systemPrompt": "Text",
			"temperature": "Double",
			"maxTokens": "Integer",
			"responseFormat": "String",
			"selectedTools": "Object",
			"guardrails": "Object",
			"enabled": "Boolean",
			"updatedBy": "ID",
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID",
			"isActive": true
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Update Agentoverride API

[Default update API] — This is the designated default update API for the sys_agentOverride data object. Frontend generators and AI agents should use this API for standard CRUD operations.

Rest Route

The updateAgentOverride API REST controller can be triggered via the following route:

/v1/agentoverride/:sys_agentOverrideId

Rest Request Parameters

The updateAgentOverride api has got 10 regular request parameters

Parameter Type Required Population
sys_agentOverrideId ID true request.params?.[“sys_agentOverrideId”]
provider String request.body?.[“provider”]
model String request.body?.[“model”]
systemPrompt Text request.body?.[“systemPrompt”]
temperature Double request.body?.[“temperature”]
maxTokens Integer request.body?.[“maxTokens”]
responseFormat String request.body?.[“responseFormat”]
selectedTools Object request.body?.[“selectedTools”]
guardrails Object request.body?.[“guardrails”]
enabled Boolean request.body?.[“enabled”]
sys_agentOverrideId : This id paremeter is used to select the required data object that will be updated
provider : Override AI provider (e.g., openai, anthropic).
model : Override model name.
systemPrompt : Override system prompt.
temperature : Override temperature (0-2).
maxTokens : Override max tokens.
responseFormat : Override response format (text/json).
selectedTools : Array of tool names from the catalog that this agent can use.
guardrails : Override guardrails: { maxToolCalls, timeout, maxTokenBudget }.
enabled : Enable or disable this agent.

REST Request To access the api you can use the REST controller with the path PATCH /v1/agentoverride/:sys_agentOverrideId

  axios({
    method: 'PATCH',
    url: `/v1/agentoverride/${sys_agentOverrideId}`,
    data: {
            provider:"String",  
            model:"String",  
            systemPrompt:"Text",  
            temperature:"Double",  
            maxTokens:"Integer",  
            responseFormat:"String",  
            selectedTools:"Object",  
            guardrails:"Object",  
            enabled:"Boolean",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_agentOverride",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"sys_agentOverride": {
		"id": "ID",
		"agentName": "String",
		"provider": "String",
		"model": "String",
		"systemPrompt": "Text",
		"temperature": "Double",
		"maxTokens": "Integer",
		"responseFormat": "String",
		"selectedTools": "Object",
		"guardrails": "Object",
		"enabled": "Boolean",
		"updatedBy": "ID",
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"isActive": true
	}
}

Create Agentoverride API

[Default create API] — This is the designated default create API for the sys_agentOverride data object. Frontend generators and AI agents should use this API for standard CRUD operations.

Rest Route

The createAgentOverride API REST controller can be triggered via the following route:

/v1/agentoverride

Rest Request Parameters

The createAgentOverride api has got 9 regular request parameters

Parameter Type Required Population
agentName String true request.body?.[“agentName”]
provider String false request.body?.[“provider”]
model String false request.body?.[“model”]
systemPrompt Text false request.body?.[“systemPrompt”]
temperature Double false request.body?.[“temperature”]
maxTokens Integer false request.body?.[“maxTokens”]
responseFormat String false request.body?.[“responseFormat”]
selectedTools Object false request.body?.[“selectedTools”]
guardrails Object false request.body?.[“guardrails”]
agentName : Design-time agent name this override applies to.
provider : Override AI provider (e.g., openai, anthropic).
model : Override model name.
systemPrompt : Override system prompt.
temperature : Override temperature (0-2).
maxTokens : Override max tokens.
responseFormat : Override response format (text/json).
selectedTools : Array of tool names from the catalog that this agent can use.
guardrails : Override guardrails: { maxToolCalls, timeout, maxTokenBudget }.

REST Request To access the api you can use the REST controller with the path POST /v1/agentoverride

  axios({
    method: 'POST',
    url: '/v1/agentoverride',
    data: {
            agentName:"String",  
            provider:"String",  
            model:"String",  
            systemPrompt:"Text",  
            temperature:"Double",  
            maxTokens:"Integer",  
            responseFormat:"String",  
            selectedTools:"Object",  
            guardrails:"Object",  
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_agentOverride",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"sys_agentOverride": {
		"id": "ID",
		"agentName": "String",
		"provider": "String",
		"model": "String",
		"systemPrompt": "Text",
		"temperature": "Double",
		"maxTokens": "Integer",
		"responseFormat": "String",
		"selectedTools": "Object",
		"guardrails": "Object",
		"enabled": "Boolean",
		"updatedBy": "ID",
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"isActive": true
	}
}

Delete Agentoverride API

[Default delete API] — This is the designated default delete API for the sys_agentOverride data object. Frontend generators and AI agents should use this API for standard CRUD operations.

Rest Route

The deleteAgentOverride API REST controller can be triggered via the following route:

/v1/agentoverride/:sys_agentOverrideId

Rest Request Parameters

The deleteAgentOverride api has got 1 regular request parameter

Parameter Type Required Population
sys_agentOverrideId ID true request.params?.[“sys_agentOverrideId”]
sys_agentOverrideId : This id paremeter is used to select the required data object that will be deleted

REST Request To access the api you can use the REST controller with the path DELETE /v1/agentoverride/:sys_agentOverrideId

  axios({
    method: 'DELETE',
    url: `/v1/agentoverride/${sys_agentOverrideId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_agentOverride",
	"method": "DELETE",
	"action": "delete",
	"appVersion": "Version",
	"rowCount": 1,
	"sys_agentOverride": {
		"id": "ID",
		"agentName": "String",
		"provider": "String",
		"model": "String",
		"systemPrompt": "Text",
		"temperature": "Double",
		"maxTokens": "Integer",
		"responseFormat": "String",
		"selectedTools": "Object",
		"guardrails": "Object",
		"enabled": "Boolean",
		"updatedBy": "ID",
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"isActive": false
	}
}

List Toolcatalog API

[Default list API] — This is the designated default list API for the sys_toolCatalog data object. Frontend generators and AI agents should use this API for standard CRUD operations.

Rest Route

The listToolCatalog API REST controller can be triggered via the following route:

/v1/toolcatalog

Rest Request Parameters

Filter Parameters

The listToolCatalog api supports 1 optional filter parameter for filtering list results:

serviceName (String): Source service name.

REST Request To access the api you can use the REST controller with the path GET /v1/toolcatalog

  axios({
    method: 'GET',
    url: '/v1/toolcatalog',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section above)
        // serviceName: '<value>' // Filter by serviceName
            }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_toolCatalogs",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"sys_toolCatalogs": [
		{
			"id": "ID",
			"toolName": "String",
			"serviceName": "String",
			"description": "Text",
			"parameters": "Object",
			"lastRefreshed": "Date",
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID",
			"isActive": true
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Get Toolcatalogentry API

[Default get API] — This is the designated default get API for the sys_toolCatalog data object. Frontend generators and AI agents should use this API for standard CRUD operations.

Rest Route

The getToolCatalogEntry API REST controller can be triggered via the following route:

/v1/toolcatalogentry/:sys_toolCatalogId

Rest Request Parameters

The getToolCatalogEntry api has got 1 regular request parameter

Parameter Type Required Population
sys_toolCatalogId ID true request.params?.[“sys_toolCatalogId”]
sys_toolCatalogId : This id paremeter is used to query the required data object.

REST Request To access the api you can use the REST controller with the path GET /v1/toolcatalogentry/:sys_toolCatalogId

  axios({
    method: 'GET',
    url: `/v1/toolcatalogentry/${sys_toolCatalogId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_toolCatalog",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"sys_toolCatalog": {
		"id": "ID",
		"toolName": "String",
		"serviceName": "String",
		"description": "Text",
		"parameters": "Object",
		"lastRefreshed": "Date",
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"isActive": true
	}
}

List Agentexecutions API

[Default list API] — This is the designated default list API for the sys_agentExecution data object. Frontend generators and AI agents should use this API for standard CRUD operations.

Rest Route

The listAgentExecutions API REST controller can be triggered via the following route:

/v1/agentexecutions

Rest Request Parameters

Filter Parameters

The listAgentExecutions api supports 5 optional filter parameters for filtering list results:

agentName (String): Agent that was executed.

agentType (Enum): Whether this was a design-time or dynamic agent.

source (Enum): How the agent was triggered.

userId (ID): User who triggered the execution.

status (Enum): Execution status.

REST Request To access the api you can use the REST controller with the path GET /v1/agentexecutions

  axios({
    method: 'GET',
    url: '/v1/agentexecutions',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section above)
        // agentName: '<value>' // Filter by agentName
        // agentType: '<value>' // Filter by agentType
        // source: '<value>' // Filter by source
        // userId: '<value>' // Filter by userId
        // status: '<value>' // Filter by status
            }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_agentExecutions",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"sys_agentExecutions": [
		{
			"id": "ID",
			"agentName": "String",
			"agentType": "Enum",
			"agentType_idx": "Integer",
			"source": "Enum",
			"source_idx": "Integer",
			"userId": "ID",
			"input": "Object",
			"output": "Object",
			"toolCalls": "Integer",
			"tokenUsage": "Object",
			"durationMs": "Integer",
			"status": "Enum",
			"status_idx": "Integer",
			"error": "Text",
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID",
			"isActive": true
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Get Agentexecution API

[Default get API] — This is the designated default get API for the sys_agentExecution data object. Frontend generators and AI agents should use this API for standard CRUD operations.

Rest Route

The getAgentExecution API REST controller can be triggered via the following route:

/v1/agentexecution/:sys_agentExecutionId

Rest Request Parameters

The getAgentExecution api has got 1 regular request parameter

Parameter Type Required Population
sys_agentExecutionId ID true request.params?.[“sys_agentExecutionId”]
sys_agentExecutionId : This id paremeter is used to query the required data object.

REST Request To access the api you can use the REST controller with the path GET /v1/agentexecution/:sys_agentExecutionId

  axios({
    method: 'GET',
    url: `/v1/agentexecution/${sys_agentExecutionId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_agentExecution",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"sys_agentExecution": {
		"id": "ID",
		"agentName": "String",
		"agentType": "Enum",
		"agentType_idx": "Integer",
		"source": "Enum",
		"source_idx": "Integer",
		"userId": "ID",
		"input": "Object",
		"output": "Object",
		"toolCalls": "Integer",
		"tokenUsage": "Object",
		"durationMs": "Integer",
		"status": "Enum",
		"status_idx": "Integer",
		"error": "Text",
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"isActive": true
	}
}

Authentication Specific Routes

Common Routes

Route: currentuser

Route Definition: Retrieves the currently authenticated user’s session information.

Route Type: sessionInfo

Access Route: GET /currentuser

Parameters

This route does not require any request parameters.

Behavior

// Sample GET /currentuser call
axios.get("/currentuser", {
  headers: {
    "Authorization": "Bearer your-jwt-token"
  }
});

Success Response Returns the session object, including user-related data and token information.

{
  "sessionId": "9cf23fa8-07d4-4e7c-80a6-ec6d6ac96bb9",
  "userId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38",
  "email": "user@example.com",
  "fullname": "John Doe",
  "roleId": "user",
  "tenantId": "abc123",
  "accessToken": "jwt-token-string",
  ...
}

Error Response 401 Unauthorized: No active session found.

{
  "status": "ERR",
  "message": "No login found"
}

Notes

Route: permissions

*Route Definition*: Retrieves all effective permission records assigned to the currently authenticated user.

*Route Type*: permissionFetch

Access Route: GET /permissions

Parameters

This route does not require any request parameters.

Behavior

// Sample GET /permissions call
axios.get("/permissions", {
  headers: {
    "Authorization": "Bearer your-jwt-token"
  }
});

Success Response

Returns an array of permission objects.

[
  {
    "id": "perm1",
    "permissionName": "adminPanel.access",
    "roleId": "admin",
    "subjectUserId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38",
    "subjectUserGroupId": null,
    "objectId": null,
    "canDo": true,
    "tenantCodename": "store123"
  },
  {
    "id": "perm2",
    "permissionName": "orders.manage",
    "roleId": null,
    "subjectUserId": "d92b9d4c-9b1e-4e95-842e-3fb9c8c1df38",
    "subjectUserGroupId": null,
    "objectId": null,
    "canDo": true,
    "tenantCodename": "store123"
  }
]

Each object reflects a single permission grant, aligned with the givenPermissions model:

Error Responses

{
  "status": "ERR",
  "message": "No login found"
}

Notes

Tip: Applications can cache permission results client-side or server-side, but should occasionally refresh by calling this endpoint, especially after login or permission-changing operations.

Route: permissions/:permissionName

Route Definition: Checks whether the current user has access to a specific permission, and provides a list of scoped object exceptions or inclusions.

Route Type: permissionScopeCheck

Access Route: GET /permissions/:permissionName

Parameters

Parameter Type Required Population
permissionName String Yes request.params.permissionName

Behavior

// Sample GET /permissions/orders.manage
axios.get("/permissions/orders.manage", {
  headers: {
    "Authorization": "Bearer your-jwt-token"
  }
});

Success Response

{
  "canDo": true,
  "exceptions": [
    "a1f2e3d4-xxxx-yyyy-zzzz-object1",
    "b2c3d4e5-xxxx-yyyy-zzzz-object2"
  ]
}

Copyright

All sources, documents and other digital materials are copyright of .

About Us

For more information please visit our website: .

. .


EVENT GUIDE

EVENT GUIDE

wechess-agenthub-service

AI Agent Hub

Architectural Design Credit and Contact Information

The architectural design of this microservice is credited to . For inquiries, feedback, or further information regarding the architecture, please direct your communication to:

Email:

We encourage open communication and welcome any questions or discussions related to the architectural aspects of this microservice.

Documentation Scope

Welcome to the official documentation for the AgentHub Service Event descriptions. This guide is dedicated to detailing how to subscribe to and listen for state changes within the AgentHub Service, offering an exclusive focus on event subscription mechanisms.

Intended Audience

This documentation is aimed at developers and integrators looking to monitor AgentHub Service state changes. It is especially relevant for those wishing to implement or enhance business logic based on interactions with AgentHub objects.

Overview

This section provides detailed instructions on monitoring service events, covering payload structures and demonstrating typical use cases through examples.

Authentication and Authorization

Access to the AgentHub service’s events is facilitated through the project’s Kafka server, which is not accessible to the public. Subscription to a Kafka topic requires being on the same network and possessing valid Kafka user credentials. This document presupposes that readers have existing access to the Kafka server.

Additionally, the service offers a public subscription option via REST for real-time data management in frontend applications, secured through REST API authentication and authorization mechanisms. To subscribe to service events via the REST API, please consult the Realtime REST API Guide.

Database Events

Database events are triggered at the database layer, automatically and atomically, in response to any modifications at the data level. These events serve to notify subscribers about the creation, update, or deletion of objects within the database, distinct from any overarching business logic.

Listening to database events is particularly beneficial for those focused on tracking changes at the database level. A typical use case for subscribing to database events is to replicate the data store of one service within another service’s scope, ensuring data consistency and syncronization across services.

For example, while a business operation such as “approve membership” might generate a high-level business event like membership-approved, the underlying database changes could involve multiple state updates to different entities. These might be published as separate events, such as dbevent-member-updated and dbevent-user-updated, reflecting the granular changes at the database level.

Such detailed eventing provides a robust foundation for building responsive, data-driven applications, enabling fine-grained observability and reaction to the dynamics of the data landscape. It also facilitates the architectural pattern of event sourcing, where state changes are captured as a sequence of events, allowing for high-fidelity data replication and history replay for analytical or auditing purposes.

DbEvent sys_agentOverride-created

Event topic: wechess-agenthub-service-dbevent-sys_agentoverride-created

This event is triggered upon the creation of a sys_agentOverride data object in the database. The event payload encompasses the newly created data, encapsulated within the root of the paylod.

Event payload:

{"id":"ID","agentName":"String","provider":"String","model":"String","systemPrompt":"Text","temperature":"Double","maxTokens":"Integer","responseFormat":"String","selectedTools":"Object","guardrails":"Object","enabled":"Boolean","updatedBy":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

DbEvent sys_agentOverride-updated

Event topic: wechess-agenthub-service-dbevent-sys_agentoverride-updated

Activation of this event follows the update of a sys_agentOverride data object. The payload contains the updated information under the sys_agentOverride attribute, along with the original data prior to update, labeled as old_sys_agentOverride and also you can find the old and new versions of updated-only portion of the data…

Event payload:

{
old_sys_agentOverride:{"id":"ID","agentName":"String","provider":"String","model":"String","systemPrompt":"Text","temperature":"Double","maxTokens":"Integer","responseFormat":"String","selectedTools":"Object","guardrails":"Object","enabled":"Boolean","updatedBy":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},
sys_agentOverride:{"id":"ID","agentName":"String","provider":"String","model":"String","systemPrompt":"Text","temperature":"Double","maxTokens":"Integer","responseFormat":"String","selectedTools":"Object","guardrails":"Object","enabled":"Boolean","updatedBy":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},
oldDataValues,
newDataValues
}

DbEvent sys_agentOverride-deleted

Event topic: wechess-agenthub-service-dbevent-sys_agentoverride-deleted

This event announces the deletion of a sys_agentOverride data object, covering both hard deletions (permanent removal) and soft deletions (where the isActive attribute is set to false). Regardless of the deletion type, the event payload will present the data as it was immediately before deletion, highlighting an isActive status of false for soft deletions.

Event payload:

{"id":"ID","agentName":"String","provider":"String","model":"String","systemPrompt":"Text","temperature":"Double","maxTokens":"Integer","responseFormat":"String","selectedTools":"Object","guardrails":"Object","enabled":"Boolean","updatedBy":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":false}

DbEvent sys_agentExecution-created

Event topic: wechess-agenthub-service-dbevent-sys_agentexecution-created

This event is triggered upon the creation of a sys_agentExecution data object in the database. The event payload encompasses the newly created data, encapsulated within the root of the paylod.

Event payload:

{"id":"ID","agentName":"String","agentType":"Enum","agentType_idx":"Integer","source":"Enum","source_idx":"Integer","userId":"ID","input":"Object","output":"Object","toolCalls":"Integer","tokenUsage":"Object","durationMs":"Integer","status":"Enum","status_idx":"Integer","error":"Text","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

DbEvent sys_agentExecution-updated

Event topic: wechess-agenthub-service-dbevent-sys_agentexecution-updated

Activation of this event follows the update of a sys_agentExecution data object. The payload contains the updated information under the sys_agentExecution attribute, along with the original data prior to update, labeled as old_sys_agentExecution and also you can find the old and new versions of updated-only portion of the data…

Event payload:

{
old_sys_agentExecution:{"id":"ID","agentName":"String","agentType":"Enum","agentType_idx":"Integer","source":"Enum","source_idx":"Integer","userId":"ID","input":"Object","output":"Object","toolCalls":"Integer","tokenUsage":"Object","durationMs":"Integer","status":"Enum","status_idx":"Integer","error":"Text","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},
sys_agentExecution:{"id":"ID","agentName":"String","agentType":"Enum","agentType_idx":"Integer","source":"Enum","source_idx":"Integer","userId":"ID","input":"Object","output":"Object","toolCalls":"Integer","tokenUsage":"Object","durationMs":"Integer","status":"Enum","status_idx":"Integer","error":"Text","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},
oldDataValues,
newDataValues
}

DbEvent sys_agentExecution-deleted

Event topic: wechess-agenthub-service-dbevent-sys_agentexecution-deleted

This event announces the deletion of a sys_agentExecution data object, covering both hard deletions (permanent removal) and soft deletions (where the isActive attribute is set to false). Regardless of the deletion type, the event payload will present the data as it was immediately before deletion, highlighting an isActive status of false for soft deletions.

Event payload:

{"id":"ID","agentName":"String","agentType":"Enum","agentType_idx":"Integer","source":"Enum","source_idx":"Integer","userId":"ID","input":"Object","output":"Object","toolCalls":"Integer","tokenUsage":"Object","durationMs":"Integer","status":"Enum","status_idx":"Integer","error":"Text","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":false}

DbEvent sys_toolCatalog-created

Event topic: wechess-agenthub-service-dbevent-sys_toolcatalog-created

This event is triggered upon the creation of a sys_toolCatalog data object in the database. The event payload encompasses the newly created data, encapsulated within the root of the paylod.

Event payload:

{"id":"ID","toolName":"String","serviceName":"String","description":"Text","parameters":"Object","lastRefreshed":"Date","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

DbEvent sys_toolCatalog-updated

Event topic: wechess-agenthub-service-dbevent-sys_toolcatalog-updated

Activation of this event follows the update of a sys_toolCatalog data object. The payload contains the updated information under the sys_toolCatalog attribute, along with the original data prior to update, labeled as old_sys_toolCatalog and also you can find the old and new versions of updated-only portion of the data…

Event payload:

{
old_sys_toolCatalog:{"id":"ID","toolName":"String","serviceName":"String","description":"Text","parameters":"Object","lastRefreshed":"Date","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},
sys_toolCatalog:{"id":"ID","toolName":"String","serviceName":"String","description":"Text","parameters":"Object","lastRefreshed":"Date","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"},
oldDataValues,
newDataValues
}

DbEvent sys_toolCatalog-deleted

Event topic: wechess-agenthub-service-dbevent-sys_toolcatalog-deleted

This event announces the deletion of a sys_toolCatalog data object, covering both hard deletions (permanent removal) and soft deletions (where the isActive attribute is set to false). Regardless of the deletion type, the event payload will present the data as it was immediately before deletion, highlighting an isActive status of false for soft deletions.

Event payload:

{"id":"ID","toolName":"String","serviceName":"String","description":"Text","parameters":"Object","lastRefreshed":"Date","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":false}

ElasticSearch Index Events

Within the AgentHub service, most data objects are mirrored in ElasticSearch indices, ensuring these indices remain syncronized with their database counterparts through creation, updates, and deletions. These indices serve dual purposes: they act as a data source for external services and furnish aggregated data tailored to enhance frontend user experiences. Consequently, an ElasticSearch index might encapsulate data in its original form or aggregate additional information from other data objects.

These aggregations can include both one-to-one and one-to-many relationships not only with database objects within the same service but also across different services. This capability allows developers to access comprehensive, aggregated data efficiently. By subscribing to ElasticSearch index events, developers are notified when an index is updated and can directly obtain the aggregated entity within the event payload, bypassing the need for separate ElasticSearch queries.

It’s noteworthy that some services may augment another service’s index by appending to the entity’s extends object. In such scenarios, an *-extended event will contain only the newly added data. Should you require the complete dataset, you would need to retrieve the full ElasticSearch index entity using the provided ID.

This approach to indexing and event handling facilitates a modular, interconnected architecture where services can seamlessly integrate and react to changes, enriching the overall data ecosystem and enabling more dynamic, responsive applications.

Index Event sys_agentoverride-created

Event topic: elastic-index-wechess_sys_agentoverride-created

Event payload:

{"id":"ID","agentName":"String","provider":"String","model":"String","systemPrompt":"Text","temperature":"Double","maxTokens":"Integer","responseFormat":"String","selectedTools":"Object","guardrails":"Object","enabled":"Boolean","updatedBy":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event sys_agentoverride-updated

Event topic: elastic-index-wechess_sys_agentoverride-created

Event payload:

{"id":"ID","agentName":"String","provider":"String","model":"String","systemPrompt":"Text","temperature":"Double","maxTokens":"Integer","responseFormat":"String","selectedTools":"Object","guardrails":"Object","enabled":"Boolean","updatedBy":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event sys_agentoverride-deleted

Event topic: elastic-index-wechess_sys_agentoverride-deleted

Event payload:

{"id":"ID","agentName":"String","provider":"String","model":"String","systemPrompt":"Text","temperature":"Double","maxTokens":"Integer","responseFormat":"String","selectedTools":"Object","guardrails":"Object","enabled":"Boolean","updatedBy":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event sys_agentoverride-extended

Event topic: elastic-index-wechess_sys_agentoverride-extended

Event payload:

{
  id: id,
  extends: {
    [extendName]: "Object",
    [extendName + "_count"]: "Number",
  },
}

Route Events

Route events are emitted following the successful execution of a route. While most routes perform CRUD (Create, Read, Update, Delete) operations on data objects, resulting in route events that closely resemble database events, there are distinctions worth noting. A single route execution might trigger multiple CRUD actions and ElasticSearch indexing operations. However, for those primarily concerned with the overarching business logic and its outcomes, listening to the consolidated route event, published once at the conclusion of the route’s execution, is more pertinent.

Moreover, routes often deliver aggregated data beyond the primary database object, catering to specific client needs. For instance, creating a data object via a route might not only return the entity’s data but also route-specific metrics, such as the executing user’s permissions related to the entity. Alternatively, a route might automatically generate default child entities following the creation of a parent object. Consequently, the route event encapsulates a unified dataset encompassing both the parent and its children, in contrast to individual events triggered for each entity created. Therefore, subscribing to route events can offer a richer, more contextually relevant set of information aligned with business logic.

The payload of a route event mirrors the REST response JSON of the route, providing a direct and comprehensive reflection of the data and metadata communicated to the client. This ensures that subscribers to route events receive a payload that encapsulates both the primary data involved and any additional information deemed significant at the business level, facilitating a deeper understanding and integration of the service’s functional outcomes.

Route Event agentoverride-retrived

Event topic : wechess-agenthub-service-agentoverride-retrived

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the sys_agentOverride data object itself.

The following JSON included in the payload illustrates the fullest representation of the sys_agentOverride object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_agentOverride","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_agentOverride":{"id":"ID","agentName":"String","provider":"String","model":"String","systemPrompt":"Text","temperature":"Double","maxTokens":"Integer","responseFormat":"String","selectedTools":"Object","guardrails":"Object","enabled":"Boolean","updatedBy":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true}}

Route Event agentoverrides-listed

Event topic : wechess-agenthub-service-agentoverrides-listed

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the sys_agentOverrides data object itself.

The following JSON included in the payload illustrates the fullest representation of the sys_agentOverrides object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_agentOverrides","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_agentOverrides":[{"id":"ID","agentName":"String","provider":"String","model":"String","systemPrompt":"Text","temperature":"Double","maxTokens":"Integer","responseFormat":"String","selectedTools":"Object","guardrails":"Object","enabled":"Boolean","updatedBy":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]}

Route Event agentoverride-updated

Event topic : wechess-agenthub-service-agentoverride-updated

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the sys_agentOverride data object itself.

The following JSON included in the payload illustrates the fullest representation of the sys_agentOverride object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_agentOverride","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"sys_agentOverride":{"id":"ID","agentName":"String","provider":"String","model":"String","systemPrompt":"Text","temperature":"Double","maxTokens":"Integer","responseFormat":"String","selectedTools":"Object","guardrails":"Object","enabled":"Boolean","updatedBy":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true}}

Route Event agentoverride-created

Event topic : wechess-agenthub-service-agentoverride-created

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the sys_agentOverride data object itself.

The following JSON included in the payload illustrates the fullest representation of the sys_agentOverride object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_agentOverride","method":"POST","action":"create","appVersion":"Version","rowCount":1,"sys_agentOverride":{"id":"ID","agentName":"String","provider":"String","model":"String","systemPrompt":"Text","temperature":"Double","maxTokens":"Integer","responseFormat":"String","selectedTools":"Object","guardrails":"Object","enabled":"Boolean","updatedBy":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true}}

Route Event agentoverride-deleted

Event topic : wechess-agenthub-service-agentoverride-deleted

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the sys_agentOverride data object itself.

The following JSON included in the payload illustrates the fullest representation of the sys_agentOverride object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_agentOverride","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"sys_agentOverride":{"id":"ID","agentName":"String","provider":"String","model":"String","systemPrompt":"Text","temperature":"Double","maxTokens":"Integer","responseFormat":"String","selectedTools":"Object","guardrails":"Object","enabled":"Boolean","updatedBy":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":false}}

Route Event toolcatalog-listed

Event topic : wechess-agenthub-service-toolcatalog-listed

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the sys_toolCatalogs data object itself.

The following JSON included in the payload illustrates the fullest representation of the sys_toolCatalogs object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_toolCatalogs","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_toolCatalogs":[{"id":"ID","toolName":"String","serviceName":"String","description":"Text","parameters":"Object","lastRefreshed":"Date","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]}

Route Event toolcatalogentry-retrived

Event topic : wechess-agenthub-service-toolcatalogentry-retrived

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the sys_toolCatalog data object itself.

The following JSON included in the payload illustrates the fullest representation of the sys_toolCatalog object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_toolCatalog","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_toolCatalog":{"id":"ID","toolName":"String","serviceName":"String","description":"Text","parameters":"Object","lastRefreshed":"Date","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true}}

Route Event agentexecutions-listed

Event topic : wechess-agenthub-service-agentexecutions-listed

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the sys_agentExecutions data object itself.

The following JSON included in the payload illustrates the fullest representation of the sys_agentExecutions object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_agentExecutions","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_agentExecutions":[{"id":"ID","agentName":"String","agentType":"Enum","agentType_idx":"Integer","source":"Enum","source_idx":"Integer","userId":"ID","input":"Object","output":"Object","toolCalls":"Integer","tokenUsage":"Object","durationMs":"Integer","status":"Enum","status_idx":"Integer","error":"Text","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]}

Route Event agentexecution-retrived

Event topic : wechess-agenthub-service-agentexecution-retrived

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the sys_agentExecution data object itself.

The following JSON included in the payload illustrates the fullest representation of the sys_agentExecution object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_agentExecution","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_agentExecution":{"id":"ID","agentName":"String","agentType":"Enum","agentType_idx":"Integer","source":"Enum","source_idx":"Integer","userId":"ID","input":"Object","output":"Object","toolCalls":"Integer","tokenUsage":"Object","durationMs":"Integer","status":"Enum","status_idx":"Integer","error":"Text","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true}}

Index Event sys_agentexecution-created

Event topic: elastic-index-wechess_sys_agentexecution-created

Event payload:

{"id":"ID","agentName":"String","agentType":"Enum","agentType_idx":"Integer","source":"Enum","source_idx":"Integer","userId":"ID","input":"Object","output":"Object","toolCalls":"Integer","tokenUsage":"Object","durationMs":"Integer","status":"Enum","status_idx":"Integer","error":"Text","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event sys_agentexecution-updated

Event topic: elastic-index-wechess_sys_agentexecution-created

Event payload:

{"id":"ID","agentName":"String","agentType":"Enum","agentType_idx":"Integer","source":"Enum","source_idx":"Integer","userId":"ID","input":"Object","output":"Object","toolCalls":"Integer","tokenUsage":"Object","durationMs":"Integer","status":"Enum","status_idx":"Integer","error":"Text","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event sys_agentexecution-deleted

Event topic: elastic-index-wechess_sys_agentexecution-deleted

Event payload:

{"id":"ID","agentName":"String","agentType":"Enum","agentType_idx":"Integer","source":"Enum","source_idx":"Integer","userId":"ID","input":"Object","output":"Object","toolCalls":"Integer","tokenUsage":"Object","durationMs":"Integer","status":"Enum","status_idx":"Integer","error":"Text","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event sys_agentexecution-extended

Event topic: elastic-index-wechess_sys_agentexecution-extended

Event payload:

{
  id: id,
  extends: {
    [extendName]: "Object",
    [extendName + "_count"]: "Number",
  },
}

Route Events

Route events are emitted following the successful execution of a route. While most routes perform CRUD (Create, Read, Update, Delete) operations on data objects, resulting in route events that closely resemble database events, there are distinctions worth noting. A single route execution might trigger multiple CRUD actions and ElasticSearch indexing operations. However, for those primarily concerned with the overarching business logic and its outcomes, listening to the consolidated route event, published once at the conclusion of the route’s execution, is more pertinent.

Moreover, routes often deliver aggregated data beyond the primary database object, catering to specific client needs. For instance, creating a data object via a route might not only return the entity’s data but also route-specific metrics, such as the executing user’s permissions related to the entity. Alternatively, a route might automatically generate default child entities following the creation of a parent object. Consequently, the route event encapsulates a unified dataset encompassing both the parent and its children, in contrast to individual events triggered for each entity created. Therefore, subscribing to route events can offer a richer, more contextually relevant set of information aligned with business logic.

The payload of a route event mirrors the REST response JSON of the route, providing a direct and comprehensive reflection of the data and metadata communicated to the client. This ensures that subscribers to route events receive a payload that encapsulates both the primary data involved and any additional information deemed significant at the business level, facilitating a deeper understanding and integration of the service’s functional outcomes.

Route Event agentoverride-retrived

Event topic : wechess-agenthub-service-agentoverride-retrived

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the sys_agentOverride data object itself.

The following JSON included in the payload illustrates the fullest representation of the sys_agentOverride object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_agentOverride","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_agentOverride":{"id":"ID","agentName":"String","provider":"String","model":"String","systemPrompt":"Text","temperature":"Double","maxTokens":"Integer","responseFormat":"String","selectedTools":"Object","guardrails":"Object","enabled":"Boolean","updatedBy":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true}}

Route Event agentoverrides-listed

Event topic : wechess-agenthub-service-agentoverrides-listed

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the sys_agentOverrides data object itself.

The following JSON included in the payload illustrates the fullest representation of the sys_agentOverrides object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_agentOverrides","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_agentOverrides":[{"id":"ID","agentName":"String","provider":"String","model":"String","systemPrompt":"Text","temperature":"Double","maxTokens":"Integer","responseFormat":"String","selectedTools":"Object","guardrails":"Object","enabled":"Boolean","updatedBy":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]}

Route Event agentoverride-updated

Event topic : wechess-agenthub-service-agentoverride-updated

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the sys_agentOverride data object itself.

The following JSON included in the payload illustrates the fullest representation of the sys_agentOverride object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_agentOverride","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"sys_agentOverride":{"id":"ID","agentName":"String","provider":"String","model":"String","systemPrompt":"Text","temperature":"Double","maxTokens":"Integer","responseFormat":"String","selectedTools":"Object","guardrails":"Object","enabled":"Boolean","updatedBy":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true}}

Route Event agentoverride-created

Event topic : wechess-agenthub-service-agentoverride-created

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the sys_agentOverride data object itself.

The following JSON included in the payload illustrates the fullest representation of the sys_agentOverride object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_agentOverride","method":"POST","action":"create","appVersion":"Version","rowCount":1,"sys_agentOverride":{"id":"ID","agentName":"String","provider":"String","model":"String","systemPrompt":"Text","temperature":"Double","maxTokens":"Integer","responseFormat":"String","selectedTools":"Object","guardrails":"Object","enabled":"Boolean","updatedBy":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true}}

Route Event agentoverride-deleted

Event topic : wechess-agenthub-service-agentoverride-deleted

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the sys_agentOverride data object itself.

The following JSON included in the payload illustrates the fullest representation of the sys_agentOverride object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_agentOverride","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"sys_agentOverride":{"id":"ID","agentName":"String","provider":"String","model":"String","systemPrompt":"Text","temperature":"Double","maxTokens":"Integer","responseFormat":"String","selectedTools":"Object","guardrails":"Object","enabled":"Boolean","updatedBy":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":false}}

Route Event toolcatalog-listed

Event topic : wechess-agenthub-service-toolcatalog-listed

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the sys_toolCatalogs data object itself.

The following JSON included in the payload illustrates the fullest representation of the sys_toolCatalogs object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_toolCatalogs","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_toolCatalogs":[{"id":"ID","toolName":"String","serviceName":"String","description":"Text","parameters":"Object","lastRefreshed":"Date","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]}

Route Event toolcatalogentry-retrived

Event topic : wechess-agenthub-service-toolcatalogentry-retrived

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the sys_toolCatalog data object itself.

The following JSON included in the payload illustrates the fullest representation of the sys_toolCatalog object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_toolCatalog","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_toolCatalog":{"id":"ID","toolName":"String","serviceName":"String","description":"Text","parameters":"Object","lastRefreshed":"Date","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true}}

Route Event agentexecutions-listed

Event topic : wechess-agenthub-service-agentexecutions-listed

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the sys_agentExecutions data object itself.

The following JSON included in the payload illustrates the fullest representation of the sys_agentExecutions object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_agentExecutions","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_agentExecutions":[{"id":"ID","agentName":"String","agentType":"Enum","agentType_idx":"Integer","source":"Enum","source_idx":"Integer","userId":"ID","input":"Object","output":"Object","toolCalls":"Integer","tokenUsage":"Object","durationMs":"Integer","status":"Enum","status_idx":"Integer","error":"Text","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]}

Route Event agentexecution-retrived

Event topic : wechess-agenthub-service-agentexecution-retrived

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the sys_agentExecution data object itself.

The following JSON included in the payload illustrates the fullest representation of the sys_agentExecution object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_agentExecution","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_agentExecution":{"id":"ID","agentName":"String","agentType":"Enum","agentType_idx":"Integer","source":"Enum","source_idx":"Integer","userId":"ID","input":"Object","output":"Object","toolCalls":"Integer","tokenUsage":"Object","durationMs":"Integer","status":"Enum","status_idx":"Integer","error":"Text","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true}}

Index Event sys_toolcatalog-created

Event topic: elastic-index-wechess_sys_toolcatalog-created

Event payload:

{"id":"ID","toolName":"String","serviceName":"String","description":"Text","parameters":"Object","lastRefreshed":"Date","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event sys_toolcatalog-updated

Event topic: elastic-index-wechess_sys_toolcatalog-created

Event payload:

{"id":"ID","toolName":"String","serviceName":"String","description":"Text","parameters":"Object","lastRefreshed":"Date","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event sys_toolcatalog-deleted

Event topic: elastic-index-wechess_sys_toolcatalog-deleted

Event payload:

{"id":"ID","toolName":"String","serviceName":"String","description":"Text","parameters":"Object","lastRefreshed":"Date","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID"}

Index Event sys_toolcatalog-extended

Event topic: elastic-index-wechess_sys_toolcatalog-extended

Event payload:

{
  id: id,
  extends: {
    [extendName]: "Object",
    [extendName + "_count"]: "Number",
  },
}

Route Events

Route events are emitted following the successful execution of a route. While most routes perform CRUD (Create, Read, Update, Delete) operations on data objects, resulting in route events that closely resemble database events, there are distinctions worth noting. A single route execution might trigger multiple CRUD actions and ElasticSearch indexing operations. However, for those primarily concerned with the overarching business logic and its outcomes, listening to the consolidated route event, published once at the conclusion of the route’s execution, is more pertinent.

Moreover, routes often deliver aggregated data beyond the primary database object, catering to specific client needs. For instance, creating a data object via a route might not only return the entity’s data but also route-specific metrics, such as the executing user’s permissions related to the entity. Alternatively, a route might automatically generate default child entities following the creation of a parent object. Consequently, the route event encapsulates a unified dataset encompassing both the parent and its children, in contrast to individual events triggered for each entity created. Therefore, subscribing to route events can offer a richer, more contextually relevant set of information aligned with business logic.

The payload of a route event mirrors the REST response JSON of the route, providing a direct and comprehensive reflection of the data and metadata communicated to the client. This ensures that subscribers to route events receive a payload that encapsulates both the primary data involved and any additional information deemed significant at the business level, facilitating a deeper understanding and integration of the service’s functional outcomes.

Route Event agentoverride-retrived

Event topic : wechess-agenthub-service-agentoverride-retrived

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the sys_agentOverride data object itself.

The following JSON included in the payload illustrates the fullest representation of the sys_agentOverride object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_agentOverride","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_agentOverride":{"id":"ID","agentName":"String","provider":"String","model":"String","systemPrompt":"Text","temperature":"Double","maxTokens":"Integer","responseFormat":"String","selectedTools":"Object","guardrails":"Object","enabled":"Boolean","updatedBy":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true}}

Route Event agentoverrides-listed

Event topic : wechess-agenthub-service-agentoverrides-listed

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the sys_agentOverrides data object itself.

The following JSON included in the payload illustrates the fullest representation of the sys_agentOverrides object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_agentOverrides","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_agentOverrides":[{"id":"ID","agentName":"String","provider":"String","model":"String","systemPrompt":"Text","temperature":"Double","maxTokens":"Integer","responseFormat":"String","selectedTools":"Object","guardrails":"Object","enabled":"Boolean","updatedBy":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]}

Route Event agentoverride-updated

Event topic : wechess-agenthub-service-agentoverride-updated

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the sys_agentOverride data object itself.

The following JSON included in the payload illustrates the fullest representation of the sys_agentOverride object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_agentOverride","method":"PATCH","action":"update","appVersion":"Version","rowCount":1,"sys_agentOverride":{"id":"ID","agentName":"String","provider":"String","model":"String","systemPrompt":"Text","temperature":"Double","maxTokens":"Integer","responseFormat":"String","selectedTools":"Object","guardrails":"Object","enabled":"Boolean","updatedBy":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true}}

Route Event agentoverride-created

Event topic : wechess-agenthub-service-agentoverride-created

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the sys_agentOverride data object itself.

The following JSON included in the payload illustrates the fullest representation of the sys_agentOverride object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"201","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_agentOverride","method":"POST","action":"create","appVersion":"Version","rowCount":1,"sys_agentOverride":{"id":"ID","agentName":"String","provider":"String","model":"String","systemPrompt":"Text","temperature":"Double","maxTokens":"Integer","responseFormat":"String","selectedTools":"Object","guardrails":"Object","enabled":"Boolean","updatedBy":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true}}

Route Event agentoverride-deleted

Event topic : wechess-agenthub-service-agentoverride-deleted

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the sys_agentOverride data object itself.

The following JSON included in the payload illustrates the fullest representation of the sys_agentOverride object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_agentOverride","method":"DELETE","action":"delete","appVersion":"Version","rowCount":1,"sys_agentOverride":{"id":"ID","agentName":"String","provider":"String","model":"String","systemPrompt":"Text","temperature":"Double","maxTokens":"Integer","responseFormat":"String","selectedTools":"Object","guardrails":"Object","enabled":"Boolean","updatedBy":"ID","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":false}}

Route Event toolcatalog-listed

Event topic : wechess-agenthub-service-toolcatalog-listed

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the sys_toolCatalogs data object itself.

The following JSON included in the payload illustrates the fullest representation of the sys_toolCatalogs object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_toolCatalogs","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_toolCatalogs":[{"id":"ID","toolName":"String","serviceName":"String","description":"Text","parameters":"Object","lastRefreshed":"Date","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]}

Route Event toolcatalogentry-retrived

Event topic : wechess-agenthub-service-toolcatalogentry-retrived

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the sys_toolCatalog data object itself.

The following JSON included in the payload illustrates the fullest representation of the sys_toolCatalog object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_toolCatalog","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_toolCatalog":{"id":"ID","toolName":"String","serviceName":"String","description":"Text","parameters":"Object","lastRefreshed":"Date","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true}}

Route Event agentexecutions-listed

Event topic : wechess-agenthub-service-agentexecutions-listed

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the sys_agentExecutions data object itself.

The following JSON included in the payload illustrates the fullest representation of the sys_agentExecutions object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_agentExecutions","method":"GET","action":"list","appVersion":"Version","rowCount":"\"Number\"","sys_agentExecutions":[{"id":"ID","agentName":"String","agentType":"Enum","agentType_idx":"Integer","source":"Enum","source_idx":"Integer","userId":"ID","input":"Object","output":"Object","toolCalls":"Integer","tokenUsage":"Object","durationMs":"Integer","status":"Enum","status_idx":"Integer","error":"Text","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true},{},{}],"paging":{"pageNumber":"Number","pageRowCount":"NUmber","totalRowCount":"Number","pageCount":"Number"},"filters":[],"uiPermissions":[]}

Route Event agentexecution-retrived

Event topic : wechess-agenthub-service-agentexecution-retrived

Event payload:

The event payload, mirroring the REST API response, is structured as an encapsulated JSON. It includes metadata related to the API as well as the sys_agentExecution data object itself.

The following JSON included in the payload illustrates the fullest representation of the sys_agentExecution object. Note, however, that certain properties might be excluded in accordance with the object’s inherent logic.

{"status":"OK","statusCode":"200","elapsedMs":126,"ssoTime":120,"source":"db","cacheKey":"hexCode","userId":"ID","sessionId":"ID","requestId":"ID","dataName":"sys_agentExecution","method":"GET","action":"get","appVersion":"Version","rowCount":1,"sys_agentExecution":{"id":"ID","agentName":"String","agentType":"Enum","agentType_idx":"Integer","source":"Enum","source_idx":"Integer","userId":"ID","input":"Object","output":"Object","toolCalls":"Integer","tokenUsage":"Object","durationMs":"Integer","status":"Enum","status_idx":"Integer","error":"Text","recordVersion":"Integer","createdAt":"Date","updatedAt":"Date","_owner":"ID","isActive":true}}

Copyright

All sources, documents and other digital materials are copyright of .

About Us

For more information please visit our website: .

. .


Data Objects

Service Design Specification - Object Design for sys_agentOverride

Service Design Specification - Object Design for sys_agentOverride

wechess-agenthub-service documentation

Document Overview

This document outlines the object design for the sys_agentOverride model in our application. It includes details about the model’s attributes, relationships, and any specific validation or business logic that applies.

sys_agentOverride Data Object

Object Overview

Description: Runtime overrides for design-time agents. Null fields use the design default.

This object represents a core data structure within the service and acts as the blueprint for database interaction, API generation, and business logic enforcement. It is defined using the ObjectSettings pattern, which governs its behavior, access control, caching strategy, and integration points with other systems such as Stripe and Redis.

Core Configuration

Properties Schema

Property Type Required Description
agentName String Yes Design-time agent name this override applies to.
provider String No Override AI provider (e.g., openai, anthropic).
model String No Override model name.
systemPrompt Text No Override system prompt.
temperature Double No Override temperature (0-2).
maxTokens Integer No Override max tokens.
responseFormat String No Override response format (text/json).
selectedTools Object No Array of tool names from the catalog that this agent can use.
guardrails Object No Override guardrails: { maxToolCalls, timeout, maxTokenBudget }.
enabled Boolean Yes Enable or disable this agent.
updatedBy ID No User who last updated this override.

Default Values

Default values are automatically assigned to properties when a new object is created, if no value is provided in the request body. Since default values are applied on db level, they should be literal values, not expressions.If you want to use expressions, you can use transposed parameters in any business API to set default values dynamically.

Always Create with Default Values

Some of the default values are set to be always used when creating a new object, even if the property value is provided in the request body. It ensures that the property is always initialized with a default value when the object is created.

Constant Properties

agentName

Constant properties are defined to be immutable after creation, meaning they cannot be updated or changed once set. They are typically used for properties that should remain constant throughout the object’s lifecycle. A property is set to be constant if the Allow Update option is set to false.

Auto Update Properties

agentName provider model systemPrompt temperature maxTokens responseFormat selectedTools guardrails enabled updatedBy

An update crud API created with the option Auto Params enabled will automatically update these properties with the provided values in the request body. If you want to update any property in your own business logic not by user input, you can set the Allow Auto Update option to false. These properties will be added to the update API’s body parameters and can be updated by the user if any value is provided in the request body.

Elastic Search Indexing

agentName enabled

Properties that are indexed in Elastic Search will be searchable via the Elastic Search API. While all properties are stored in the elastic search index of the data object, only those marked for Elastic Search indexing will be available for search queries.

Database Indexing

agentName enabled

Properties that are indexed in the database will be optimized for query performance, allowing for faster data retrieval. Make a property indexed in the database if you want to use it frequently in query filters or sorting.

Unique Properties

agentName

Unique properties are enforced to have distinct values across all instances of the data object, preventing duplicate entries. Note that a unique property is automatically indexed in the database so you will not need to set the Indexed in DB option.

Session Data Properties

updatedBy

Session data properties are used to store data that is specific to the user session, allowing for personalized experiences and temporary data storage. If a property is configured as session data, it will be automatically mapped to the related field in the user session during CRUD operations. Note that session data properties can not be mutated by the user, but only by the system.


Service Design Specification - Object Design for sys_agentExecution

Service Design Specification - Object Design for sys_agentExecution

wechess-agenthub-service documentation

Document Overview

This document outlines the object design for the sys_agentExecution model in our application. It includes details about the model’s attributes, relationships, and any specific validation or business logic that applies.

sys_agentExecution Data Object

Object Overview

Description: Agent execution log. Records each agent invocation with input, output, and performance metrics.

This object represents a core data structure within the service and acts as the blueprint for database interaction, API generation, and business logic enforcement. It is defined using the ObjectSettings pattern, which governs its behavior, access control, caching strategy, and integration points with other systems such as Stripe and Redis.

Core Configuration

Properties Schema

Property Type Required Description
agentName String Yes Agent that was executed.
agentType Enum Yes Whether this was a design-time or dynamic agent.
source Enum Yes How the agent was triggered.
userId ID No User who triggered the execution.
input Object No Request input (truncated for large payloads).
output Object No Response output (truncated for large payloads).
toolCalls Integer No Number of tool calls made during execution.
tokenUsage Object No Token usage: { prompt, completion, total }.
durationMs Integer No Execution time in milliseconds.
status Enum Yes Execution status.
error Text No Error message if execution failed.

Default Values

Default values are automatically assigned to properties when a new object is created, if no value is provided in the request body. Since default values are applied on db level, they should be literal values, not expressions.If you want to use expressions, you can use transposed parameters in any business API to set default values dynamically.

Constant Properties

agentName agentType source userId input output toolCalls tokenUsage durationMs status error

Constant properties are defined to be immutable after creation, meaning they cannot be updated or changed once set. They are typically used for properties that should remain constant throughout the object’s lifecycle. A property is set to be constant if the Allow Update option is set to false.

Auto Update Properties

agentName agentType source userId input output toolCalls tokenUsage durationMs status error

An update crud API created with the option Auto Params enabled will automatically update these properties with the provided values in the request body. If you want to update any property in your own business logic not by user input, you can set the Allow Auto Update option to false. These properties will be added to the update API’s body parameters and can be updated by the user if any value is provided in the request body.

Enum Properties

Enum properties are defined with a set of allowed values, ensuring that only valid options can be assigned to them. The enum options value will be stored as strings in the database, but when a data object is created an addtional property with the same name plus an idx suffix will be created, which will hold the index of the selected enum option. You can use the index property to sort by the enum value or when your enum options represent a sequence of values.

Elastic Search Indexing

agentName agentType source userId toolCalls durationMs status

Properties that are indexed in Elastic Search will be searchable via the Elastic Search API. While all properties are stored in the elastic search index of the data object, only those marked for Elastic Search indexing will be available for search queries.

Database Indexing

agentName agentType source userId status

Properties that are indexed in the database will be optimized for query performance, allowing for faster data retrieval. Make a property indexed in the database if you want to use it frequently in query filters or sorting.

Filter Properties

agentName agentType source userId status

Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API’s that have “Auto Params” enabled.


Service Design Specification - Object Design for sys_toolCatalog

Service Design Specification - Object Design for sys_toolCatalog

wechess-agenthub-service documentation

Document Overview

This document outlines the object design for the sys_toolCatalog model in our application. It includes details about the model’s attributes, relationships, and any specific validation or business logic that applies.

sys_toolCatalog Data Object

Object Overview

Description: Cached tool catalog discovered from project services. Refreshed periodically.

This object represents a core data structure within the service and acts as the blueprint for database interaction, API generation, and business logic enforcement. It is defined using the ObjectSettings pattern, which governs its behavior, access control, caching strategy, and integration points with other systems such as Stripe and Redis.

Core Configuration

Properties Schema

Property Type Required Description
toolName String Yes Full tool name (e.g., service:apiName).
serviceName String Yes Source service name.
description Text No Tool description.
parameters Object No JSON Schema of tool parameters.
lastRefreshed Date No When this tool was last discovered/refreshed.

Default Values

Default values are automatically assigned to properties when a new object is created, if no value is provided in the request body. Since default values are applied on db level, they should be literal values, not expressions.If you want to use expressions, you can use transposed parameters in any business API to set default values dynamically.

Auto Update Properties

toolName serviceName description parameters lastRefreshed

An update crud API created with the option Auto Params enabled will automatically update these properties with the provided values in the request body. If you want to update any property in your own business logic not by user input, you can set the Allow Auto Update option to false. These properties will be added to the update API’s body parameters and can be updated by the user if any value is provided in the request body.

Elastic Search Indexing

toolName serviceName description

Properties that are indexed in Elastic Search will be searchable via the Elastic Search API. While all properties are stored in the elastic search index of the data object, only those marked for Elastic Search indexing will be available for search queries.

Database Indexing

toolName serviceName

Properties that are indexed in the database will be optimized for query performance, allowing for faster data retrieval. Make a property indexed in the database if you want to use it frequently in query filters or sorting.

Unique Properties

toolName

Unique properties are enforced to have distinct values across all instances of the data object, preventing duplicate entries. Note that a unique property is automatically indexed in the database so you will not need to set the Indexed in DB option.

Filter Properties

serviceName

Filter properties are used to define parameters that can be used in query filters, allowing for dynamic data retrieval based on user input or predefined criteria. These properties are automatically mapped as API parameters in the listing API’s that have “Auto Params” enabled.


Business APIs

Business API Design Specification - Get Agentoverride

Business API Design Specification - Get Agentoverride

A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic.

While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized.

This document provides an in-depth explanation of the architectural design of the getAgentOverride Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side.

Main Data Object and CRUD Operation

The getAgentOverride Business API is designed to handle a get operation on the Sys_agentOverride data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The getAgentOverride Business API includes a REST controller that can be triggered via the following route:

/v1/agentoverride/:sys_agentOverrideId

By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the Parameters section.

MCP Tool

REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This getAgentOverride Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The getAgentOverride Business API has 1 parameter that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client.

Business API parameters can be:

Regular Parameters

Name Type Required Default Location Data Path
sys_agentOverrideId ID Yes - urlpath sys_agentOverrideId
Description: This id paremeter is used to query the required data object.

Parameter Transformations

Some parameters are post-processed using transform scripts after being read from the request but before validation or workflow execution. Only parameters with a transform script are listed below.

No parameters are transformed in this API.

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the getAgentOverride Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Select Clause

Specifies which fields will be selected from the main data object during a get or list operation. Leave blank to select all properties. This applies only to get and list type APIs.",

``

Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({id:this.sys_agentOverrideId}), {"path":"services[4].businessLogic[0].whereClause.fullWhereClause"})

Get Options

Use these options to set get specific settings.

setAsRead: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed.

No setAsread field-value pair is configured.

Business Logic Workflow

[1] Step : startBusinessApi

Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Extracts parameters from request and Redis, applies defaults, and writes them to context.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Executes parameter transformation scripts, applies type coercion, merges derived values, and reshapes inputs for downstream milestones.


[4] Step : checkParameters

Validates required and custom parameters, enforcing business-specific rules and constraints.


[5] Step : checkBasicAuth

Performs login, role, and permission checks, and applies dynamic object-level access rules.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildWhereClause

Builds the WHERE clause for fetching the object and applies additional scoped filters if configured.

You can use the following settings to change some behavior of this step. whereClause

[7] Step : mainGetOperation

Executes the database fetch, retrieves the object, and stores it in context for enrichment or further checks.

You can use the following settings to change some behavior of this step. selectClause, getOptions

[8] Step : checkInstance

Performs instance-level validations, such as ownership, existence, or access conditions.


[9] Step : buildOutput

Assembles the response from the object, applies masking, formatting, and injects additional metadata if needed.


[10] Step : sendResponse

Delivers the response to the controller for client delivery.


[11] Step : raiseApiEvent

Triggers optional API-level events after workflow completion, sending messages to integrations like Kafka if configured.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The getAgentOverride api has got 1 regular client parameter

Parameter Type Required Population
sys_agentOverrideId ID true request.params?.[“sys_agentOverrideId”]

REST Request

To access the api you can use the REST controller with the path GET /v1/agentoverride/:sys_agentOverrideId

  axios({
    method: 'GET',
    url: `/v1/agentoverride/${sys_agentOverrideId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the sys_agentOverride object in the respones. However, some properties may be omitted based on the object’s internal logic.

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_agentOverride",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"sys_agentOverride": {
		"id": "ID",
		"agentName": "String",
		"provider": "String",
		"model": "String",
		"systemPrompt": "Text",
		"temperature": "Double",
		"maxTokens": "Integer",
		"responseFormat": "String",
		"selectedTools": "Object",
		"guardrails": "Object",
		"enabled": "Boolean",
		"updatedBy": "ID",
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"isActive": true
	}
}

Business API Design Specification - List Agentoverrides

Business API Design Specification - List Agentoverrides

A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic.

While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized.

This document provides an in-depth explanation of the architectural design of the listAgentOverrides Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side.

Main Data Object and CRUD Operation

The listAgentOverrides Business API is designed to handle a list operation on the Sys_agentOverride data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The listAgentOverrides Business API includes a REST controller that can be triggered via the following route:

/v1/agentoverrides

By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the Parameters section.

MCP Tool

REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This listAgentOverrides Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The listAgentOverrides Business API does not require any parameters to be provided from the controllers.

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the listAgentOverrides Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Select Clause

Specifies which fields will be selected from the main data object during a get or list operation. Leave blank to select all properties. This applies only to get and list type APIs.",

``

Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

null

List Options

Defines list-specific options including filtering logic, default sorting, and result customization for APIs that return multiple records.

List Sort By Sort order definitions for the result set. Multiple fields can be provided with direction (asc/desc).

Specific sort order is not configure, natural order (ascending id) will be used.

List Group By Grouping definitions for the result set. This is typically used for visual or report-based grouping.

The list is not grouped.

setAsRead: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed.

No setAsread field-value pair is configured.

Permission Filter Optional filter that applies permission constraints dynamically based on session or object roles. So that the list items are filtered by the user’s OBAC or ABAC permissions.

Permission filter is not active at the moment. Follow Mindbricks updates to be able to use it.

Pagination Options

Contains settings to configure pagination behavior for list APIs. Includes options like page size, offset, cursor support, and total count inclusion.

Business Logic Workflow

[1] Step : startBusinessApi

Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Reads request and Redis parameters, applies defaults, and writes them to context for downstream processing.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Transforms and normalizes parameters, derives dependent values, and reshapes inputs for the main list query.


[4] Step : checkParameters

Executes validation logic on required and custom parameters, enforcing business rules and cross-field consistency.


[5] Step : checkBasicAuth

Performs role-based access checks and applies dynamic membership or session-based restrictions.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildWhereClause

Constructs the main query WHERE clause and applies optional filters or scoped access controls.

You can use the following settings to change some behavior of this step. whereClause

[7] Step : mainListOperation

Executes the paginated database query, retrieves the list, and stores results in context for enrichment.

You can use the following settings to change some behavior of this step. selectClause, listOptions, paginationOptions

[8] Step : buildOutput

Assembles the list response, sanitizes sensitive fields, applies transformations, and injects extra context if needed.


[9] Step : sendResponse

Sends the paginated list to the client through the controller.


[10] Step : raiseApiEvent

Triggers optional post-workflow events, such as Kafka messages, logs, or system notifications.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources. The listAgentOverrides api has got no visible parameters.

REST Request

To access the api you can use the REST controller with the path GET /v1/agentoverrides

  axios({
    method: 'GET',
    url: '/v1/agentoverrides',
    data: {
    
    },
    params: {
    
        }
  });

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the sys_agentOverrides object in the respones. However, some properties may be omitted based on the object’s internal logic.

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_agentOverrides",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"sys_agentOverrides": [
		{
			"id": "ID",
			"agentName": "String",
			"provider": "String",
			"model": "String",
			"systemPrompt": "Text",
			"temperature": "Double",
			"maxTokens": "Integer",
			"responseFormat": "String",
			"selectedTools": "Object",
			"guardrails": "Object",
			"enabled": "Boolean",
			"updatedBy": "ID",
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID",
			"isActive": true
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Business API Design Specification - Update Agentoverride

Business API Design Specification - Update Agentoverride

A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic.

While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized.

This document provides an in-depth explanation of the architectural design of the updateAgentOverride Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side.

Main Data Object and CRUD Operation

The updateAgentOverride Business API is designed to handle a update operation on the Sys_agentOverride data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The updateAgentOverride Business API includes a REST controller that can be triggered via the following route:

/v1/agentoverride/:sys_agentOverrideId

By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the Parameters section.

MCP Tool

REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This updateAgentOverride Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The updateAgentOverride Business API has 11 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client.

Business API parameters can be:

Regular Parameters

Name Type Required Default Location Data Path
sys_agentOverrideId ID Yes - urlpath sys_agentOverrideId
Description: This id paremeter is used to select the required data object that will be updated
provider String No - body provider
Description: Override AI provider (e.g., openai, anthropic).
model String No - body model
Description: Override model name.
systemPrompt Text No - body systemPrompt
Description: Override system prompt.
temperature Double No - body temperature
Description: Override temperature (0-2).
maxTokens Integer No - body maxTokens
Description: Override max tokens.
responseFormat String No - body responseFormat
Description: Override response format (text/json).
selectedTools Object No - body selectedTools
Description: Array of tool names from the catalog that this agent can use.
guardrails Object No - body guardrails
Description: Override guardrails: { maxToolCalls, timeout, maxTokenBudget }.
enabled Boolean No - body enabled
Description: Enable or disable this agent.
updatedBy ID No - session userId
Description: User who last updated this override.

Parameter Transformations

Some parameters are post-processed using transform scripts after being read from the request but before validation or workflow execution. Only parameters with a transform script are listed below.

No parameters are transformed in this API.

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the updateAgentOverride Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({id:this.sys_agentOverrideId}), {"path":"services[4].businessLogic[2].whereClause.fullWhereClause"})

Data Clause

Defines custom field-value assignments used to modify or augment the default payload for create and update operations. These settings override values derived from the session or parameters if explicitly provided.", Note that a default data clause is always prepared by Mindbricks using data property settings, however any property in the data clause can be override by Data Clause Settings.

An update data clause populates all update-allowed properties of a data object, however the null properties (that are not provided by client) are ignored in db layer.

Custom Data Clause Override No custom data clause override configured

Actual Data Clause

The business api will use the following data clause. Note that any calculated value will be added to the data clause in the api manager.

{
  provider: this.provider,
  model: this.model,
  systemPrompt: this.systemPrompt,
  temperature: this.temperature,
  maxTokens: this.maxTokens,
  responseFormat: this.responseFormat,
  selectedTools: this.selectedTools ? (typeof this.selectedTools == 'string' ? JSON.parse(this.selectedTools) : this.selectedTools) : null,
  guardrails: this.guardrails ? (typeof this.guardrails == 'string' ? JSON.parse(this.guardrails) : this.guardrails) : null,
  enabled: this.enabled,
  updatedBy: this.updatedBy,
}

Business Logic Workflow

[1] Step : startBusinessApi

Manager initializes context, prepares request and session objects, and sets up internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Manager reads parameters from the request or Redis, applies defaults, and writes them into context for downstream milestones.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Manager executes parameter transform scripts and derives any helper values or reshaped payloads into the context.


[4] Step : checkParameters

Manager validates required parameters, checks ID formats (UUID/ObjectId), and ensures all preconditions for update are met.


[5] Step : checkBasicAuth

Manager performs login verification, role, and permission checks, enforcing tenant and access rules before update.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildWhereClause

Manager constructs the WHERE clause used to identify the record to update, applying ownership and parent checks if necessary.

You can use the following settings to change some behavior of this step. whereClause

[7] Step : fetchInstance

Manager fetches the existing record from the database and writes it to the context for validation or enrichment.


[8] Step : checkInstance

Manager performs instance-level validations, including ownership, existence, lock status, or other pre-update checks.


[9] Step : buildDataClause

Manager prepares the data clause for the update, applying transformations or enhancements before persisting.

You can use the following settings to change some behavior of this step. dataClause

[10] Step : mainUpdateOperation

Manager executes the update operation with the WHERE and data clauses. Database-level events are raised if configured.


[11] Step : buildOutput

Manager assembles the response object from the update result, masking fields or injecting additional metadata.


[12] Step : sendResponse

Manager sends the response back to the controller for delivery to the client.


[13] Step : raiseApiEvent

Manager triggers API-level events, sending relevant messages to Kafka or other integrations if configured.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The updateAgentOverride api has got 10 regular client parameters

Parameter Type Required Population
sys_agentOverrideId ID true request.params?.[“sys_agentOverrideId”]
provider String request.body?.[“provider”]
model String request.body?.[“model”]
systemPrompt Text request.body?.[“systemPrompt”]
temperature Double request.body?.[“temperature”]
maxTokens Integer request.body?.[“maxTokens”]
responseFormat String request.body?.[“responseFormat”]
selectedTools Object request.body?.[“selectedTools”]
guardrails Object request.body?.[“guardrails”]
enabled Boolean request.body?.[“enabled”]

REST Request

To access the api you can use the REST controller with the path PATCH /v1/agentoverride/:sys_agentOverrideId

  axios({
    method: 'PATCH',
    url: `/v1/agentoverride/${sys_agentOverrideId}`,
    data: {
            provider:"String",  
            model:"String",  
            systemPrompt:"Text",  
            temperature:"Double",  
            maxTokens:"Integer",  
            responseFormat:"String",  
            selectedTools:"Object",  
            guardrails:"Object",  
            enabled:"Boolean",  
    
    },
    params: {
    
        }
  });

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the sys_agentOverride object in the respones. However, some properties may be omitted based on the object’s internal logic.

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_agentOverride",
	"method": "PATCH",
	"action": "update",
	"appVersion": "Version",
	"rowCount": 1,
	"sys_agentOverride": {
		"id": "ID",
		"agentName": "String",
		"provider": "String",
		"model": "String",
		"systemPrompt": "Text",
		"temperature": "Double",
		"maxTokens": "Integer",
		"responseFormat": "String",
		"selectedTools": "Object",
		"guardrails": "Object",
		"enabled": "Boolean",
		"updatedBy": "ID",
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"isActive": true
	}
}

Business API Design Specification - Create Agentoverride

Business API Design Specification - Create Agentoverride

A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic.

While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized.

This document provides an in-depth explanation of the architectural design of the createAgentOverride Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side.

Main Data Object and CRUD Operation

The createAgentOverride Business API is designed to handle a create operation on the Sys_agentOverride data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The createAgentOverride Business API includes a REST controller that can be triggered via the following route:

/v1/agentoverride

By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the Parameters section.

MCP Tool

REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This createAgentOverride Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The createAgentOverride Business API has 11 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client.

Business API parameters can be:

Regular Parameters

Name Type Required Default Location Data Path
sys_agentOverrideId ID No - body sys_agentOverrideId
Description: This id paremeter is used to create the data object with a given specific id. Leave null for automatic id.
agentName String Yes - body agentName
Description: Design-time agent name this override applies to.
provider String No - body provider
Description: Override AI provider (e.g., openai, anthropic).
model String No - body model
Description: Override model name.
systemPrompt Text No - body systemPrompt
Description: Override system prompt.
temperature Double No - body temperature
Description: Override temperature (0-2).
maxTokens Integer No - body maxTokens
Description: Override max tokens.
responseFormat String No - body responseFormat
Description: Override response format (text/json).
selectedTools Object No - body selectedTools
Description: Array of tool names from the catalog that this agent can use.
guardrails Object No - body guardrails
Description: Override guardrails: { maxToolCalls, timeout, maxTokenBudget }.
updatedBy ID No - session userId
Description: User who last updated this override.

Parameter Transformations

Some parameters are post-processed using transform scripts after being read from the request but before validation or workflow execution. Only parameters with a transform script are listed below.

No parameters are transformed in this API.

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the createAgentOverride Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Data Clause

Defines custom field-value assignments used to modify or augment the default payload for create and update operations. These settings override values derived from the session or parameters if explicitly provided.", Note that a default data clause is always prepared by Mindbricks using data property settings, however any property in the data clause can be override by Data Clause Settings.

Custom Data Clause Override No custom data clause override configured

Actual Data Clause

The business api will use the following data clause. Note that any calculated value will be added to the data clause in the api manager.

{
  id: this.sys_agentOverrideId,
  agentName: this.agentName,
  provider: this.provider,
  model: this.model,
  systemPrompt: this.systemPrompt,
  temperature: this.temperature,
  maxTokens: this.maxTokens,
  responseFormat: this.responseFormat,
  selectedTools: this.selectedTools ? (typeof this.selectedTools == 'string' ? JSON.parse(this.selectedTools) : this.selectedTools) : null,
  guardrails: this.guardrails ? (typeof this.guardrails == 'string' ? JSON.parse(this.guardrails) : this.guardrails) : null,
  updatedBy: this.updatedBy,
}

Business Logic Workflow

[1] Step : startBusinessApi

Manager initializes context, populates session and request objects, prepares internal structures for parameter handling and workflow execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Manager reads input parameters, normalizes missing values, applies default type casting, and stores them in the API context.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Manager transforms parameters, computes derived values, flattens or remaps arrays/objects, and adjusts formats for downstream processing.


[4] Step : checkParameters

Manager executes built-in validations: required field checks, type enforcement, and basic business rules. Prevents operation if validation fails.


[5] Step : checkBasicAuth

Manager performs authentication and authorization checks: verifies session, user roles, permissions, and tenant restrictions.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildDataClause

Manager constructs the final data object for creation, fills auto-generated fields (IDs, timestamps, owner fields), and ensures schema consistency.

You can use the following settings to change some behavior of this step. dataClause

[7] Step : mainCreateOperation

Manager executes the database insert operation, updates indexes/caches, and triggers internal post-processing like linked default records.


[8] Step : buildOutput

Manager shapes the response: masks sensitive fields, resolves linked references, and formats output according to API contract.


[9] Step : sendResponse

Manager sends the response to the client and finalizes internal tasks like flushing logs or updating session state.


[10] Step : raiseApiEvent

Manager triggers API-level events (Kafka, WebSocket, async workflows) as the final internal step.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The createAgentOverride api has got 9 regular client parameters

Parameter Type Required Population
agentName String true request.body?.[“agentName”]
provider String false request.body?.[“provider”]
model String false request.body?.[“model”]
systemPrompt Text false request.body?.[“systemPrompt”]
temperature Double false request.body?.[“temperature”]
maxTokens Integer false request.body?.[“maxTokens”]
responseFormat String false request.body?.[“responseFormat”]
selectedTools Object false request.body?.[“selectedTools”]
guardrails Object false request.body?.[“guardrails”]

REST Request

To access the api you can use the REST controller with the path POST /v1/agentoverride

  axios({
    method: 'POST',
    url: '/v1/agentoverride',
    data: {
            agentName:"String",  
            provider:"String",  
            model:"String",  
            systemPrompt:"Text",  
            temperature:"Double",  
            maxTokens:"Integer",  
            responseFormat:"String",  
            selectedTools:"Object",  
            guardrails:"Object",  
    
    },
    params: {
    
        }
  });

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the sys_agentOverride object in the respones. However, some properties may be omitted based on the object’s internal logic.

{
	"status": "OK",
	"statusCode": "201",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_agentOverride",
	"method": "POST",
	"action": "create",
	"appVersion": "Version",
	"rowCount": 1,
	"sys_agentOverride": {
		"id": "ID",
		"agentName": "String",
		"provider": "String",
		"model": "String",
		"systemPrompt": "Text",
		"temperature": "Double",
		"maxTokens": "Integer",
		"responseFormat": "String",
		"selectedTools": "Object",
		"guardrails": "Object",
		"enabled": "Boolean",
		"updatedBy": "ID",
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"isActive": true
	}
}

Business API Design Specification - Delete Agentoverride

Business API Design Specification - Delete Agentoverride

A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic.

While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized.

This document provides an in-depth explanation of the architectural design of the deleteAgentOverride Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side.

Main Data Object and CRUD Operation

The deleteAgentOverride Business API is designed to handle a delete operation on the Sys_agentOverride data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The deleteAgentOverride Business API includes a REST controller that can be triggered via the following route:

/v1/agentoverride/:sys_agentOverrideId

By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the Parameters section.

MCP Tool

REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This deleteAgentOverride Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The deleteAgentOverride Business API has 1 parameter that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client.

Business API parameters can be:

Regular Parameters

Name Type Required Default Location Data Path
sys_agentOverrideId ID Yes - urlpath sys_agentOverrideId
Description: This id paremeter is used to select the required data object that will be deleted

Parameter Transformations

Some parameters are post-processed using transform scripts after being read from the request but before validation or workflow execution. Only parameters with a transform script are listed below.

No parameters are transformed in this API.

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the deleteAgentOverride Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({id:this.sys_agentOverrideId}), {"path":"services[4].businessLogic[4].whereClause.fullWhereClause"})

Delete Options

Use these options to set delete specific settings.

useSoftDelete: If true, the record will be marked as deleted (isActive: false) instead of removed. The implementation depends on the data object’s soft delete configuration.

Business Logic Workflow

[1] Step : startBusinessApi

Manager initializes context, prepares request/session objects, and sets up internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Manager reads and normalizes parameters, applies defaults, and stores them in the context for downstream steps.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Manager executes parameter transform scripts, computes derived values, and remaps objects or arrays as needed for later processing.


[4] Step : checkParameters

Manager runs built-in validations including required field checks, type enforcement, and deletion preconditions. Stops execution if validation fails.


[5] Step : checkBasicAuth

Manager validates session, user roles, permissions, and tenant-specific access rules to enforce basic auth restrictions.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildWhereClause

Manager generates the query conditions, applies ownership and parent checks, and ensures the clause is correct for the delete operation.

You can use the following settings to change some behavior of this step. whereClause

[7] Step : fetchInstance

Manager fetches the target record, applies filters from WHERE clause, and writes the instance to the context for further checks.


[8] Step : checkInstance

Manager performs object-level validations such as lock status, soft-delete eligibility, and multi-step approval enforcement.


[9] Step : mainDeleteOperation

Manager executes the delete query, updates related indexes/caches, and handles soft/hard delete logic according to configuration.

You can use the following settings to change some behavior of this step. deleteOptions

[10] Step : buildOutput

Manager shapes the response payload, masks sensitive fields, and formats related cleanup results for output.


[11] Step : sendResponse

Manager delivers the response to the client and finalizes any temporary internal structures.


[12] Step : raiseApiEvent

Manager triggers asynchronous API events, notifies queues or streams, and performs final cleanup for the workflow.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The deleteAgentOverride api has got 1 regular client parameter

Parameter Type Required Population
sys_agentOverrideId ID true request.params?.[“sys_agentOverrideId”]

REST Request

To access the api you can use the REST controller with the path DELETE /v1/agentoverride/:sys_agentOverrideId

  axios({
    method: 'DELETE',
    url: `/v1/agentoverride/${sys_agentOverrideId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the sys_agentOverride object in the respones. However, some properties may be omitted based on the object’s internal logic.

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_agentOverride",
	"method": "DELETE",
	"action": "delete",
	"appVersion": "Version",
	"rowCount": 1,
	"sys_agentOverride": {
		"id": "ID",
		"agentName": "String",
		"provider": "String",
		"model": "String",
		"systemPrompt": "Text",
		"temperature": "Double",
		"maxTokens": "Integer",
		"responseFormat": "String",
		"selectedTools": "Object",
		"guardrails": "Object",
		"enabled": "Boolean",
		"updatedBy": "ID",
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"isActive": false
	}
}

Business API Design Specification - List Toolcatalog

Business API Design Specification - List Toolcatalog

A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic.

While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized.

This document provides an in-depth explanation of the architectural design of the listToolCatalog Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side.

Main Data Object and CRUD Operation

The listToolCatalog Business API is designed to handle a list operation on the Sys_toolCatalog data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The listToolCatalog Business API includes a REST controller that can be triggered via the following route:

/v1/toolcatalog

By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the Parameters section.

MCP Tool

REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This listToolCatalog Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The listToolCatalog Business API has 1 parameter that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client.

Business API parameters can be:

Filter Parameters

The listToolCatalog api supports 1 optional filter parameter for filtering list results using URL query parameters. These parameters are only available for list type APIs.

serviceName Filter

Type: String
Description: Source service name.
Location: Query Parameter

Usage:

Non-Array Property (Case-Insensitive Partial Matching):

Examples:

// Find records with "john" in the field (case-insensitive partial match)
GET /v1/toolcatalog?serviceName=john
// Matches: "John", "Johnny", "johnson", "McJohn", etc.

// Find records with multiple values (use multiple parameters)
GET /v1/toolcatalog?serviceName=laptop&serviceName=phone&serviceName=tablet
// Matches records containing "laptop", "phone", or "tablet" anywhere in the field

// Find records without this field
GET /v1/toolcatalog?serviceName=null

Parameter Transformations

Some parameters are post-processed using transform scripts after being read from the request but before validation or workflow execution. Only parameters with a transform script are listed below.

No parameters are transformed in this API.

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the listToolCatalog Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Select Clause

Specifies which fields will be selected from the main data object during a get or list operation. Leave blank to select all properties. This applies only to get and list type APIs.",

``

Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

null

List Options

Defines list-specific options including filtering logic, default sorting, and result customization for APIs that return multiple records.

List Sort By Sort order definitions for the result set. Multiple fields can be provided with direction (asc/desc).

Specific sort order is not configure, natural order (ascending id) will be used.

List Group By Grouping definitions for the result set. This is typically used for visual or report-based grouping.

The list is not grouped.

setAsRead: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed.

No setAsread field-value pair is configured.

Permission Filter Optional filter that applies permission constraints dynamically based on session or object roles. So that the list items are filtered by the user’s OBAC or ABAC permissions.

Permission filter is not active at the moment. Follow Mindbricks updates to be able to use it.

Pagination Options

Contains settings to configure pagination behavior for list APIs. Includes options like page size, offset, cursor support, and total count inclusion.

Business Logic Workflow

[1] Step : startBusinessApi

Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Reads request and Redis parameters, applies defaults, and writes them to context for downstream processing.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Transforms and normalizes parameters, derives dependent values, and reshapes inputs for the main list query.


[4] Step : checkParameters

Executes validation logic on required and custom parameters, enforcing business rules and cross-field consistency.


[5] Step : checkBasicAuth

Performs role-based access checks and applies dynamic membership or session-based restrictions.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildWhereClause

Constructs the main query WHERE clause and applies optional filters or scoped access controls.

You can use the following settings to change some behavior of this step. whereClause

[7] Step : mainListOperation

Executes the paginated database query, retrieves the list, and stores results in context for enrichment.

You can use the following settings to change some behavior of this step. selectClause, listOptions, paginationOptions

[8] Step : buildOutput

Assembles the list response, sanitizes sensitive fields, applies transformations, and injects extra context if needed.


[9] Step : sendResponse

Sends the paginated list to the client through the controller.


[10] Step : raiseApiEvent

Triggers optional post-workflow events, such as Kafka messages, logs, or system notifications.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The listToolCatalog api has 1 filter parameter available for filtering list results. See the Filter Parameters section above for detailed usage examples.

Filter Parameter Type Array Property Description
serviceName String No Source service name.

REST Request

To access the api you can use the REST controller with the path GET /v1/toolcatalog

  axios({
    method: 'GET',
    url: '/v1/toolcatalog',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section for usage examples)
        // serviceName: '<value>' // Filter by serviceName
            }
  });

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the sys_toolCatalogs object in the respones. However, some properties may be omitted based on the object’s internal logic.

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_toolCatalogs",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"sys_toolCatalogs": [
		{
			"id": "ID",
			"toolName": "String",
			"serviceName": "String",
			"description": "Text",
			"parameters": "Object",
			"lastRefreshed": "Date",
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID",
			"isActive": true
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Business API Design Specification - Get Toolcatalogentry

Business API Design Specification - Get Toolcatalogentry

A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic.

While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized.

This document provides an in-depth explanation of the architectural design of the getToolCatalogEntry Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side.

Main Data Object and CRUD Operation

The getToolCatalogEntry Business API is designed to handle a get operation on the Sys_toolCatalog data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The getToolCatalogEntry Business API includes a REST controller that can be triggered via the following route:

/v1/toolcatalogentry/:sys_toolCatalogId

By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the Parameters section.

MCP Tool

REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This getToolCatalogEntry Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The getToolCatalogEntry Business API has 1 parameter that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client.

Business API parameters can be:

Regular Parameters

Name Type Required Default Location Data Path
sys_toolCatalogId ID Yes - urlpath sys_toolCatalogId
Description: This id paremeter is used to query the required data object.

Parameter Transformations

Some parameters are post-processed using transform scripts after being read from the request but before validation or workflow execution. Only parameters with a transform script are listed below.

No parameters are transformed in this API.

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the getToolCatalogEntry Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Select Clause

Specifies which fields will be selected from the main data object during a get or list operation. Leave blank to select all properties. This applies only to get and list type APIs.",

``

Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({id:this.sys_toolCatalogId}), {"path":"services[4].businessLogic[6].whereClause.fullWhereClause"})

Get Options

Use these options to set get specific settings.

setAsRead: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed.

No setAsread field-value pair is configured.

Business Logic Workflow

[1] Step : startBusinessApi

Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Extracts parameters from request and Redis, applies defaults, and writes them to context.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Executes parameter transformation scripts, applies type coercion, merges derived values, and reshapes inputs for downstream milestones.


[4] Step : checkParameters

Validates required and custom parameters, enforcing business-specific rules and constraints.


[5] Step : checkBasicAuth

Performs login, role, and permission checks, and applies dynamic object-level access rules.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildWhereClause

Builds the WHERE clause for fetching the object and applies additional scoped filters if configured.

You can use the following settings to change some behavior of this step. whereClause

[7] Step : mainGetOperation

Executes the database fetch, retrieves the object, and stores it in context for enrichment or further checks.

You can use the following settings to change some behavior of this step. selectClause, getOptions

[8] Step : checkInstance

Performs instance-level validations, such as ownership, existence, or access conditions.


[9] Step : buildOutput

Assembles the response from the object, applies masking, formatting, and injects additional metadata if needed.


[10] Step : sendResponse

Delivers the response to the controller for client delivery.


[11] Step : raiseApiEvent

Triggers optional API-level events after workflow completion, sending messages to integrations like Kafka if configured.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The getToolCatalogEntry api has got 1 regular client parameter

Parameter Type Required Population
sys_toolCatalogId ID true request.params?.[“sys_toolCatalogId”]

REST Request

To access the api you can use the REST controller with the path GET /v1/toolcatalogentry/:sys_toolCatalogId

  axios({
    method: 'GET',
    url: `/v1/toolcatalogentry/${sys_toolCatalogId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the sys_toolCatalog object in the respones. However, some properties may be omitted based on the object’s internal logic.

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_toolCatalog",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"sys_toolCatalog": {
		"id": "ID",
		"toolName": "String",
		"serviceName": "String",
		"description": "Text",
		"parameters": "Object",
		"lastRefreshed": "Date",
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"isActive": true
	}
}

Business API Design Specification - List Agentexecutions

Business API Design Specification - List Agentexecutions

A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic.

While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized.

This document provides an in-depth explanation of the architectural design of the listAgentExecutions Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side.

Main Data Object and CRUD Operation

The listAgentExecutions Business API is designed to handle a list operation on the Sys_agentExecution data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The listAgentExecutions Business API includes a REST controller that can be triggered via the following route:

/v1/agentexecutions

By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the Parameters section.

MCP Tool

REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This listAgentExecutions Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The listAgentExecutions Business API has 5 parameters that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client.

Business API parameters can be:

Filter Parameters

The listAgentExecutions api supports 5 optional filter parameters for filtering list results using URL query parameters. These parameters are only available for list type APIs.

agentName Filter

Type: String
Description: Agent that was executed.
Location: Query Parameter

Usage:

Non-Array Property (Case-Insensitive Partial Matching):

Examples:

// Find records with "john" in the field (case-insensitive partial match)
GET /v1/agentexecutions?agentName=john
// Matches: "John", "Johnny", "johnson", "McJohn", etc.

// Find records with multiple values (use multiple parameters)
GET /v1/agentexecutions?agentName=laptop&agentName=phone&agentName=tablet
// Matches records containing "laptop", "phone", or "tablet" anywhere in the field

// Find records without this field
GET /v1/agentexecutions?agentName=null

agentType Filter

Type: Enum
Description: Whether this was a design-time or dynamic agent.
Location: Query Parameter

Usage:

Examples:

// Get records with specific enum value
GET /v1/agentexecutions?agentType=active

// Get records with multiple enum values (use multiple parameters)
GET /v1/agentexecutions?agentType=active&agentType=pending

// Get records without this field
GET /v1/agentexecutions?agentType=null

source Filter

Type: Enum
Description: How the agent was triggered.
Location: Query Parameter

Usage:

Examples:

// Get records with specific enum value
GET /v1/agentexecutions?source=active

// Get records with multiple enum values (use multiple parameters)
GET /v1/agentexecutions?source=active&source=pending

// Get records without this field
GET /v1/agentexecutions?source=null

userId Filter

Type: ID
Description: User who triggered the execution.
Location: Query Parameter

Usage:

Non-Array Property:

Examples:

// Get records with a specific ID
GET /v1/agentexecutions?userId=550e8400-e29b-41d4-a716-446655440000

// Get records with multiple IDs (use multiple parameters)
GET /v1/agentexecutions?userId=550e8400-e29b-41d4-a716-446655440000&userId=660e8400-e29b-41d4-a716-446655440001

// Get records without this field
GET /v1/agentexecutions?userId=null

status Filter

Type: Enum
Description: Execution status.
Location: Query Parameter

Usage:

Examples:

// Get records with specific enum value
GET /v1/agentexecutions?status=active

// Get records with multiple enum values (use multiple parameters)
GET /v1/agentexecutions?status=active&status=pending

// Get records without this field
GET /v1/agentexecutions?status=null

Parameter Transformations

Some parameters are post-processed using transform scripts after being read from the request but before validation or workflow execution. Only parameters with a transform script are listed below.

No parameters are transformed in this API.

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the listAgentExecutions Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Select Clause

Specifies which fields will be selected from the main data object during a get or list operation. Leave blank to select all properties. This applies only to get and list type APIs.",

``

Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

null

List Options

Defines list-specific options including filtering logic, default sorting, and result customization for APIs that return multiple records.

List Sort By Sort order definitions for the result set. Multiple fields can be provided with direction (asc/desc).

Specific sort order is not configure, natural order (ascending id) will be used.

List Group By Grouping definitions for the result set. This is typically used for visual or report-based grouping.

The list is not grouped.

setAsRead: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed.

No setAsread field-value pair is configured.

Permission Filter Optional filter that applies permission constraints dynamically based on session or object roles. So that the list items are filtered by the user’s OBAC or ABAC permissions.

Permission filter is not active at the moment. Follow Mindbricks updates to be able to use it.

Pagination Options

Contains settings to configure pagination behavior for list APIs. Includes options like page size, offset, cursor support, and total count inclusion.

Business Logic Workflow

[1] Step : startBusinessApi

Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Reads request and Redis parameters, applies defaults, and writes them to context for downstream processing.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Transforms and normalizes parameters, derives dependent values, and reshapes inputs for the main list query.


[4] Step : checkParameters

Executes validation logic on required and custom parameters, enforcing business rules and cross-field consistency.


[5] Step : checkBasicAuth

Performs role-based access checks and applies dynamic membership or session-based restrictions.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildWhereClause

Constructs the main query WHERE clause and applies optional filters or scoped access controls.

You can use the following settings to change some behavior of this step. whereClause

[7] Step : mainListOperation

Executes the paginated database query, retrieves the list, and stores results in context for enrichment.

You can use the following settings to change some behavior of this step. selectClause, listOptions, paginationOptions

[8] Step : buildOutput

Assembles the list response, sanitizes sensitive fields, applies transformations, and injects extra context if needed.


[9] Step : sendResponse

Sends the paginated list to the client through the controller.


[10] Step : raiseApiEvent

Triggers optional post-workflow events, such as Kafka messages, logs, or system notifications.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The listAgentExecutions api has 5 filter parameters available for filtering list results. See the Filter Parameters section above for detailed usage examples.

Filter Parameter Type Array Property Description
agentName String No Agent that was executed.
agentType Enum No Whether this was a design-time or dynamic agent.
source Enum No How the agent was triggered.
userId ID No User who triggered the execution.
status Enum No Execution status.

REST Request

To access the api you can use the REST controller with the path GET /v1/agentexecutions

  axios({
    method: 'GET',
    url: '/v1/agentexecutions',
    data: {
    
    },
    params: {
    
        // Filter parameters (see Filter Parameters section for usage examples)
        // agentName: '<value>' // Filter by agentName
        // agentType: '<value>' // Filter by agentType
        // source: '<value>' // Filter by source
        // userId: '<value>' // Filter by userId
        // status: '<value>' // Filter by status
            }
  });

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the sys_agentExecutions object in the respones. However, some properties may be omitted based on the object’s internal logic.

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_agentExecutions",
	"method": "GET",
	"action": "list",
	"appVersion": "Version",
	"rowCount": "\"Number\"",
	"sys_agentExecutions": [
		{
			"id": "ID",
			"agentName": "String",
			"agentType": "Enum",
			"agentType_idx": "Integer",
			"source": "Enum",
			"source_idx": "Integer",
			"userId": "ID",
			"input": "Object",
			"output": "Object",
			"toolCalls": "Integer",
			"tokenUsage": "Object",
			"durationMs": "Integer",
			"status": "Enum",
			"status_idx": "Integer",
			"error": "Text",
			"recordVersion": "Integer",
			"createdAt": "Date",
			"updatedAt": "Date",
			"_owner": "ID",
			"isActive": true
		},
		{},
		{}
	],
	"paging": {
		"pageNumber": "Number",
		"pageRowCount": "NUmber",
		"totalRowCount": "Number",
		"pageCount": "Number"
	},
	"filters": [],
	"uiPermissions": []
}

Business API Design Specification - Get Agentexecution

Business API Design Specification - Get Agentexecution

A Business API is a set of logical actions centered around a main data object. These actions can range from simple CRUD operations to complex workflows that implement intricate business logic.

While the term “API” traditionally refers to an interface that allows software systems to interact, in Mindbricks a Business API represents a broader concept. It encapsulates a business workflow around a data object, going beyond basic CRUD operations to include rich, internally coordinated actions that can be fully designed and customized.

This document provides an in-depth explanation of the architectural design of the getAgentExecution Business API. It is intended to guide backend architects and developers in maintaining the current design. Additionally, frontend developers and frontend AI agents can use this document to understand how to properly consume this API on the client side.

Main Data Object and CRUD Operation

The getAgentExecution Business API is designed to handle a get operation on the Sys_agentExecution data object. This operation is performed under the specified conditions and may include additional, coordinated actions as part of the workflow.

API Description

API Options

API Controllers

A Mindbricks Business API can be accessed through multiple interfaces, including REST, gRPC, WebSocket, Kafka, or Cron. The controllers listed below map the business workflow to a specific interface, enabling consistent interaction regardless of the communication channel.

REST Controller

The getAgentExecution Business API includes a REST controller that can be triggered via the following route:

/v1/agentexecution/:sys_agentExecutionId

By sending a request to this route using the service API address, you can execute this Business API. Parameters can be provided in multiple HTTP locations, including the URL path, URL query, request body, and request headers. Detailed information about these parameters is provided in the Parameters section.

MCP Tool

REST controllers also expose the Business API as a tool in the MCP, making it accessible to AI agents. This getAgentExecution Business API will be registered as a tool on the MCP server within the service binding.

API Parameters

The getAgentExecution Business API has 1 parameter that must be sent from the controller. Note that all parameters, except session and Redis parameters, should be provided by the client.

Business API parameters can be:

Regular Parameters

Name Type Required Default Location Data Path
sys_agentExecutionId ID Yes - urlpath sys_agentExecutionId
Description: This id paremeter is used to query the required data object.

Parameter Transformations

Some parameters are post-processed using transform scripts after being read from the request but before validation or workflow execution. Only parameters with a transform script are listed below.

No parameters are transformed in this API.

AUTH Configuration

The authentication and authorization configuration defines the core access rules for the getAgentExecution Business API. These checks are applied after parameter validation and before executing the main business logic.

While these settings cover the most common scenarios, more fine-grained or conditional access control—such as permissions based on object context, nested memberships, or custom workflows—should be implemented using explicit actions like PermissionCheckAction, MembershipCheckAction, or ObjectPermissionCheckAction.

Login Requirement

This API requires login (loginRequired = true). Requests from non-logged-in users will return a 401 Unauthorized error. Login is necessary but not sufficient, as additional role, permission, or other authorization checks may still apply.


Ownership Checks


Role and Permission Settings


Select Clause

Specifies which fields will be selected from the main data object during a get or list operation. Leave blank to select all properties. This applies only to get and list type APIs.",

``

Where Clause

Defines the criteria used to locate the target record(s) for the main operation. This is expressed as a query object and applies to get, list, update, and delete APIs. All API types except list are expected to affect a single record.

If nothing is configured for (get, update, delete) the id fields will be the select criteria.

Select By: A list of fields that must be matched exactly as part of the WHERE clause. This is not a filter — it is a required selection rule. In single-record APIs (get, update, delete), it defines how a unique record is located. In list APIs, it scopes the results to only entries matching the given values. Note that selectBy fields will be ignored if fullWhereClause is set.

The business api configuration has no selectBy setting.

Full Where Clause An MScript query expression that overrides all default WHERE clause logic. Use this for fully customized queries. When fullWhereClause is set, selectBy is ignored, however additional selects will still be applied to final where clause.

The business api configuration has no fullWhereClause setting.

Additional Clauses A list of conditionally applied MScript query fragments. These clauses are appended only if their conditions evaluate to true. If no condition is set it will be applied to the where clause directly.

The business api configuration has no additionalClauses setting.

Actual Where Clause This where clause is built using whereClause configuration (if set) and default business logic.

runMScript(() => ({id:this.sys_agentExecutionId}), {"path":"services[4].businessLogic[8].whereClause.fullWhereClause"})

Get Options

Use these options to set get specific settings.

setAsRead: An optional array of field-value mappings that will be updated after the read operation. Useful for marking items as read or viewed.

No setAsread field-value pair is configured.

Business Logic Workflow

[1] Step : startBusinessApi

Initializes context with request and session objects. Prepares internal structures for parameter handling and milestone execution.

You can use the following settings to change some behavior of this step. apiOptions, restSettings, grpcSettings, kafkaSettings, sseSettings, cronSettings

[2] Step : readParameters

Extracts parameters from request and Redis, applies defaults, and writes them to context.

You can use the following settings to change some behavior of this step. customParameters, redisParameters

[3] Step : transposeParameters

Executes parameter transformation scripts, applies type coercion, merges derived values, and reshapes inputs for downstream milestones.


[4] Step : checkParameters

Validates required and custom parameters, enforcing business-specific rules and constraints.


[5] Step : checkBasicAuth

Performs login, role, and permission checks, and applies dynamic object-level access rules.

You can use the following settings to change some behavior of this step. authOptions

[6] Step : buildWhereClause

Builds the WHERE clause for fetching the object and applies additional scoped filters if configured.

You can use the following settings to change some behavior of this step. whereClause

[7] Step : mainGetOperation

Executes the database fetch, retrieves the object, and stores it in context for enrichment or further checks.

You can use the following settings to change some behavior of this step. selectClause, getOptions

[8] Step : checkInstance

Performs instance-level validations, such as ownership, existence, or access conditions.


[9] Step : buildOutput

Assembles the response from the object, applies masking, formatting, and injects additional metadata if needed.


[10] Step : sendResponse

Delivers the response to the controller for client delivery.


[11] Step : raiseApiEvent

Triggers optional API-level events after workflow completion, sending messages to integrations like Kafka if configured.


Rest Usage

Rest Client Parameters

Client parameters are the api parameters that are visible to client and will be populated by the client. Note that some api parameters are not visible to client because they are populated by internal system, session, calculation or joint sources.

The getAgentExecution api has got 1 regular client parameter

Parameter Type Required Population
sys_agentExecutionId ID true request.params?.[“sys_agentExecutionId”]

REST Request

To access the api you can use the REST controller with the path GET /v1/agentexecution/:sys_agentExecutionId

  axios({
    method: 'GET',
    url: `/v1/agentexecution/${sys_agentExecutionId}`,
    data: {
    
    },
    params: {
    
        }
  });

REST Response

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property. For error handling, refer to the “Error Response” section.

Following JSON represents the most comprehensive form of the sys_agentExecution object in the respones. However, some properties may be omitted based on the object’s internal logic.

{
	"status": "OK",
	"statusCode": "200",
	"elapsedMs": 126,
	"ssoTime": 120,
	"source": "db",
	"cacheKey": "hexCode",
	"userId": "ID",
	"sessionId": "ID",
	"requestId": "ID",
	"dataName": "sys_agentExecution",
	"method": "GET",
	"action": "get",
	"appVersion": "Version",
	"rowCount": 1,
	"sys_agentExecution": {
		"id": "ID",
		"agentName": "String",
		"agentType": "Enum",
		"agentType_idx": "Integer",
		"source": "Enum",
		"source_idx": "Integer",
		"userId": "ID",
		"input": "Object",
		"output": "Object",
		"toolCalls": "Integer",
		"tokenUsage": "Object",
		"durationMs": "Integer",
		"status": "Enum",
		"status_idx": "Integer",
		"error": "Text",
		"recordVersion": "Integer",
		"createdAt": "Date",
		"updatedAt": "Date",
		"_owner": "ID",
		"isActive": true
	}
}

Bff Service

Service Design Specification

Service Design Specification

BFF Service Documentation Version: 1.0.2


Scope

This document provides a comprehensive architectural overview of the BFF Service, a Backend-for-Frontend layer designed to unify access to backend ElasticSearch indices and event-driven aggregation logic. The service offers a full REST API suite and listens to Kafka topics to synchronize enriched views.

This document is intended for:

For endpoint-level specifications, refer to the REST API Guide. For listener-level behavior, refer to the Event API Guide.


Service Settings


API Routes Overview

The BFF service exposes a dynamic REST API interface that provides full access to ElasticSearch indices. These include list, count, filter, and schema-based interactions for both stored and virtual views.

For full documentation of REST routes, including supported methods and examples, refer to the REST API Guide.


Kafka Event Listeners

The BFF service listens to ElasticSearch-related Kafka topics to maintain enriched and denormalized indices. These listeners trigger view aggregation functions upon receiving create, update, or delete events for primary and related entities.

For detailed behavior, payloads, and listener-to-function mappings, refer to the Event Guide.


Aggregation Strategy

Each view is either:

For each stored view:

Final document is saved to: <project_codename>_<view.newIndexName>


Middleware

Error Handling

Request Validation

Async Wrapper


Elasticsearch Utilities


Cron Repair Logic

Runs periodically to ensure data integrity:


Environment Variables

Variable Description
HTTP_PORT Service port
KAFKA_BROKER Kafka broker host
ELASTIC_URL Elasticsearch base URL
CORS_ORIGIN Allowed frontend origin (optional)
NODE_ENV Environment (dev, prod)
SERVICE_URL Used for injected API face config
SERVICE_SHORT_NAME Used in injected auth URL

App Lifecycle

  1. Loads env: .env, .prod.env, etc.

  2. Bootstraps Express app with:

    • CORS setup
    • JSON + cookie parsers
    • Dynamic routes
    • Swagger and API Face
  3. Starts:

    • Kafka listeners
    • Cron repair jobs
    • Full enrichment pipelines
  4. Handles SIGINT to close server cleanly


Testing Strategy

Unit Tests

Integration Tests

Load Tests (Optional)



REST API GUIDE

REST API GUIDE

BFF SERVICE

Version: 1.0.2

BFF service is a microservice that acts as a bridge between the client and the backend services. It provides a unified API for the client to interact with multiple backend services, simplifying the communication process and improving performance.

Architectural Design Credit and Contact Information

The architectural design of this microservice is credited to.
For inquiries, feedback, or further information regarding the architecture, please direct your communication to:

Email:

We encourage open communication and welcome any questions or discussions related to the architectural aspects of this microservice.

Documentation Scope

Welcome to the official documentation for the BFF Service’s REST API. This document is designed to provide a comprehensive guide to interfacing with our BFF Service exclusively through RESTful API endpoints.

Intended Audience

This documentation is intended for developers and integrators who are looking to interact with the BFF Service via HTTP requests for purposes such as listing, filtering, and searching data.

Overview

Within these pages, you will find detailed information on how to effectively utilize the REST API, including authentication methods, request and response formats, endpoint descriptions, and examples of common use cases.

Beyond REST
It’s important to note that the BFF Service also supports alternative methods of interaction, such as gRPC and messaging via a Message Broker. These communication methods are beyond the scope of this document. For information regarding these protocols, please refer to their respective documentation.


Resources

Elastic Index Resource

Resource Definition: A virtual resource representing dynamic search data from a specified index.


Route: List Records

Route Definition: Returns a paginated list from the elastic index. Route Type: list
Default access route: POST /:indexName/list

Parameters

Parameter Type Required Population
indexName String Yes path.param
page Number No query.page
limit Number No query.limit
sortBy String No query.sortBy
sortOrder String No query.sortOrder
q String No query.q
filters Object Yes body
axios({
  method: "POST",
  url: `/${indexName}/list`,
  data: {
    filters: "Object"
  },
  params: {
    page: "Number",
    limit: "Number",
    sortBy: "String",
    sortOrder: "String",
    q: "String"
  }
});

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a "status": "OK" property.

---

Default access route: GET /:indexName/list

Parameters

Parameter Type Required Population
indexName String Yes path.param
page Number No query.page
limit Number No query.limit
sortBy String No query.sortBy
sortOrder String No query.sortOrder
q String No query.q
axios({
  method: "GET",
  url: `/${indexName}/list`,
  data:{},
  params: {
    page: "Number",
    limit: "Number",
    sortBy: "String",
    sortOrder: "String",
    q: "String"
  }
});

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a “status”: “OK” property.

Route: Count Records

Route Definition: Counts matching documents in the elastic index. Route Type: count
Default access route: POST /:indexName/count

Parameters

Parameter Type Required Population
indexName String Yes path.param
q String No query.q
filters Object Yes body
axios({
  method: "POST",
  url: `/${indexName}/count`,
  data: {
    filters: "Object"
  },
  params: {
    q: "String"
  }
});

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a “status”: “OK” property.


Default access route: GET /:indexName/count

Parameters

Parameter Type Required Population
indexName String Yes path.param
q String No query.q
axios({
  method: "GET",
  url: `/${indexName}/count`,
  data:{},
  params: {
    q: "String"
  }
});

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a “status”: “OK” property.

Route: Get Index Schema

Route Definition: Returns the schema for the elastic index. Route Type: get
Default access route: GET /:indexName/schema

Parameters

Parameter Type Required Population
indexName String Yes path.param
axios({
  method: "GET",
  url: `/${indexName}/schema`,
  data:{},
  params: {}
});

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a “status”: “OK” property.

Route: Filters

GET /:indexName/filters

Route Type: get

Parameters

Parameter Type Required Population
indexName String Yes path.param
page Number No query.page
limit Number No query.limit
axios({
  method: "GET",
  url: `/${indexName}/filters`,
  data:{},
  params: {
    page: "Number",
    limit: "Number"
  }
});

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a “status”: “OK” property.

POST /:indexName/filters

Route Type: create

Parameters

Parameter Type Required Population
indexName String Yes path.param
filters Object Yes body
axios({
  method: "POST",
  url: `/${indexName}/filters`,
  data: {
    filterName: "String",
    conditions: "Object"
  },
  params: {}
});

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a “status”: “OK” property.

DELETE /:indexName/filters/:filterId

Route Type: delete

Parameters

Parameter Type Required Population
indexName String Yes path.param
filterId String Yes path.param
axios({
  method: "DELETE",
  url: `/${indexName}/filters/${filterId}`,
  data:{},
  params: {}
});

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a “status”: “OK” property.

Route: Get One Record

Route Type: get
Default access route: GET /:indexName/:id

Parameters

Parameter Type Required Population
indexName String Yes path.param
id ID Yes path.param
axios({
  method: "GET",
  url: `/${indexName}/${id}`,
  data:{},
  params: {}

});

The API response is encapsulated within a JSON envelope. Successful operations return an HTTP status code of 200 for get, list, update, or delete requests, and 201 for create requests. Each successful response includes a “status”: “OK” property.

Route: Get All Aggregated Records

Route Definition: Retrieves a full list of aggregated view data. Route Type: list Default access route: GET /playerProfileView

Example:

axios({
  method: "GET",
  url: `/playerProfileView`,
  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 /playerProfileView/:id

Parameters

Parameter Type Required Population
id ID Yes path.param
axios({
  method: "GET",
  url: `/playerProfileView/${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 /chessGameDetailView

Example:

axios({
  method: "GET",
  url: `/chessGameDetailView`,
  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 /chessGameDetailView/:id

Parameters

Parameter Type Required Population
id ID Yes path.param
axios({
  method: "GET",
  url: `/chessGameDetailView/${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 /lobbyChatMessageView

Example:

axios({
  method: "GET",
  url: `/lobbyChatMessageView`,
  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 /lobbyChatMessageView/:id

Parameters

Parameter Type Required Population
id ID Yes path.param
axios({
  method: "GET",
  url: `/lobbyChatMessageView/${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 /invitationNotificationView

Example:

axios({
  method: "GET",
  url: `/invitationNotificationView`,
  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 /invitationNotificationView/:id

Parameters

Parameter Type Required Population
id ID Yes path.param
axios({
  method: "GET",
  url: `/invitationNotificationView/${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 /gameTerminatedNotificationView

Example:

axios({
  method: "GET",
  url: `/gameTerminatedNotificationView`,
  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 /gameTerminatedNotificationView/:id

Parameters

Parameter Type Required Population
id ID Yes path.param
axios({
  method: "GET",
  url: `/gameTerminatedNotificationView/${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 /chatModerationNotificationView

Example:

axios({
  method: "GET",
  url: `/chatModerationNotificationView`,
  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 /chatModerationNotificationView/:id

Parameters

Parameter Type Required Population
id ID Yes path.param
axios({
  method: "GET",
  url: `/chatModerationNotificationView/${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 /chessGameListView/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: `/chessGameListView/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 /chessGameListView/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: `/chessGameListView/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 /chessGameListView/count

Parameters

Parameter Type Required Population
q String No query.q
filters Object Yes body
axios({
  method: "POST",
  url: `/chessGameListView/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 /chessGameListView/count

Parameters

Parameter Type Required Population
q String No query.q
axios({
  method: "GET",
  url: `/chessGameListView/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 /chessGameListView/schema

axios({
  method: "GET",
  url: `/chessGameListView/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 /chessGameListView/filters

Route Type: get

Parameters

Parameter Type Required Population
page Number No query.page
limit Number No query.limit
axios({
  method: "GET",
  url: `/chessGameListView/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 /chessGameListView/filters

Route Type: create

Parameters

Parameter Type Required Population
filters Object Yes body
axios({
  method: "POST",
  url: `/chessGameListView/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 /chessGameListView/filters/:filterId

Route Type: delete

Parameters

Parameter Type Required Population
filterId ID Yes path.param
axios({
  method: "DELETE",
  url: `/chessGameListView/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 /chessGameListView/:id

Parameters

Parameter Type Required Population
id ID Yes path.param
axios({
  method: "GET",
  url: `/chessGameListView/${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 /leaderboardTopView/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: `/leaderboardTopView/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 /leaderboardTopView/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: `/leaderboardTopView/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 /leaderboardTopView/count

Parameters

Parameter Type Required Population
q String No query.q
filters Object Yes body
axios({
  method: "POST",
  url: `/leaderboardTopView/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 /leaderboardTopView/count

Parameters

Parameter Type Required Population
q String No query.q
axios({
  method: "GET",
  url: `/leaderboardTopView/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 /leaderboardTopView/schema

axios({
  method: "GET",
  url: `/leaderboardTopView/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 /leaderboardTopView/filters

Route Type: get

Parameters

Parameter Type Required Population
page Number No query.page
limit Number No query.limit
axios({
  method: "GET",
  url: `/leaderboardTopView/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 /leaderboardTopView/filters

Route Type: create

Parameters

Parameter Type Required Population
filters Object Yes body
axios({
  method: "POST",
  url: `/leaderboardTopView/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 /leaderboardTopView/filters/:filterId

Route Type: delete

Parameters

Parameter Type Required Population
filterId ID Yes path.param
axios({
  method: "DELETE",
  url: `/leaderboardTopView/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 /leaderboardTopView/:id

Parameters

Parameter Type Required Population
id ID Yes path.param
axios({
  method: "GET",
  url: `/leaderboardTopView/${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: chessgame-created

Event Topic: elastic-index-wechess_chessgame-created

When a chessgame is created in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the chessGameListViewAggregateData function to enrich and store the final document in the related index.

Expected Payload:

{
  "id": "String"
}

Kafka Event Listener: chessgame-updated

Event Topic: elastic-index-wechess_chessgame-updated

When a chessgame is updated in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the chessGameListViewAggregateData function to update the enriched document in the related index.

Expected Payload:

{
  "id": "String"
}

Kafka Event Listener: chessgame-deleted

Event Topic: elastic-index-wechess>_chessgame-deleted

When a chessgame is deleted in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the chessGameListViewAggregateData 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 playerWhiteReChessGameListView function to update dependent documents in the related index.

Expected Payload:

{
  "id": "String"
}

Kafka Event Listener: user-updated

Event Topic: elastic-index-wechess>_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 playerWhiteReChessGameListView function to re-enrich dependent data in the related index.

Expected Payload:

{
  "id": "String"
}

Kafka Event Listener: user-deleted

Event Topic: elastic-index-wechess>_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 playerWhiteReChessGameListView function to handle dependent data cleanup or updates.

Expected Payload:

{
  "id": "String"
}

Kafka Event Listener: user-created

Event Topic: elastic-index-user-created

When a user is created in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the playerBlackReChessGameListView function to update dependent documents in the related index.

Expected Payload:

{
  "id": "String"
}

Kafka Event Listener: user-updated

Event Topic: elastic-index-wechess>_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 playerBlackReChessGameListView function to re-enrich dependent data in the related index.

Expected Payload:

{
  "id": "String"
}

Kafka Event Listener: user-deleted

Event Topic: elastic-index-wechess>_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 playerBlackReChessGameListView function to handle dependent data cleanup or updates.

Expected Payload:

{
  "id": "String"
}

Kafka Event Listener: leaderboardentry-created

Event Topic: elastic-index-wechess_leaderboardentry-created

When a leaderboardentry is created in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the leaderboardTopViewAggregateData function to enrich and store the final document in the related index.

Expected Payload:

{
  "id": "String"
}

Kafka Event Listener: leaderboardentry-updated

Event Topic: elastic-index-wechess_leaderboardentry-updated

When a leaderboardentry is updated in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the leaderboardTopViewAggregateData function to update the enriched document in the related index.

Expected Payload:

{
  "id": "String"
}

Kafka Event Listener: leaderboardentry-deleted

Event Topic: elastic-index-wechess>_leaderboardentry-deleted

When a leaderboardentry is deleted in the ElasticSearch index, this listener is triggered. It parses the event payload, extracts the entity ID, and invokes the leaderboardTopViewAggregateData 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 userReLeaderboardTopView function to update dependent documents in the related index.

Expected Payload:

{
  "id": "String"
}

Kafka Event Listener: user-updated

Event Topic: elastic-index-wechess>_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 userReLeaderboardTopView function to re-enrich dependent data in the related index.

Expected Payload:

{
  "id": "String"
}

Kafka Event Listener: user-deleted

Event Topic: elastic-index-wechess>_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 userReLeaderboardTopView 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.7


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.7

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: wechess-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 wechess-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: wechess-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 wechess-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: wechess-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 wechess-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: wechess-notification-service-notification-email

When a notification is sent through the Email channel, this listener is triggered. It consumes messages from the wechess-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: wechess-notification-service-notification-push

When a notification is sent through the Push channel, this listener is triggered. It consumes messages from the wechess-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: wechess-notification-service-notification-sms

When a notification is sent through the SMS channel, this listener is triggered. It consumes messages from the wechess-notification-service-notification-sms topic, parses the payload, and uses the dynamically configured SMS provider to send the notification.

Kafka Event Listener: runprivateGameInvitationReceivedListener

Event Topic: wechess-gameplay-service-dbevent-chessgameinvitation-created

When a notification is sent through the wechess-gameplay-service-dbevent-chessgameinvitation-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 (invitationNotificationView).

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: runprivateGameInvitationResponseListener

Event Topic: wechess-gameplay-service-dbevent-chessgameinvitation-updated

When a notification is sent through the wechess-gameplay-service-dbevent-chessgameinvitation-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 (invitationNotificationView).

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: rungameMoveReminderListener

Event Topic: wechess-gameplay-service-chessgame-moveTimeoutReminder

When a notification is sent through the wechess-gameplay-service-chessgame-moveTimeoutReminder 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 (chessGameDetailView).

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: rungameResumeAvailableListener

Event Topic: wechess-gameplay-service-dbevent-chessgame-updated

When a notification is sent through the wechess-gameplay-service-dbevent-chessgame-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 (chessGameDetailView).

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: runchatMessageModeratedLobbyListener

Event Topic: wechess-lobbychat-service-dbevent-lobbymessage-updated

When a notification is sent through the wechess-lobbychat-service-dbevent-lobbymessage-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 (chatModerationNotificationView).

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: runchatMessageReportedLobbyListener

Event Topic: wechess-lobbychat-service-dbevent-lobbymessage-updated

When a notification is sent through the wechess-lobbychat-service-dbevent-lobbymessage-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 (chatModerationNotificationView).

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: rungameTerminatedByAdminListener

Event Topic: wechess-gameplay-service-dbevent-chessgame-updated

When a notification is sent through the wechess-gameplay-service-dbevent-chessgame-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 (gameTerminatedNotificationView).

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: wechess-user-service-email-verification-start

When a notification is sent through the wechess-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: wechess-user-service-mobile-verification-start

When a notification is sent through the wechess-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: wechess-user-service-password-reset-by-email-start

When a notification is sent through the wechess-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: wechess-user-service-password-reset-by-mobile-start

When a notification is sent through the wechess-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: wechess-user-service-email-2FA-start

When a notification is sent through the wechess-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: wechess-user-service-mobile-2FA-start

When a notification is sent through the wechess-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