weChess Multiplayer Chess Platform - Frontend Development Prompts

AI-assisted frontend development prompts for weChess Multiplayer Chess Platform

This document contains all frontend development prompts that can be used to build the user interface for this project. Each prompt provides detailed specifications for implementing specific frontend features.


Table of Contents


Introduction

Project Overview

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.


How to Use These Prompts

These prompts are designed to be used with AI coding assistants to help build frontend features. Each prompt includes:

  1. Feature Description - What the feature does and its purpose
  2. Data Models - The backend data structures to work with
  3. API Endpoints - Available REST APIs for the feature
  4. UI Requirements - Specific user interface requirements
  5. Implementation Guidelines - Best practices and patterns to follow

When using these prompts with an AI assistant:


Frontend Development Prompts

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.

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.


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.


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.


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.


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.


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.


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.


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.


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.


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.


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.



Related Documentation

For more detailed information, refer to:


Generated by Mindbricks Genesis Engine