Service Design Specification

wechess-gameplay-service documentation Version: 1.0.74

Scope

This document provides a structured architectural overview of the gameplay microservice, detailing its configuration, data model, authorization logic, business rules, and API design. It has been automatically generated based on the service definition within Mindbricks, ensuring that the information reflects the source of truth used during code generation and deployment.

The document is intended to serve multiple audiences:

Note for Frontend Developers: While this document is valuable for understanding business logic and data interactions, please refer to the Service API Documentation for endpoint-level specifications and integration details.

Note for Backend Developers: Since the code for this service is automatically generated by Mindbricks, you typically won’t need to implement or modify it manually. However, this document is especially valuable when you’re building other services—whether within Mindbricks or externally—that need to interact with or depend on this service. It provides a clear reference to the service’s data contracts, business rules, and API structure, helping ensure compatibility and correct integration.

Gameplay Service Settings

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

Service Overview

This service is configured to listen for HTTP requests on port 3000, serving both the main API interface and default administrative endpoints.

The following routes are available by default:

The service uses a PostgreSQL database for data storage, with the database name set to wechess-gameplay-service.

This service is accessible via the following environment-specific URLs:

Authentication & Security

This service requires user authentication for access. It supports both JWT and RSA-based authentication mechanisms, ensuring secure user sessions and data integrity. If a crud route also is configured to require login, it will check a valid JWT token in the request query/header/bearer/cookie. If the token is valid, it will extract the user information from the token and make the fetched session data available in the request context.

Service Data Objects

The service uses a PostgreSQL database for data storage, with the database name set to wechess-gameplay-service.

Data deletion is managed using a soft delete strategy. Instead of removing records from the database, they are flagged as inactive by setting the isActive field to false.

Object Name Description Public Access
chessGame No description accessPrivate
chessGameMove Represents a single move in a chess game (FIDE-compliant SAN/LAN representation, timestamp, player, time, move number). accessPrivate
chessGameInvitation An invitation for a private chess game between two players; status tracked; expires at set time or when accepted/declined. accessPrivate
customBoard No description accessPrivate
boardTheme No description accessPrivate
userPreference No description accessPrivate
gameHubMessage Auto-generated message DataObject for the gameHub RealtimeHub. Stores all messages with typed content payloads. accessPrivate
gameHubModeration Auto-generated moderation DataObject for the gameHub RealtimeHub. Stores block and silence actions for room-level user moderation. accessPrivate

chessGame Data Object

Object Overview

Description: No description provided.

This object represents a core data structure within the service and acts as the blueprint for database interaction, API generation, and business logic enforcement. It is defined using the ObjectSettings pattern, which governs its behavior, access control, caching strategy, and integration points with other systems such as Stripe and Redis.

Core Configuration

Properties Schema

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

Default Values

Default values are automatically assigned to properties when a new object is created, if no value is provided in the request body. Since default values are applied on db level, they should be literal values, not expressions.If you want to use expressions, you can use transposed parameters in any business API to set default values dynamically.

Constant Properties

playerWhiteId createdById mode invitationCode gameType initialFEN

Constant properties are defined to be immutable after creation, meaning they cannot be updated or changed once set. They are typically used for properties that should remain constant throughout the object’s lifecycle. A property is set to be constant if the Allow Update option is set to false.

Auto Update Properties

playerWhiteId playerBlackId createdById status mode invitationCode currentFEN gameType saveStatus saveRequestWhite saveRequestBlack movedAt result terminatedById reportStatus guestPlayerWhite guestPlayerBlack initialFEN

An update crud API created with the option Auto Params enabled will automatically update these properties with the provided values in the request body. If you want to update any property in your own business logic not by user input, you can set the Allow Auto Update option to false. These properties will be added to the update API’s body parameters and can be updated by the user if any value is provided in the request body.

Enum Properties

Enum properties are defined with a set of allowed values, ensuring that only valid options can be assigned to them. The enum options value will be stored as strings in the database, but when a data object is created an addtional property with the same name plus an idx suffix will be created, which will hold the index of the selected enum option. You can use the index property to sort by the enum value or when your enum options represent a sequence of values.

Elastic Search Indexing

playerWhiteId playerBlackId createdById status mode invitationCode currentFEN gameType saveStatus saveRequestWhite saveRequestBlack movedAt result terminatedById reportStatus guestPlayerWhite guestPlayerBlack initialFEN

Properties that are indexed in Elastic Search will be searchable via the Elastic Search API. While all properties are stored in the elastic search index of the data object, only those marked for Elastic Search indexing will be available for search queries.

Database Indexing

playerWhiteId playerBlackId createdById status mode invitationCode movedAt result

Properties that are indexed in the database will be optimized for query performance, allowing for faster data retrieval. Make a property indexed in the database if you want to use it frequently in query filters or sorting.

Secondary Key Properties

mode invitationCode

Secondary key properties are used to create an additional indexed identifiers for the data object, allowing for alternative access patterns. Different than normal indexed properties, secondary keys will act as primary keys and Mindbricks will provide automatic secondary key db utility functions to access the data object by the secondary key.

Relation Properties

playerWhiteId playerBlackId createdById terminatedById

Mindbricks supports relations between data objects, allowing you to define how objects are linked together. You can define relations in the data object properties, which will be used to create foreign key constraints in the database. For complex joins operations, Mindbricks supportsa BFF pattern, where you can view dynamic and static views based on Elastic Search Indexes. Use db level relations for simple one-to-one or one-to-many relationships, and use BFF views for complex joins that require multiple data objects to be joined together.

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

On Delete: Set Null Required: No

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

On Delete: Set Null Required: No

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

On Delete: Set Null Required: No

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

On Delete: Set Null Required: No

Filter Properties

status invitationCode

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

chessGameMove Data Object

Object Overview

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

This object represents a core data structure within the service and acts as the blueprint for database interaction, API generation, and business logic enforcement. It is defined using the ObjectSettings pattern, which governs its behavior, access control, caching strategy, and integration points with other systems such as Stripe and Redis.

Core Configuration

Composite Indexes

The index also defines a conflict resolution strategy for duplicate key violations.

When a new record would violate this composite index, the following action will be taken:

On Duplicate: throwError

An error will be thrown, preventing the insertion of conflicting data.

Properties Schema

Display Label Property: moveNotation — This property is the default display label for records of this data object. Relation dropdowns and record references in the frontend will show the value of this property as the human-readable label.

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

Default Values

Default values are automatically assigned to properties when a new object is created, if no value is provided in the request body. Since default values are applied on db level, they should be literal values, not expressions.If you want to use expressions, you can use transposed parameters in any business API to set default values dynamically.

Constant Properties

gameId moveNumber moveNotation moveTime movedById moveTimestamp

Constant properties are defined to be immutable after creation, meaning they cannot be updated or changed once set. They are typically used for properties that should remain constant throughout the object’s lifecycle. A property is set to be constant if the Allow Update option is set to false.

Auto Update Properties

gameId moveNumber moveNotation moveTime movedById moveTimestamp

An update crud API created with the option Auto Params enabled will automatically update these properties with the provided values in the request body. If you want to update any property in your own business logic not by user input, you can set the Allow Auto Update option to false. These properties will be added to the update API’s body parameters and can be updated by the user if any value is provided in the request body.

Elastic Search Indexing

gameId moveNumber moveNotation movedById moveTimestamp

Properties that are indexed in Elastic Search will be searchable via the Elastic Search API. While all properties are stored in the elastic search index of the data object, only those marked for Elastic Search indexing will be available for search queries.

Database Indexing

gameId moveNumber moveTimestamp

Properties that are indexed in the database will be optimized for query performance, allowing for faster data retrieval. Make a property indexed in the database if you want to use it frequently in query filters or sorting.

Secondary Key Properties

gameId moveNumber

Secondary key properties are used to create an additional indexed identifiers for the data object, allowing for alternative access patterns. Different than normal indexed properties, secondary keys will act as primary keys and Mindbricks will provide automatic secondary key db utility functions to access the data object by the secondary key.

Relation Properties

gameId movedById

Mindbricks supports relations between data objects, allowing you to define how objects are linked together. You can define relations in the data object properties, which will be used to create foreign key constraints in the database. For complex joins operations, Mindbricks supportsa BFF pattern, where you can view dynamic and static views based on Elastic Search Indexes. Use db level relations for simple one-to-one or one-to-many relationships, and use BFF views for complex joins that require multiple data objects to be joined together.

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

On Delete: Set Null Required: Yes

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

On Delete: Set Null Required: No

Filter Properties

gameId

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

chessGameInvitation Data Object

Object Overview

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

This object represents a core data structure within the service and acts as the blueprint for database interaction, API generation, and business logic enforcement. It is defined using the ObjectSettings pattern, which governs its behavior, access control, caching strategy, and integration points with other systems such as Stripe and Redis.

Core Configuration

Composite Indexes

The index also defines a conflict resolution strategy for duplicate key violations.

When a new record would violate this composite index, the following action will be taken:

On Duplicate: throwError

An error will be thrown, preventing the insertion of conflicting data.

Properties Schema

Property Type Required Description
gameId ID Yes Game this invitation is linked to.
senderId ID Yes -
recipientId ID Yes -
status Enum Yes -
expiresAt Date Yes Expiration date/time for the invitation.

Default Values

Default values are automatically assigned to properties when a new object is created, if no value is provided in the request body. Since default values are applied on db level, they should be literal values, not expressions.If you want to use expressions, you can use transposed parameters in any business API to set default values dynamically.

Constant Properties

gameId

Constant properties are defined to be immutable after creation, meaning they cannot be updated or changed once set. They are typically used for properties that should remain constant throughout the object’s lifecycle. A property is set to be constant if the Allow Update option is set to false.

Auto Update Properties

gameId senderId recipientId status expiresAt

An update crud API created with the option Auto Params enabled will automatically update these properties with the provided values in the request body. If you want to update any property in your own business logic not by user input, you can set the Allow Auto Update option to false. These properties will be added to the update API’s body parameters and can be updated by the user if any value is provided in the request body.

Enum Properties

Enum properties are defined with a set of allowed values, ensuring that only valid options can be assigned to them. The enum options value will be stored as strings in the database, but when a data object is created an addtional property with the same name plus an idx suffix will be created, which will hold the index of the selected enum option. You can use the index property to sort by the enum value or when your enum options represent a sequence of values.

Elastic Search Indexing

gameId senderId recipientId status expiresAt

Properties that are indexed in Elastic Search will be searchable via the Elastic Search API. While all properties are stored in the elastic search index of the data object, only those marked for Elastic Search indexing will be available for search queries.

Database Indexing

gameId senderId recipientId expiresAt

Properties that are indexed in the database will be optimized for query performance, allowing for faster data retrieval. Make a property indexed in the database if you want to use it frequently in query filters or sorting.

Secondary Key Properties

gameId

Secondary key properties are used to create an additional indexed identifiers for the data object, allowing for alternative access patterns. Different than normal indexed properties, secondary keys will act as primary keys and Mindbricks will provide automatic secondary key db utility functions to access the data object by the secondary key.

Relation Properties

gameId senderId recipientId

Mindbricks supports relations between data objects, allowing you to define how objects are linked together. You can define relations in the data object properties, which will be used to create foreign key constraints in the database. For complex joins operations, Mindbricks supportsa BFF pattern, where you can view dynamic and static views based on Elastic Search Indexes. Use db level relations for simple one-to-one or one-to-many relationships, and use BFF views for complex joins that require multiple data objects to be joined together.

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

On Delete: Set Null Required: Yes

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

On Delete: Set Null Required: No

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

On Delete: Set Null Required: No

Filter Properties

senderId recipientId status

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

customBoard Data Object

Object Overview

Description: No description provided.

This object represents a core data structure within the service and acts as the blueprint for database interaction, API generation, and business logic enforcement. It is defined using the ObjectSettings pattern, which governs its behavior, access control, caching strategy, and integration points with other systems such as Stripe and Redis.

Core Configuration

Properties Schema

Display Label Property: name — This property is the default display label for records of this data object. Relation dropdowns and record references in the frontend will show the value of this property as the human-readable label.

Property Type Required Description
name String Yes Name of the custom board position
fen String Yes FEN string representing the board position
description Text No Optional description of the custom board
isPublished Boolean Yes -
category Enum Yes -
createdById ID Yes -

Default Values

Default values are automatically assigned to properties when a new object is created, if no value is provided in the request body. Since default values are applied on db level, they should be literal values, not expressions.If you want to use expressions, you can use transposed parameters in any business API to set default values dynamically.

Auto Update Properties

name fen description isPublished category createdById

An update crud API created with the option Auto Params enabled will automatically update these properties with the provided values in the request body. If you want to update any property in your own business logic not by user input, you can set the Allow Auto Update option to false. These properties will be added to the update API’s body parameters and can be updated by the user if any value is provided in the request body.

Enum Properties

Enum properties are defined with a set of allowed values, ensuring that only valid options can be assigned to them. The enum options value will be stored as strings in the database, but when a data object is created an addtional property with the same name plus an idx suffix will be created, which will hold the index of the selected enum option. You can use the index property to sort by the enum value or when your enum options represent a sequence of values.

Elastic Search Indexing

name fen description isPublished category createdById

Properties that are indexed in Elastic Search will be searchable via the Elastic Search API. While all properties are stored in the elastic search index of the data object, only those marked for Elastic Search indexing will be available for search queries.

Database Indexing

name isPublished category createdById

Properties that are indexed in the database will be optimized for query performance, allowing for faster data retrieval. Make a property indexed in the database if you want to use it frequently in query filters or sorting.

Relation Properties

createdById

Mindbricks supports relations between data objects, allowing you to define how objects are linked together. You can define relations in the data object properties, which will be used to create foreign key constraints in the database. For complex joins operations, Mindbricks supportsa BFF pattern, where you can view dynamic and static views based on Elastic Search Indexes. Use db level relations for simple one-to-one or one-to-many relationships, and use BFF views for complex joins that require multiple data objects to be joined together.

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

On Delete: Set Null Required: No

Filter Properties

isPublished category createdById

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

boardTheme Data Object

Object Overview

Description: No description provided.

This object represents a core data structure within the service and acts as the blueprint for database interaction, API generation, and business logic enforcement. It is defined using the ObjectSettings pattern, which governs its behavior, access control, caching strategy, and integration points with other systems such as Stripe and Redis.

Core Configuration

Properties Schema

Display Label Property: name — This property is the default display label for records of this data object. Relation dropdowns and record references in the frontend will show the value of this property as the human-readable label.

Property Type Required Description
name String Yes Theme display name
lightSquare String Yes Hex color for light squares
darkSquare String Yes Hex color for dark squares
isPublished Boolean No Whether the theme is publicly visible
createdById ID Yes User who created this theme

Default Values

Default values are automatically assigned to properties when a new object is created, if no value is provided in the request body. Since default values are applied on db level, they should be literal values, not expressions.If you want to use expressions, you can use transposed parameters in any business API to set default values dynamically.

Always Create with Default Values

Some of the default values are set to be always used when creating a new object, even if the property value is provided in the request body. It ensures that the property is always initialized with a default value when the object is created.

Constant Properties

createdById

Constant properties are defined to be immutable after creation, meaning they cannot be updated or changed once set. They are typically used for properties that should remain constant throughout the object’s lifecycle. A property is set to be constant if the Allow Update option is set to false.

Auto Update Properties

name lightSquare darkSquare isPublished createdById

An update crud API created with the option Auto Params enabled will automatically update these properties with the provided values in the request body. If you want to update any property in your own business logic not by user input, you can set the Allow Auto Update option to false. These properties will be added to the update API’s body parameters and can be updated by the user if any value is provided in the request body.

Elastic Search Indexing

name lightSquare darkSquare isPublished createdById

Properties that are indexed in Elastic Search will be searchable via the Elastic Search API. While all properties are stored in the elastic search index of the data object, only those marked for Elastic Search indexing will be available for search queries.

Database Indexing

name isPublished createdById

Properties that are indexed in the database will be optimized for query performance, allowing for faster data retrieval. Make a property indexed in the database if you want to use it frequently in query filters or sorting.

Relation Properties

createdById

Mindbricks supports relations between data objects, allowing you to define how objects are linked together. You can define relations in the data object properties, which will be used to create foreign key constraints in the database. For complex joins operations, Mindbricks supportsa BFF pattern, where you can view dynamic and static views based on Elastic Search Indexes. Use db level relations for simple one-to-one or one-to-many relationships, and use BFF views for complex joins that require multiple data objects to be joined together.

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

On Delete: Set Null Required: No

Filter Properties

isPublished

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

userPreference Data Object

Object Overview

Description: No description provided.

This object represents a core data structure within the service and acts as the blueprint for database interaction, API generation, and business logic enforcement. It is defined using the ObjectSettings pattern, which governs its behavior, access control, caching strategy, and integration points with other systems such as Stripe and Redis.

Core Configuration

Properties Schema

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

Default Values

Default values are automatically assigned to properties when a new object is created, if no value is provided in the request body. Since default values are applied on db level, they should be literal values, not expressions.If you want to use expressions, you can use transposed parameters in any business API to set default values dynamically.

Constant Properties

userId

Constant properties are defined to be immutable after creation, meaning they cannot be updated or changed once set. They are typically used for properties that should remain constant throughout the object’s lifecycle. A property is set to be constant if the Allow Update option is set to false.

Auto Update Properties

userId activeThemeId soundEnabled showAnimations boardOrientation premoveEnabled

An update crud API created with the option Auto Params enabled will automatically update these properties with the provided values in the request body. If you want to update any property in your own business logic not by user input, you can set the Allow Auto Update option to false. These properties will be added to the update API’s body parameters and can be updated by the user if any value is provided in the request body.

Enum Properties

Enum properties are defined with a set of allowed values, ensuring that only valid options can be assigned to them. The enum options value will be stored as strings in the database, but when a data object is created an addtional property with the same name plus an idx suffix will be created, which will hold the index of the selected enum option. You can use the index property to sort by the enum value or when your enum options represent a sequence of values.

Elastic Search Indexing

userId activeThemeId soundEnabled showAnimations boardOrientation premoveEnabled

Properties that are indexed in Elastic Search will be searchable via the Elastic Search API. While all properties are stored in the elastic search index of the data object, only those marked for Elastic Search indexing will be available for search queries.

Database Indexing

userId

Properties that are indexed in the database will be optimized for query performance, allowing for faster data retrieval. Make a property indexed in the database if you want to use it frequently in query filters or sorting.

Unique Properties

userId

Unique properties are enforced to have distinct values across all instances of the data object, preventing duplicate entries. Note that a unique property is automatically indexed in the database so you will not need to set the Indexed in DB option.

Relation Properties

userId

Mindbricks supports relations between data objects, allowing you to define how objects are linked together. You can define relations in the data object properties, which will be used to create foreign key constraints in the database. For complex joins operations, Mindbricks supportsa BFF pattern, where you can view dynamic and static views based on Elastic Search Indexes. Use db level relations for simple one-to-one or one-to-many relationships, and use BFF views for complex joins that require multiple data objects to be joined together.

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

On Delete: Set Null Required: No

gameHubMessage Data Object

Object Overview

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

This object represents a core data structure within the service and acts as the blueprint for database interaction, API generation, and business logic enforcement. It is defined using the ObjectSettings pattern, which governs its behavior, access control, caching strategy, and integration points with other systems such as Stripe and Redis.

Core Configuration

Properties Schema

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

Default Values

Default values are automatically assigned to properties when a new object is created, if no value is provided in the request body. Since default values are applied on db level, they should be literal values, not expressions.If you want to use expressions, you can use transposed parameters in any business API to set default values dynamically.

Constant Properties

roomId senderId senderName senderAvatar messageType timestamp

Constant properties are defined to be immutable after creation, meaning they cannot be updated or changed once set. They are typically used for properties that should remain constant throughout the object’s lifecycle. A property is set to be constant if the Allow Update option is set to false.

Auto Update Properties

roomId senderId senderName senderAvatar messageType content timestamp status

An update crud API created with the option Auto Params enabled will automatically update these properties with the provided values in the request body. If you want to update any property in your own business logic not by user input, you can set the Allow Auto Update option to false. These properties will be added to the update API’s body parameters and can be updated by the user if any value is provided in the request body.

Enum Properties

Enum properties are defined with a set of allowed values, ensuring that only valid options can be assigned to them. The enum options value will be stored as strings in the database, but when a data object is created an addtional property with the same name plus an idx suffix will be created, which will hold the index of the selected enum option. You can use the index property to sort by the enum value or when your enum options represent a sequence of values.

Elastic Search Indexing

roomId senderId senderName senderAvatar messageType content timestamp status

Properties that are indexed in Elastic Search will be searchable via the Elastic Search API. While all properties are stored in the elastic search index of the data object, only those marked for Elastic Search indexing will be available for search queries.

Database Indexing

roomId senderId senderName senderAvatar messageType content timestamp status

Properties that are indexed in the database will be optimized for query performance, allowing for faster data retrieval. Make a property indexed in the database if you want to use it frequently in query filters or sorting.

Secondary Key Properties

roomId

Secondary key properties are used to create an additional indexed identifiers for the data object, allowing for alternative access patterns. Different than normal indexed properties, secondary keys will act as primary keys and Mindbricks will provide automatic secondary key db utility functions to access the data object by the secondary key.

Session Data Properties

senderId

Session data properties are used to store data that is specific to the user session, allowing for personalized experiences and temporary data storage. If a property is configured as session data, it will be automatically mapped to the related field in the user session during CRUD operations. Note that session data properties can not be mutated by the user, but only by the system.

Filter Properties

roomId senderId senderName senderAvatar messageType content timestamp status

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

gameHubModeration Data Object

Object Overview

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

This object represents a core data structure within the service and acts as the blueprint for database interaction, API generation, and business logic enforcement. It is defined using the ObjectSettings pattern, which governs its behavior, access control, caching strategy, and integration points with other systems such as Stripe and Redis.

Core Configuration

Properties Schema

Property Type Required Description
roomId ID Yes Reference to the room where the moderation action applies
userId ID Yes The user who is blocked or silenced
action Enum Yes Moderation action type
reason Text No Optional reason for the moderation action
duration Integer No Duration in seconds. 0 means permanent
expiresAt No Expiry timestamp. Null means permanent
issuedBy ID No The moderator who issued the action

Default Values

Default values are automatically assigned to properties when a new object is created, if no value is provided in the request body. Since default values are applied on db level, they should be literal values, not expressions.If you want to use expressions, you can use transposed parameters in any business API to set default values dynamically.

Constant Properties

roomId userId action duration expiresAt issuedBy

Constant properties are defined to be immutable after creation, meaning they cannot be updated or changed once set. They are typically used for properties that should remain constant throughout the object’s lifecycle. A property is set to be constant if the Allow Update option is set to false.

Auto Update Properties

roomId userId action reason duration expiresAt issuedBy

An update crud API created with the option Auto Params enabled will automatically update these properties with the provided values in the request body. If you want to update any property in your own business logic not by user input, you can set the Allow Auto Update option to false. These properties will be added to the update API’s body parameters and can be updated by the user if any value is provided in the request body.

Enum Properties

Enum properties are defined with a set of allowed values, ensuring that only valid options can be assigned to them. The enum options value will be stored as strings in the database, but when a data object is created an addtional property with the same name plus an idx suffix will be created, which will hold the index of the selected enum option. You can use the index property to sort by the enum value or when your enum options represent a sequence of values.

Elastic Search Indexing

roomId userId action reason duration expiresAt issuedBy

Properties that are indexed in Elastic Search will be searchable via the Elastic Search API. While all properties are stored in the elastic search index of the data object, only those marked for Elastic Search indexing will be available for search queries.

Database Indexing

roomId userId action reason duration expiresAt issuedBy

Properties that are indexed in the database will be optimized for query performance, allowing for faster data retrieval. Make a property indexed in the database if you want to use it frequently in query filters or sorting.

Secondary Key Properties

roomId userId

Secondary key properties are used to create an additional indexed identifiers for the data object, allowing for alternative access patterns. Different than normal indexed properties, secondary keys will act as primary keys and Mindbricks will provide automatic secondary key db utility functions to access the data object by the secondary key.

Relation Properties

roomId

Mindbricks supports relations between data objects, allowing you to define how objects are linked together. You can define relations in the data object properties, which will be used to create foreign key constraints in the database. For complex joins operations, Mindbricks supportsa BFF pattern, where you can view dynamic and static views based on Elastic Search Indexes. Use db level relations for simple one-to-one or one-to-many relationships, and use BFF views for complex joins that require multiple data objects to be joined together.

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

On Delete: Set Null Required: Yes

Session Data Properties

issuedBy

Session data properties are used to store data that is specific to the user session, allowing for personalized experiences and temporary data storage. If a property is configured as session data, it will be automatically mapped to the related field in the user session during CRUD operations. Note that session data properties can not be mutated by the user, but only by the system.

Filter Properties

roomId userId action reason duration expiresAt issuedBy

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

Business Logic

gameplay has got 28 Business APIs to manage its internal and crud logic. For the details of each business API refer to its chapter.

Realtime Hubs

gameplay has 1 Realtime Hub configured. Each hub provides bidirectional communication powered by Socket.IO with room-based messaging, built-in and custom message types, and auto-generated REST endpoints.

Hub Name Namespace Room DataObject Roles
gameHub /hub/gameHub chessGame player

For detailed documentation on each hub, refer to:

Service Library

Functions

processGameResult.js

const { interserviceCall } = require("serviceCommon");

/**
 * Mindbricks interservice calls return the same envelope as REST (e.g. { playerStats: {...} }).
 * Unwrap so we read id, eloRating, wins, etc. from the actual row.
 */
function unwrapPlayerStats(res) {
  if (res == null || typeof res !== "object") return null;
  const inner = res.playerStats;
  if (inner && typeof inner === "object" && inner.id) return inner;
  if (res.id && res.userId) return res;
  return null;
}

/**
 * Processes a completed/terminated chess game result:
 * - Computes ELO changes for both players
 * - Calls leaderboard service to update playerStats for registered (non-guest) players
 * - Calls leaderboard service to update leaderboardEntry eloRating and rank
 *
 * @param {object} context - The API context (this)
 */
module.exports = async function processGameResult(context) {
  const game = context.chessGame;
  const updatedFields = context;

  const status = updatedFields.status || game.status;
  const result = updatedFields.result || game.result;

  if (!["completed", "terminated"].includes(status) || !result) {
    return null;
  }

  if (result === "aborted") {
    return null;
  }

  const playerWhiteId = game.playerWhiteId;
  const playerBlackId = game.playerBlackId;
  const isWhiteGuest = game.guestPlayerWhite === true;
  const isBlackGuest = game.guestPlayerBlack === true;

  let whiteOutcome;
  let blackOutcome;
  if (result === "whiteWin") {
    whiteOutcome = "win";
    blackOutcome = "loss";
  } else if (result === "blackWin") {
    whiteOutcome = "loss";
    blackOutcome = "win";
  } else if (result === "draw") {
    whiteOutcome = "draw";
    blackOutcome = "draw";
  } else {
    return null;
  }

  let whiteStats = null;
  let blackStats = null;

  if (!isWhiteGuest && playerWhiteId) {
    try {
      const raw = await interserviceCall("leaderboard", "getPlayerStats", { userId: playerWhiteId });
      whiteStats = unwrapPlayerStats(raw);
    } catch (e) {
      /* player may not have stats yet */
    }
  }
  if (!isBlackGuest && playerBlackId) {
    try {
      const raw = await interserviceCall("leaderboard", "getPlayerStats", { userId: playerBlackId });
      blackStats = unwrapPlayerStats(raw);
    } catch (e) {
      /* player may not have stats yet */
    }
  }

  const whiteElo = whiteStats ? (Number(whiteStats.eloRating) || 1200) : 1200;
  const blackElo = blackStats ? (Number(blackStats.eloRating) || 1200) : 1200;

  const K = 32;
  const expectedWhite = 1 / (1 + Math.pow(10, (blackElo - whiteElo) / 400));
  const expectedBlack = 1 / (1 + Math.pow(10, (whiteElo - blackElo) / 400));

  let actualWhite;
  let actualBlack;
  if (result === "whiteWin") {
    actualWhite = 1;
    actualBlack = 0;
  } else if (result === "blackWin") {
    actualWhite = 0;
    actualBlack = 1;
  } else {
    actualWhite = 0.5;
    actualBlack = 0.5;
  }

  const newWhiteElo = Math.round(whiteElo + K * (actualWhite - expectedWhite));
  const newBlackElo = Math.round(blackElo + K * (actualBlack - expectedBlack));

  const now = new Date().toISOString();

  function buildUpdatePayload(stats, outcome, newElo) {
    const wins = (stats ? stats.wins : 0) + (outcome === "win" ? 1 : 0);
    const losses = (stats ? stats.losses : 0) + (outcome === "loss" ? 1 : 0);
    const draws = (stats ? stats.draws : 0) + (outcome === "draw" ? 1 : 0);
    const totalGames = wins + losses + draws;
    let streak = stats ? stats.streak : 0;
    if (outcome === "win") streak = streak > 0 ? streak + 1 : 1;
    else if (outcome === "loss") streak = streak < 0 ? streak - 1 : -1;
    else streak = 0;
    return { eloRating: newElo, totalGames, wins, losses, draws, streak, lastGameAt: now };
  }

  if (!isWhiteGuest && playerWhiteId && whiteStats) {
    try {
      const payload = buildUpdatePayload(whiteStats, whiteOutcome, newWhiteElo);
      await interserviceCall("leaderboard", "updatePlayerStats", { id: whiteStats.id, ...payload });
    } catch (e) {
      console.error("Failed to update white player stats:", e.message);
    }
  }

  if (!isBlackGuest && playerBlackId && blackStats) {
    try {
      const payload = buildUpdatePayload(blackStats, blackOutcome, newBlackElo);
      await interserviceCall("leaderboard", "updatePlayerStats", { id: blackStats.id, ...payload });
    } catch (e) {
      console.error("Failed to update black player stats:", e.message);
    }
  }

  return { whiteElo: newWhiteElo, blackElo: newBlackElo, result };
};

This document was generated from the service architecture definition and should be kept in sync with implementation changes.