Members
# ASSISTANT_GREETING_MESSAGE
Assistant greeting message to the user
# constant AUTOGEN_RANDOM_BYTES
Number of random bytes used to generate a unique subLink suffix.
# constant AssistantSchema
Embedded schema representing assistant responses in the chat history.
# CORS_ALLOWED_DOMAIN
CORS allowed domain (e.g., ".aaic.dev" to allow all subdomains)
# constant CURRICULUM_SORT_EXPR
MongoDB expression for curriculum sorting (empty → "zzz" to sort last)
# constant Chat
Chat model used to persist conversation history.
# constant ChatHistorySchema
Chat history entry schema combining user and assistant messages.
# constant ChatSchema
Root schema representing a chat session and associated investigation reference.
# constant DEFAULT_CURRICULUM
Default values and constants for investigation utilities
# constant DEFAULT_HISTORY_LIMIT
Default number of history entries to return
# constant EditableFieldSchema
General EditableField Schema - Base schema for all editable fields This schema provides the common structure for AI-generated and human-editable content
# constant EditableVector3Schema
Vector3 Schema - 3D vector with x, y, z coordinates
# constant FIELD_HISTORY_LIMIT_MIN
Pagination limit constants for field history endpoint
# constant FieldHistoryEntrySchema
Field History Entry Schema - Schema for a single history entry
# constant GCS_PATHS
Google Cloud Storage path constants Centralized path definitions for GCS storage organization
# constant GRADE_MIN
Grade range constants Defines the minimum and maximum grade values allowed in the system
# constant GRADE_SORT_EMPTY
Sort value for empty/missing grades
# constant GRADE_SORT_FIELD
MongoDB expression for grade sorting. Converts grade to numeric: K=0, 1-12=1-12, P=13, B=14, C=15, other=99, empty=999
# constant GRADE_SORT_UNKNOWN
Sort value for unknown/unrecognized grades
# constant GRADE_SORT_VALUES
Grade sort values for non-numeric grades. Numeric grades (1-12) use their own values. Order: K=0, [1-12], P=13, B=14, C=15, unknown=99, empty=999
# constant INVESTIGATIONS_FETCH_ALL_LIMIT
Hard cap for fetchAll requests to prevent memory/performance issues
# constant INVESTIGATIONS_LIST_LIMIT_MIN
Pagination limit constants for investigations list endpoint
# INVESTIGATION_INACTIVITY_TIMEOUT_MS
Investigation inactivity timeout in milliseconds
# constant INVESTIGATION_VERSIONS_LIMIT_MIN
Pagination limit constants for investigation versions endpoint
# constant Investigation
Investigation Model This is the main model file that assembles all components
string
# InvestigationGroupType
Investigation List Group Type Enum Defines sub-grouping options within sections
# constant InvestigationMetadataSchema
Investigation Metadata Schema - Metadata for an investigation
# constant InvestigationSchema
Investigation Schema Definition This file contains the main mongoose schema definition for investigations
string
# InvestigationSectionType
Investigation List Section Type Enum Defines how investigations are grouped in the main list view
string
# InvestigationSortBy
Investigation Sort By Field Enum Defines which field to sort investigations by
# constant LESSON_SORT_FIELDS
MongoDB expressions for lesson-based group sorting (extends unit sorting)
# LinkKey
Link key - logical destination / page type for the URL
# constant MAX_UNIQUE_RETRIES
Max attempts to find a unique subLink before falling back to timestamp-based slug.
# constant Metadata
Metadata model exposing catalog metadata persistence APIs.
# constant MetadataSchema
Metadata schema describing investigation catalog entries.
string
# ModifyInvestigationIntents
AI Assistant's Modify InvestigationIntents Enum - For Assistant investigation modification
# constant ObjectIdParamSchema
Zod validation schemas for URL/link endpoints
# constant ObjectSchema
Object Schema - 3D object with position, rotation, size, view and components
# PHYSICS_ENGINE_AMQP_PASSWORD
Physics service RabbitMQ password
# PHYSICS_ENGINE_COMMAND_QUEUE
RabbitMQ queue name for physics commands (request). Chrono must consume with prefetch(1) so only one command is processed at a time (waiting = queued, running = unacked).
# PHYSICS_ENGINE_HEARTBEAT
RabbitMQ connection heartbeat in seconds. Keeps connection alive over unstable networks.
# PHYSICS_ENGINE_REPLY_QUEUE
RabbitMQ queue name for physics command replies (RPC). Per-connection queues use this as prefix + connectionId.
# PHYSICS_ENGINE_STATE_EXCHANGE
RabbitMQ topic exchange name for physics state broadcasts
# PHYSICS_ENGINE_STATE_QUEUE
RabbitMQ queue name prefix for state broadcasts. Per-connection queue name is {prefix}_{connectionId}.
# PHYSICS_GATEWAY_CLEANUP_DELAY_MS
Delay in ms before closing physics gateway (replies/state queues) after socket disconnect. Use 60000 (60s) or 300000 (300s) for stable reconnects on poor user internet.
# PHYSICS_GATEWAY_RECONNECT_ATTEMPTS
Max reconnection attempts for physics gateway (connection/channel drops).
# PHYSICS_GATEWAY_RECONNECT_DELAY_MS
Base delay in ms between reconnection attempts. Backoff may increase on repeated failures.
# constant Prompt
Prompt model providing access to reusable LLM prompt templates.
# constant SORT_FIELD_MAP
Map of sortBy enum values to MongoDB field paths
# constant STATUS_DISPLAY_MAP
Map of status codes to human-readable display names
# constant SUBJECT_ORDER
Subject sort order: Physics → Biology → Chemistry
# constant SUBJECT_SORT_FIELDS
MongoDB expressions for subject-based group sorting. Order: Physics (1) → Biology (2) → Chemistry (3) → other (50) → N/A (99)
# constant SUBLINK_MAX_LENGTH
Max length of an autogenerated subLink slug (from title).
# constant StepSchema
Step Schema - Individual step in an investigation Each field is now wrapped with EditableFieldSchema for AI/human editing capabilities
# constant UNIT_IDENTIFIER_EXPR
Helper expression to extract unit identifier: " Unit 8.1: Title " → "8.1"
# constant UNIT_SORT_FIELDS
MongoDB expressions for unit-based group sorting
# constant URL_LOOKUP_STAGES
MongoDB aggregation stages for looking up URL data and computing views/completions
# constant Url
URL model used to persist short links associated with investigations.
# constant UrlCountersSchema
URL Counters Schema - Mongoose schema for UrlCounters This is a subdocument schema with no _id
# constant UrlSchema
URL Schema Definition This file contains the main mongoose schema definition for URLs
string
# UserRole
User role enumeration - matches Auth Service definition Only admin and SME (Subject Matter Expert) roles are supported
# constant UserSchema
Embedded schema representing a user entry in the chat history.
# constant Vector3Schema
Vector3 validation schema
# WS_PORT
WebSocket server port (for Unity WebGL and other platforms)
# constant apiKeyLimiter
Rate limiter for API key-based requests More lenient for authenticated API access
# constant asyncHandler
Wraps an async function to catch any rejections and forward them to the next middleware. This allows you to use async/await in route handlers without manually wrapping them in try-catch blocks.
Example
```typescript
// Instead of:
app.get('/users', async (req, res, next) => {
try {
const users = await userService.getUsers();
res.json(users);
} catch (error) {
next(error);
}
});
// You can do:
app.get('/users', asyncHandler(async (req, res) => {
const users = await userService.getUsers();
res.json(users);
}));
```
# constant authLimiter
Strict rate limiter for authentication endpoints Used to prevent brute-force attacks on login/auth endpoints
# constant envSchema
Environment variables schema and validation.
# fetchAll
When true, fetches all matching investigations up to INVESTIGATIONS_FETCH_ALL_LIMIT. This is required for proper sectioning/grouping - without full data, sections would be incomplete and split across pages (e.g., "Grade 8" appearing on multiple pages with different items). When fetchAll is true, limit/offset are ignored.
# constant generalLimiter
General rate limiter for all API endpoints
# constant mockInvestigations
Pre-defined mock investigation items for common test scenarios
# constant mockPhysicsGatewayService
Mock the physics gateway service
# constant mongoOptions
MongoDB connection options used for the service-level connection pool.
# constant redisUtils
Convenience helpers for interacting with Redis commands.
# constant requireAuthenticated
Create middleware that requires authentication (admin or SME role)
# constant router
REST endpoints that manage investigations.
# constant router
Link routes (public resolve + protected investigation-scoped list/create).
- GET/POST /investigation/:id require auth.
- GET /:key/:subLink is public (resolve).
# constant subjectsFactory
Maps subject codes to their corresponding full names.
# constant swaggerOptions
Swagger configuration for API documentation
# constant uploadLimiter
Stricter rate limiter for file upload endpoints
Methods
# addContradictionInPlace(investigation, contradiction) → {Partial.<IInvestigation>}
Adds a contradiction to a specific field in an investigation.
Parameters:
| Name | Type | Description |
|---|---|---|
investigation |
Partial.<IInvestigation>
|
The investigation object to update. |
contradiction |
IContradictionInput
|
The details of the contradiction to add. |
- If the field is not found in the investigation.
Error
- The investigation object with the updated contradiction.
Partial.<IInvestigation>
# assertNotInDevelopment(investigation, message) → {void}
Throws when investigation is in development state.
Parameters:
| Name | Type | Description |
|---|---|---|
investigation |
IInvestigation
|
Investigation to validate. |
message |
string
|
Error message to throw. |
No return value.
void
# batchFetchUserProfiles(userIds, grpcClient) → {Promise.<Map.<string, IUserProfile>>}
Batch fetch multiple user profiles efficiently using a single gRPC call. Uses Redis mget for batch cache lookup, then fetches missing profiles via batch gRPC.
Parameters:
| Name | Type | Description |
|---|---|---|
userIds |
Array.<string>
|
Array of user IDs to fetch. |
grpcClient |
AuthGrpcService
|
The gRPC client used to fetch users. |
Map of userId to profile.
Promise.<Map.<string, IUserProfile>>
# buildGroupSortFields(group) → {Array.<SectionSortAddFieldsStage>}
Builds MongoDB $addFields stages for group sorting
Parameters:
| Name | Type | Description |
|---|---|---|
group |
GroupType
|
null
|
The group type to build sort fields for |
Array of MongoDB $addFields stages
Array.<SectionSortAddFieldsStage>
# buildInvestigationQuery(searchDto) → {Object}
Builds MongoDB query from search filters
Parameters:
| Name | Type | Description |
|---|---|---|
searchDto |
IInvestigationSearchDto
|
The search and filter parameters |
Query object and search metadata
Object
# buildInvestigationSnapshot(investigation) → {Record.<string, unknown>}
Builds a plain JSON snapshot of the investigation state for versioning.
Parameters:
| Name | Type | Description |
|---|---|---|
investigation |
IInvestigation
|
Investigation document to snapshot. |
Snapshot of the investigation without versioning metadata.
Record.<string, unknown>
# buildRelevanceScoreStage(escapedSearchTerm) → {object}
Builds MongoDB aggregation stage for relevance scoring with priorities Priority order: Title (highest) > Curriculum/Unit/Lesson/Grade > Objectives/Goals/AnalyticalFacts/NGSS > Day/Steps/Objects Exact matches score higher than partial matches
Parameters:
| Name | Type | Description |
|---|---|---|
escapedSearchTerm |
string
|
Escaped search term for regex matching |
MongoDB $addFields stage with relevanceScore calculation
object
# buildSectionSortFields(section, currentUserIdopt, sortedAuthorIdsopt) → {Array.<SectionSortAddFieldsStage>}
Builds MongoDB $addFields stages for section sorting
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
section |
SectionType
|
null
|
The section type to build sort fields for |
|
currentUserId |
string
|
<optional> |
Optional current user ID for author sorting |
sortedAuthorIds |
Array.<Types.ObjectId>
|
<optional> |
Optional pre-sorted author IDs |
Array of MongoDB $addFields stages
Array.<SectionSortAddFieldsStage>
# buildSortSpec(sortBy, sortOrder, hasSearch, section, hasSortedAuthorIds, group) → {Record.<string, number>}
Builds MongoDB sort specification with section/group-aware sorting
Parameters:
| Name | Type | Description |
|---|---|---|
sortBy |
InvestigationSortBy
|
undefined
|
The field to sort by |
sortOrder |
SortOrder
|
undefined
|
The sort order (ASC or DESC) |
hasSearch |
boolean
|
Whether a search term is present |
section |
SectionType
|
null
|
Optional section type for section-aware sorting |
hasSortedAuthorIds |
boolean
|
Whether pre-sorted author IDs are available |
group |
GroupType
|
null
|
Optional group type for group-aware sorting |
MongoDB sort specification object
Record.<string, number>
# checkAndUnlockStaleLocks() → {Promise.<number>}
Check and unlock stale locks (investigations locked for more than 5 minutes).
Number of investigations unlocked.
Promise.<number>
# cloneInvestigation(investigationId, userIdopt) → {Promise.<IInvestigation>}
Clones the current investigation by adding a "copy_N" postfix to its identifier.
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
investigationId |
string
|
The ID of the current investigation to clone. |
|
userId |
string
|
<optional> |
The ID of the user cloning the investigation (will be set as the new author). |
- If an error occurs during the cloning process.
Error
- The cloned investigation object.
Promise.<IInvestigation>
# closeDatabaseConnection() → {Promise.<void>}
Close the active MongoDB connection if one exists.
Resolves after the connection is terminated.
Promise.<void>
# closeDatabases() → {Promise.<void>}
Close database connections.
Propagates shutdown errors.
unknown
Resolves when MongoDB and Redis connections are closed.
Promise.<void>
# closeRedisConnection() → {Promise.<void>}
Gracefully close the Redis connection if active.
Resolves when the connection quits.
Promise.<void>
# closeVault() → {void}
Closes the Vault service.
- If the Vault service cannot be closed.
Error
- Closes the Vault service.
void
# connectToDatabase() → {Promise.<void>}
Connect to MongoDB using the configured connection options.
Propagates connection errors once the retry budget is exhausted.
unknown
Resolves when the connection is established.
Promise.<void>
# connectToRedis() → {Promise.<Redis>}
Establish Redis connection for caching and pub/sub use cases.
Propagates connection errors/timeouts.
unknown
Resolves with a ready Redis client.
Promise.<Redis>
# convertEditableFieldToSimple(investigation) → {function}
Creates a helper function to extract a simplified version of an EditableField
from an investigation object.
The returned function allows retrieving a specific field by name and converts it into
a plain IEditableFieldSimple object, providing default values for missing properties.
Parameters:
| Name | Type | Description |
|---|---|---|
investigation |
IInvestigation
|
The investigation object containing |
- A function that accepts:
fieldName: The key of the field to extract.defaultValue: The fallback value if the field's value is missing (default: ""). ReturnsIEditableFieldSimpleornullif the field does not exist.
function
# convertInvestigationFromModel(investigation) → {ICreateInvestigationDto}
Converts an investigation from the database/model format to a simple DTO format suitable for API input or further processing.
Parameters:
| Name | Type | Description |
|---|---|---|
investigation |
IInvestigation
|
The investigation in the model format. |
The investigation converted to a simple ICreateInvestigationDto format.
ICreateInvestigationDto
# convertObjectsToInputFormat(objects, withCoordinates) → {Array.<object>}
Converts an array of IObjectBase objects with EditableField structures
into a plain input format suitable for API requests or other processing.
Extracts the value from each editable field and provides default fallbacks:
- Empty string for
nameandobjectId 0for position and rotation coordinatesnullfor size if not defined
Parameters:
| Name | Type | Description |
|---|---|---|
objects |
Array.<IObjectBase>
|
Array of objects with |
withCoordinates |
boolean
|
If true, it converts with coordinates fields(position, rotation, size), otherwise converts without them. |
- Array of plain objects with
name,objectId,position,rotation, andsize.
Array.<object>
# convertObjectsToSimple(objects) → {Array.<object>}
Convert database objects (IObject[]) to simple objects (ISimpleObject[]) for API response
Parameters:
| Name | Type | Description |
|---|---|---|
objects |
Array.<IObjectBase>
|
Database objects with EditableField structure |
- Simple objects for API response with default values instead of null/undefined
Array.<object>
# convertObjectsToUpdateFormat(objects) → {Array.<IUpdateObjectDto>}
Converts an array of simple objects (from AI response or plain format) to IUpdateObjectDto format. This is the reverse of convertObjectsToInputFormat - it converts from simple format to update DTO format.
Parameters:
| Name | Type | Description |
|---|---|---|
objects |
Array.<ISimpleObject>
|
Array.<ISimpleResponseObject>
|
Array of simple objects with plain values. |
- Array of objects in IUpdateObjectDto format suitable for update requests.
Array.<IUpdateObjectDto>
# convertStepsToSimple(steps) → {Array.<IStep>}
Convert database steps (IStep[]) to simple steps (ISimpleStep[]) for API response
Parameters:
| Name | Type | Description |
|---|---|---|
steps |
Array.<IInvestigationBaseStepModel>
|
Database steps with EditableField structure |
- Simple steps for API response with empty strings instead of undefined
Array.<IStep>
# createAuthMiddleware(options) → {function}
Create authentication middleware for Express routes
Parameters:
| Name | Type | Description |
|---|---|---|
options |
IAuthMiddlewareOptions
|
Configuration options for the middleware |
Express middleware function
function
# createEmptyEditableField(defaultValue) → {IEditableFieldResponse.<T>}
Creates an empty editable field response with default value
Parameters:
| Name | Type | Description |
|---|---|---|
defaultValue |
T
|
The default value to use for the empty field |
Empty editable field response with the default value
IEditableFieldResponse.<T>
# createInvestigation(createDto) → {Promise.<IInvestigation>}
Creates a new investigation.
Parameters:
| Name | Type | Description |
|---|---|---|
createDto |
ICreateInvestigationDto
|
The data required to create the investigation. |
- The created investigation.
Promise.<IInvestigation>
# createLink(investigationId, options, createdBy) → {Promise.<IUrl>}
Create a new link for an investigation. If subLink is provided: validate uniqueness and set origin HUMAN. If subLink is omitted: autogenerate from investigation title (or random), set origin AUTO.
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
investigationId |
Types.ObjectId
|
Investigation to attach the link to |
|
options |
object
|
Link options |
|
key |
string
|
Link key (e.g. "physical-tool") |
|
subLink |
string
|
<optional> |
Custom slug; if omitted, one is generated |
description |
string
|
<optional> |
Optional description |
createdBy |
Types.ObjectId
|
null
|
User ID who created the link (or null) |
The saved URL document
Promise.<IUrl>
# createMockInvestigationItem(overrides) → {IInvestigationListItemDto}
Creates a mock investigation list item with default or overridden values
Parameters:
| Name | Type | Description |
|---|---|---|
overrides |
Partial.<IInvestigationListItemDto>
|
Properties to override defaults |
Mock investigation item
IInvestigationListItemDto
# createMockSearchDto(overrides) → {IInvestigationSearchDto}
Creates a mock search DTO with default or overridden values
Parameters:
| Name | Type | Description |
|---|---|---|
overrides |
Partial.<IInvestigationSearchDto>
|
Properties to override defaults |
Mock search DTO
IInvestigationSearchDto
# createRangeValidation(fromField, toField) → {function}
Helper function to create a range validation refine Validates that a "from" field is less than or equal to a "to" field
Parameters:
| Name | Type | Description |
|---|---|---|
fromField |
string
|
Name of the "from" field |
toField |
string
|
Name of the "to" field |
Zod refine function that validates the range
function
# createSampleInvestigation() → {IInvestigation}
Create a sample investigation based on the Galileo Cloud interface
The sample investigation
IInvestigation
# createVersionEntry(investigation, updatedBy, isAiGeneratedopt) → {IInvestigationVersionEntryModel}
Creates a new version entry from the current investigation state.
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
investigation |
IInvestigation
|
Investigation document to version. |
|
updatedBy |
Types.ObjectId
|
null
|
User id who made the change (null when not available). |
|
isAiGenerated |
boolean
|
<optional> |
Whether the versioned state was AI-generated (defaults to false). |
Version entry containing snapshot and metadata.
IInvestigationVersionEntryModel
# createWebSocketServer(httpServer) → {WebSocketServer}
Create a general-purpose WebSocket server for Unity WebGL and other platforms
Parameters:
| Name | Type | Description |
|---|---|---|
httpServer |
HTTPServer
|
HTTP server instance to attach WebSocket server to |
WebSocketServer instance
WebSocketServer
# deleteInvestigationById(investigationId) → {Promise.<IDeleteInvestigationByIdResponse>}
Permanently deletes an investigation and its related chat history.
Parameters:
| Name | Type | Description |
|---|---|---|
investigationId |
string
|
The ID of the investigation to delete. |
- If an error occurs during the deletion process.
Error
- An object summarizing the deletion status of the investigation and related chats.
Promise.<IDeleteInvestigationByIdResponse>
# deleteInvestigationData(investigation) → {IInvestigation}
Deletes the data of a given investigation.
Parameters:
| Name | Type | Description |
|---|---|---|
investigation |
IInvestigation
|
The investigation to clear. |
- If an error occurs during the deletion process.
Error
- The investigation object with its values emptied.
IInvestigation
# emitInvestigationUpdated(investigationId, payload)
Emit an "investigation:updated" event to all subscribers of the given investigation room.
Parameters:
| Name | Type | Description |
|---|---|---|
investigationId |
string
|
Investigation identifier used as room name. |
payload |
object
|
Arbitrary payload to send with the event. |
updatedBy |
string
|
null
|
The ID of the user who updated the investigation. |
updatedAt |
string
|
null
|
The date and time the investigation was updated. |
updatedFields |
unknown
|
The fields that were updated. |
# enrichInvestigationResponse(investigation, dto, grpcClient) → {Promise.<void>}
Enriches an investigation response DTO with detailed author and editor profile information.
Fetches user profiles from the Auth gRPC service using batch fetch and populates
the metadata.author and metadata.editorsDetailed fields with user details such as
name, email, and avatar.
Parameters:
| Name | Type | Description |
|---|---|---|
investigation |
IInvestigation
|
The investigation object containing metadata. |
dto |
IInvestigationResponseDto
|
The investigation response DTO to enrich. |
grpcClient |
AuthGrpcService
|
The Auth gRPC client used to fetch user profiles. |
- Enriches the
dtoobject in-place.
Promise.<void>
# async enrichItemsWithProfiles(items, grpcClientopt) → {Promise.<Array.<IInvestigationListItemDto>>}
Enriches investigation list items with author profile information.
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
items |
Array.<IInvestigationListItemDto>
|
The investigation items to enrich. |
|
grpcClient |
AuthGrpcService
|
<optional> |
Optional gRPC client for fetching user profiles. |
- Items enriched with author profiles.
Promise.<Array.<IInvestigationListItemDto>>
# enrichUserItems(items, grpcClient) → {Promise.<IUserProfile>}
Enriches items that have an id field with user profile information (name, email, avatar).
Commonly used for enriching authors/editors lists in filter metadata.
Parameters:
| Name | Type | Description |
|---|---|---|
items |
Array
|
Array of items with |
grpcClient |
AuthGrpcService
|
undefined
|
gRPC client for fetching profiles (if undefined, returns items unchanged) |
Promise resolving to items with populated name, email, and avatar fields
Promise.<IUserProfile>
# ensureInvestigationAuthor(investigationId, authorId) → {Promise.<(IInvestigation|null)>}
Ensures that the author of a given investigation is set.
If the investigation exists and does not already have a valid author, this method sets the author
to the provided authorId and updates the dateModified field.
Parameters:
| Name | Type | Description |
|---|---|---|
investigationId |
string
|
The ID of the investigation to check. |
authorId |
Types.ObjectId
|
The ObjectId of the author to set. |
If there is an error during the process of fetching or saving the investigation.
Error
- The updated investigation object, or
nullif the investigation does not exist or already has a valid author.
Promise.<(IInvestigation|null)>
# errorHandler(error, req, res, _next) → {void}
Error Handler Middleware
Parameters:
| Name | Type | Description |
|---|---|---|
error |
IApiError
|
The error object |
req |
Request
|
The request object |
res |
Response
|
The response object |
_next |
NextFunction
|
The next function |
void
# async existsByKeyAndSubLink(key, subLink) → {Promise.<boolean>}
Check if a (key, subLink) pair already exists in the URLs collection.
Parameters:
| Name | Type | Description |
|---|---|---|
key |
string
|
Link key (e.g. "physical-tool") |
subLink |
string
|
Slug (normalized to lowercase) |
True if a URL document exists with this key and subLink
Promise.<boolean>
# fetchUserProfile(userId, profileCache, grpcClient) → {Promise.<IUserProfile>}
Fetches a user profile using a multi-layered caching strategy.
Parameters:
| Name | Type | Description |
|---|---|---|
userId |
string
|
The ID of the user whose profile is being fetched. |
profileCache |
Map.<string, (IUserProfile|Promise.<IUserProfile>)>
|
undefined
|
Optional memoization cache to prevent duplicate fetches. |
grpcClient |
AuthGrpcService
|
The gRPC client used to fetch the user if cache misses. |
The resolved user profile with name, avatar, and email fields (nullable if unavailable).
Promise.<IUserProfile>
# formatHistory(chatHistory) → {Array.<IFormattedHistory>}
Formats chat history into the OpenAI message format for LLM requests.
Parameters:
| Name | Type | Description |
|---|---|---|
chatHistory |
Array.<IChatHistory>
|
Chat exchanges between the user and assistant. |
Array of formatted messages ready for LLM consumption.
Array.<IFormattedHistory>
# fromEditableField(field, defaultValue, historyLimit) → {IEditableFieldResponse.<T>}
Convert editable field to response DTO format
Parameters:
| Name | Type | Description |
|---|---|---|
field |
IEditableField.<T>
|
null
|
undefined
|
The editable field to convert |
defaultValue |
T
|
The default value to use if the field is null or undefined |
historyLimit |
number
|
Maximum number of history entries to return |
The formatted editable field response
IEditableFieldResponse.<T>
# generateInvestigation(aiProcessor, message, history, investigationMetadata) → {Promise.<(IAssistantInvestigationFormat|null)>}
Generates an entire investigation based on the provided metadata. If the investigation is not found, it throws an error.
Parameters:
| Name | Type | Description |
|---|---|---|
aiProcessor |
AIProcessor
|
AI processor instance. |
message |
string
|
The user's message from which the lesson must be detected. |
history |
FormattedHistory
|
The chat history between the user and the assistant. |
investigationMetadata |
IMetadataDocument
|
The metadata of the investigation. |
- If the investigation is not found.
Error
- The generated investigation.
Promise.<(IAssistantInvestigationFormat|null)>
# generateInvestigationObjects(aiProcessor, message, history, investigationMetadata, investigation) → {Promise.<(IAssistantInvestigationFormat|null)>}
Generates objects of investigation based on the provided metadata and plain investigation. If the objects are not found, it throws an error.
Parameters:
| Name | Type | Description |
|---|---|---|
aiProcessor |
AIProcessor
|
AI processor instance. |
message |
string
|
The user's message from which the lesson must be detected. |
history |
string
|
The chat history between the user and the assistant. |
investigationMetadata |
string
|
The metadata of the investigation. |
investigation |
string
|
The plain investigation without steps and objects with yaml format. |
- If the objects are not found.
Error
- The generated objects of the provided investigation.
Promise.<(IAssistantInvestigationFormat|null)>
# generateInvestigationSteps(aiProcessor, message, history, investigationMetadata, investigation) → {Promise.<(IAssistantInvestigationFormat|null)>}
Generates steps of investigation based on the provided metadata and the provided investigation. If the steps are not found, it throws an error.
Parameters:
| Name | Type | Description |
|---|---|---|
aiProcessor |
AIProcessor
|
AI processor instance. |
message |
string
|
The user's message from which the lesson must be detected. |
history |
string
|
The chat history between the user and the assistant. |
investigationMetadata |
string
|
The metadata of the investigation. |
investigation |
string
|
The provided investigation without steps with yaml format. |
- If the steps are not found.
Error
- The generated steps of the provided investigation.
Promise.<(IAssistantInvestigationFormat|null)>
# generateInvestigationWithoutStepsAndObjects(aiProcessor, message, history, investigationMetadata) → {Promise.<(IAssistantInvestigationFormat|null)>}
Generates an investigation without steps and objects based on the provided metadata. If the investigation is not found, it throws an error.
Parameters:
| Name | Type | Description |
|---|---|---|
aiProcessor |
AIProcessor
|
AI processor instance. |
message |
string
|
The user's message from which the lesson must be detected. |
history |
string
|
The chat history between the user and the assistant. |
investigationMetadata |
string
|
The metadata of the investigation. |
- If the investigation is not found.
Error
- The generated investigation without steps and objects.
Promise.<(IAssistantInvestigationFormat|null)>
# getDatabaseStatus() → {object}
Snapshot of the current MongoDB connection state.
Connection metadata.
object
# getDefaultSortOrder(sortBy) → {SortOrder}
Determines the default sort order based on the sort field
Parameters:
| Name | Type | Description |
|---|---|---|
sortBy |
InvestigationSortBy
|
undefined
|
The field to sort by |
The default sort order for the field
# getFieldHistory(investigationId, fieldPath, limit) → {Promise.<{fieldPath: string, history: Array.<unknown>, totalCount: number}>}
Gets the history for a specific field in an investigation.
Parameters:
| Name | Type | Description |
|---|---|---|
investigationId |
string
|
The ID of the investigation. |
fieldPath |
string
|
The path to the field (e.g., "title", "steps.0.title", "objects.0.name"). |
limit |
number
|
Maximum number of history entries to return (default: 50). |
If the investigation is not found.
Error
The field history.
Promise.<{fieldPath: string, history: Array.<unknown>, totalCount: number}>
# getFieldOrEmpty(shouldBeEmpty, field, defaultValue, historyLimit) → {IEditableFieldResponse.<T>}
Returns either an empty field or converts from editable field based on condition
Parameters:
| Name | Type | Description |
|---|---|---|
shouldBeEmpty |
boolean
|
Whether to return an empty field |
field |
IEditableField.<T>
|
null
|
undefined
|
The editable field to convert if not empty |
defaultValue |
T
|
The default value to use |
historyLimit |
number
|
Maximum number of history entries to return |
Empty or populated editable field response
IEditableFieldResponse.<T>
# getFilterMetadata() → {Promise.<IInvestigationFilterMetadataDto>}
Retrieves filter metadata for investigations list. Returns available filter options with counts for status, curriculum, grade, authors, and editors. Uses MongoDB $facet aggregation to compute all counts in a single query.
- Filter metadata with counts for each dimension.
Promise.<IInvestigationFilterMetadataDto>
# getInvestigationById(investigationId) → {Promise.<IInvestigation>}
Retrieves a single investigation by its ID.
Parameters:
| Name | Type | Description |
|---|---|---|
investigationId |
string
|
The ID of the investigation to retrieve. |
If the investigation is not found.
Error
- The investigation data.
Promise.<IInvestigation>
# getInvestigationVersions(investigationId, limit) → {Promise.<IInvestigationVersionListResponse>}
Gets the versions of an investigation.
Parameters:
| Name | Type | Description |
|---|---|---|
investigationId |
string
|
The ID of the investigation. |
limit |
number
|
The number of versions to return (default: 20). |
If the investigation is not found.
Error
- The investigation versions.
Promise.<IInvestigationVersionListResponse>
# getInvestigations(searchDto, grpcClientopt) → {Promise.<IInvestigationListResponseDto>}
Retrieves investigations with filtering, sorting, and grouping.
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
searchDto |
IInvestigationSearchDto
|
The search and pagination parameters. |
|
grpcClient |
AuthGrpcService
|
<optional> |
Optional gRPC client for enriching user profiles. |
- The investigations with sections/items.
Promise.<IInvestigationListResponseDto>
# getLessonData(unit, hasInvestigation) → {Promise.<string>}
Retrieves lesson metadata for a given unit and formats it as a string.
Can optionally filter lessons based on whether they have an associated investigation. The returned string includes the unit name and a list of lessons with their numbers, titles, and optionally whether they have an investigation.
Parameters:
| Name | Type | Description |
|---|---|---|
unit |
string
|
The unit identifier to fetch lessons for. |
hasInvestigation |
boolean
|
null
|
Optional filter to only include lessons that do (true) or do not (false) have an investigation. If |
- A formatted string containing the unit and lesson information.
Promise.<string>
# getLinksByInvestigationId(investigationId) → {Promise.<Array.<IUrl>>}
List all links for an investigation, sorted by creation date.
Parameters:
| Name | Type | Description |
|---|---|---|
investigationId |
Types.ObjectId
|
Investigation ID |
Array of URL documents (plain objects from lean())
Promise.<Array.<IUrl>>
# getLogger() → {Logger}
Get the logger from the async local storage context
Logger instance with request ID, or base logger if no context
Logger
# getRandomMetadata() → {Promise.<(IMetadataDocument|null)>}
Retrieves a random metadata entry for investigation generation.
- A random metadata document or null if none found.
Promise.<(IMetadataDocument|null)>
# getRedisStatus() → {object}
Snapshot of the Redis client status.
High-level connection flags.
object
# getRequestId() → {string|undefined}
Get the request ID from the async local storage context
Request ID string or undefined if not in context
string
|
undefined
# getSocketServer() → {SocketIOServer|null}
Get the currently registered Socket.IO server instance, if any.
Socket.IO server instance or null.
SocketIOServer
|
null
# getUnitNames() → {Promise.<string>}
Retrieves all unique units with their names and descriptions, grouped by grade. Formats the output similar to the detect_unit_from_message prompt format.
- A formatted string containing all units grouped by grade.
Promise.<string>
# handleWebSocketConnection(ws, request)
Handle new WebSocket connections
Parameters:
| Name | Type | Description |
|---|---|---|
ws |
WebSocket
|
WebSocket instance |
request |
IncomingMessage
|
HTTP request |
# hasArrayValue(value) → {boolean}
Type-safe version of hasValue for arrays
Parameters:
| Name | Type | Description |
|---|---|---|
value |
Array.<unknown>
|
undefined
|
null
|
The value to check |
- true if the value is not null and is an array
boolean
# hasNumberValue(value) → {boolean}
Type-safe version of hasValue for numbers
Parameters:
| Name | Type | Description |
|---|---|---|
value |
number
|
undefined
|
null
|
The value to check |
- true if the value is not null
boolean
# hasStringValue(value) → {boolean}
Type-safe version of hasValue for strings
Parameters:
| Name | Type | Description |
|---|---|---|
value |
string
|
undefined
|
null
|
The value to check |
- true if the value is not null, undefined, or empty string
boolean
# initializeDatabases() → {Promise.<void>}
Initialize database connections.
Propagates connection errors.
unknown
Resolves when MongoDB and Redis are ready.
Promise.<void>
# initializeVault() → {Promise.<void>}
Initializes the Vault service and loads secrets from Vault.
- Promise that resolves when the Vault service is initialized and secrets are loaded.
Promise.<void>
# lockInvestigation(investigationId, userId) → {Promise.<IInvestigation>}
Lock an investigation for editing by a specific user.
Parameters:
| Name | Type | Description |
|---|---|---|
investigationId |
string
|
The investigation ID to lock. |
userId |
string
|
The user ID who is locking the investigation. |
The updated investigation.
Promise.<IInvestigation>
# mapHistoryEntries(history, limit) → {Array.<IFieldHistoryEntryResponse>|undefined}
Maps history entries to response format
Parameters:
| Name | Type | Description |
|---|---|---|
history |
Array.<IHistoryEntry.<T>>
|
undefined
|
Array of history entries to map |
limit |
number
|
Maximum number of history entries to return |
Mapped history entries or undefined if no history
Array.<IFieldHistoryEntryResponse>
|
undefined
# mapVector3History(vector, limit) → {IVector3HistoryResponse|undefined}
Maps Vector3 history (x, y, z) to response format
Parameters:
| Name | Type | Description |
|---|---|---|
vector |
IVector3Editable
|
undefined
|
Vector3 object with x, y, z editable fields |
limit |
number
|
Maximum number of history entries per axis |
Object with x, y, z history arrays or undefined if no vector
IVector3HistoryResponse
|
undefined
# notFoundHandler(req, res) → {void}
Not Found Handler Middleware
Parameters:
| Name | Type | Description |
|---|---|---|
req |
Request
|
The request object |
res |
Response
|
The response object |
void
# optionalAuth(options) → {function}
Create optional authentication middleware
Parameters:
| Name | Type | Description |
|---|---|---|
options |
IAuthMiddlewareOptions
|
Configuration options for the middleware |
Express middleware function that optionally authenticates
function
# parseQueryStringArray(val) → {Array.<T>|undefined}
Parses a query parameter value into an array of specified type Handles both comma-separated strings and array inputs
Parameters:
| Name | Type | Description |
|---|---|---|
val |
unknown
|
The query parameter value to parse |
Parsed array or undefined if value is falsy
Array.<T>
|
undefined
Examples
// Comma-separated string
parseQueryStringArray<string>("foo,bar,baz") // ["foo", "bar", "baz"]
// Array input
parseQueryStringArray<string>(["foo", "bar"]) // ["foo", "bar"]
// Single value
parseQueryStringArray<string>("foo") // ["foo"]
// Empty/undefined
parseQueryStringArray<string>(undefined) // undefined
# prepareSnapshotForRestore(snapshot) → {Record.<string, unknown>}
Removes document metadata from a snapshot payload before restore.
Parameters:
| Name | Type | Description |
|---|---|---|
snapshot |
Record.<string, unknown>
|
Snapshot data as stored in versions. |
Snapshot payload without Mongo/Mongoose metadata fields.
Record.<string, unknown>
# randomSuffix() → {string}
Generate a short random subLink suffix (URL-safe).
Lowercase URL-safe string (up to 8 chars)
string
# redoInvestigation(investigationId) → {Promise.<IInvestigation>}
Redo investigation - increment currentVersionIndex and return investigation at that version
Parameters:
| Name | Type | Description |
|---|---|---|
investigationId |
string
|
The ID of the investigation. |
If the investigation is not found or if the index is out of bounds.
Error
- The investigation at the new index.
Promise.<IInvestigation>
# regenerateOtherFields(aiProcessor, investigationId, fieldName, updatedBy, historyopt) → {Promise.<IInvestigation>}
Regenerates other fields in an investigation based on a specific field. This operation uses a 3-step process: text fields → objects → steps.
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
aiProcessor |
AIProcessor
|
AI processor instance. |
|
investigationId |
string
|
The ID of the investigation to update. |
|
fieldName |
string
|
The name of the field to base regeneration on (e.g., "title", "curriculum", "objectives"). |
|
updatedBy |
Types.ObjectId
|
null
|
The user making the change (optional). |
|
history |
string
|
<optional> |
Chat history in YAML format (optional, defaults to "-"). |
If the investigation is not found or the field is invalid.
Error
- The updated investigation.
Promise.<IInvestigation>
# regenerateOtherFieldsObjects(aiProcessor, fieldName, fieldValue, investigation, investigationMetadata, historyopt, contradictionInfoopt) → {Promise.<(IAssistantInvestigationFormat|null)>}
Regenerates objects based on regenerated text fields. This is Step 2 of the 3-step regeneration process.
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
aiProcessor |
AIProcessor
|
AI processor instance. |
|
fieldName |
string
|
The name of the field to base regeneration on. |
|
fieldValue |
string
|
The value of the field to base regeneration on. |
|
investigation |
string
|
The regenerated investigation from Step 1 (YAML format). |
|
investigationMetadata |
string
|
The metadata/guide in YAML format. |
|
history |
string
|
<optional> |
Chat history in YAML format (optional, defaults to "-"). |
contradictionInfo |
object
|
<optional> |
Optional contradiction information. |
contradictionReason |
string
|
null
|
<optional> |
Reason for contradiction. |
targetFieldName |
string
|
null
|
<optional> |
Target field name for contradiction. |
isContradicting |
boolean
|
<optional> |
Whether the field is contradicting. |
If the prompt is not found or regeneration fails.
Error
- The regenerated objects only.
Promise.<(IAssistantInvestigationFormat|null)>
# regenerateOtherFieldsSteps(aiProcessor, fieldName, fieldValue, investigation, investigationMetadata, historyopt, contradictionInfoopt) → {Promise.<(IAssistantInvestigationFormat|null)>}
Regenerates steps based on regenerated text fields and objects. This is Step 3 of the 3-step regeneration process.
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
aiProcessor |
AIProcessor
|
AI processor instance. |
|
fieldName |
string
|
The name of the field to base regeneration on. |
|
fieldValue |
string
|
The value of the field to base regeneration on. |
|
investigation |
string
|
The regenerated investigation from Step 1 + Step 2 (YAML format). |
|
investigationMetadata |
string
|
The metadata/guide in YAML format. |
|
history |
string
|
<optional> |
Chat history in YAML format (optional, defaults to "-"). |
contradictionInfo |
object
|
<optional> |
Optional contradiction information. |
contradictionReason |
string
|
null
|
<optional> |
Reason for contradiction. |
targetFieldName |
string
|
null
|
<optional> |
Target field name for contradiction. |
isContradicting |
boolean
|
<optional> |
Whether the field is contradicting. |
If the prompt is not found or regeneration fails.
Error
- The regenerated steps only.
Promise.<(IAssistantInvestigationFormat|null)>
# regenerateOtherFieldsWithoutStepsAndObjects(aiProcessor, fieldName, fieldValue, investigation, investigationMetadata, historyopt, contradictionInfoopt) → {Promise.<(IAssistantInvestigationFormat|null)>}
Regenerates text fields (without steps and objects) based on a specific field value. This is Step 1 of the 3-step regeneration process.
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
aiProcessor |
AIProcessor
|
AI processor instance. |
|
fieldName |
string
|
The name of the field to base regeneration on. |
|
fieldValue |
string
|
The value of the field to base regeneration on. |
|
investigation |
string
|
The current investigation in YAML format. |
|
investigationMetadata |
string
|
The metadata/guide in YAML format. |
|
history |
string
|
<optional> |
Chat history in YAML format (optional, defaults to "-"). |
contradictionInfo |
object
|
<optional> |
Optional contradiction information. |
contradictionReason |
string
|
null
|
<optional> |
Reason for contradiction. |
targetFieldName |
string
|
null
|
<optional> |
Target field name for contradiction. |
isContradicting |
boolean
|
<optional> |
Whether the field is contradicting. |
If the prompt is not found or regeneration fails.
Error
- The regenerated text fields only.
Promise.<(IAssistantInvestigationFormat|null)>
# registerInvestigationCollaborationHandlers(io, socket, context)
Register real-time collaboration (presence + action tracking) handlers for a specific investigation on a given socket connection.
Parameters:
| Name | Type | Description |
|---|---|---|
io |
SocketIOServer
|
Socket.IO server instance. |
socket |
Socket
|
Connected client socket. |
context |
ICollaborationContext
|
Connection and user metadata. |
# removeAiGeneratedValues(obj)
Recursively sets all aiGeneratedValue fields to null.
This method is schema-agnostic and works regardless of changes to the investigation structure.
Parameters:
| Name | Type | Description |
|---|---|---|
obj |
Record.<string, unknown>
|
The object whose |
# removeInvestigationObjectCoordinates(investigation) → {IInvestigationWithoutObjectsCoordinatesDto}
Removes the current investigation objects' coordinates
Parameters:
| Name | Type | Description |
|---|---|---|
investigation |
IInvestigation
|
The investigation in the model format. |
The investigation converted to a simple ICreateInvestigationDto format.
IInvestigationWithoutObjectsCoordinatesDto
# requestIdMiddleware(req, res, next)
Middleware to add request ID tracking to each request
Parameters:
| Name | Type | Description |
|---|---|---|
req |
Request
|
Express request object |
res |
Response
|
Express response object |
next |
NextFunction
|
Express next function |
# requireAdmin(options) → {function}
Create middleware that requires admin role
Parameters:
| Name | Type | Description |
|---|---|---|
options |
Omit.<IAuthMiddlewareOptions, "requiredRoles">
|
Configuration options (excluding requiredRoles) |
Express middleware function that only allows admin users
function
# resolveAndIncrementVisit(key, subLink) → {Promise.<IResolveLinkResult>}
Resolve a link by (key, subLink): increment visit count and return investigation id.
Parameters:
| Name | Type | Description |
|---|---|---|
key |
string
|
Link key (e.g. "physical-tool") |
subLink |
string
|
Slug identifying the link |
404 if no URL document exists for this key and subLink
Resolve result with investigationId, linkId, and counters
Promise.<IResolveLinkResult>
# restoreInvestigationFromSnapshot(investigation, snapshot) → {IInvestigation}
Restores an investigation from a snapshot
Parameters:
| Name | Type | Description |
|---|---|---|
investigation |
IInvestigation
|
The investigation document to restore |
snapshot |
IInvestigationSnapshot
|
The snapshot data to apply |
- The investigation with snapshot data applied
IInvestigation
# saveFieldHistory(investigation, updateFields, updatedBy) → {Record.<string, {historyEntry: *, fieldPath: string}>}
Computes history updates for an investigation update payload.
Parameters:
| Name | Type | Description |
|---|---|---|
investigation |
IInvestigation
|
Current investigation document (used as the source of "old" values). |
updateFields |
MongoUpdateFields
|
Flat update payload (typically produced by the builder) to compare against current values. |
updatedBy |
Types.ObjectId
|
null
|
User id who made the change (null when not available). |
History entries keyed by base field path.
Record.<string, {historyEntry: *, fieldPath: string}>
# async seedInvestigation() → {Promise.<void>}
Main seed function
A promise that resolves when the seed script is completed
Promise.<void>
# setSocketServer(io)
Attach a Socket.IO server instance so that other modules (e.g. controllers) can emit real-time events without tight coupling to the HTTP bootstrap code.
This should be called once during application startup from the place where the Socket.IO server is created.
Parameters:
| Name | Type | Description |
|---|---|---|
io |
SocketIOServer
|
Socket.IO server instance. |
# setupConnectionEventListeners()
Register listeners for Mongo connection lifecycle events.
# setupPhysicsHandlers(client, optionsopt)
Setup physics handlers for a WebSocket client
Parameters:
| Name | Type | Attributes | Description |
|---|---|---|---|
client |
WebSocketClient
|
WebSocket client |
|
options |
IPhysicsHandlerOptions
|
<optional> |
Optional overrides (e.g. physics host for dev-stage) |
# setupRedisEventListeners(client)
Internal helper that wires Redis connection lifecycle logging.
Parameters:
| Name | Type | Description |
|---|---|---|
client |
Redis
|
Connected Redis instance. |
# slugify(text) → {string}
Slugify a string for use as subLink: lowercase, alphanumeric + . _ -
Parameters:
| Name | Type | Description |
|---|---|---|
text |
string
|
Raw string (e.g. investigation title) |
Slug suitable for subLink (max SUBLINK_MAX_LENGTH chars)
string
# stripMarkdown(text) → {string}
Strips markdown formatting from text while preserving HTML/XML tags. Used to clean AI assistant responses before displaying to users.
Parameters:
| Name | Type | Description |
|---|---|---|
text |
string
|
The text containing markdown formatting |
The text with markdown formatting removed
string
# toInvestigationResponseDto(investigation) → {IInvestigationResponseDto}
Convert Investigation database model to Response DTO
Parameters:
| Name | Type | Description |
|---|---|---|
investigation |
IInvestigation
|
The investigation document from the database |
- The formatted response DTO
IInvestigationResponseDto
# toUrlResponseDto(doc) → {IUrlResponseDto}
Map a URL document (or lean plain object) to the response DTO shape.
Parameters:
| Name | Type | Description |
|---|---|---|
doc |
IUrl
|
URL document or lean result |
DTO with string ids and flattened counters
IUrlResponseDto
# toggleInvestigationDevelopment(investigationId) → {Promise.<IInvestigation>}
Sends/return investigation to/from InDevelopment.
Parameters:
| Name | Type | Description |
|---|---|---|
investigationId |
string
|
The ID of the investigation. |
If the investigation is not found.
Error
- The modified investigation.
Promise.<IInvestigation>
# trimEditableField(field)
Helper function to trim string fields in an editable field object
Parameters:
| Name | Type | Description |
|---|---|---|
field |
Record.<string, unknown>
|
null
|
undefined
|
Editable field object |
# trimIfString(value) → {unknown}
Helper function to trim a string value if it exists
Parameters:
| Name | Type | Description |
|---|---|---|
value |
unknown
|
Value to trim |
Trimmed value or original value if not a string
unknown
# trimUpdateObject(obj)
Helper function to recursively trim string values in an update object Handles $set operations and nested editable field structures
Parameters:
| Name | Type | Description |
|---|---|---|
obj |
Record.<string, unknown>
|
Object to process |
# undoInvestigation(investigationId) → {Promise.<IInvestigation>}
Undo investigation - decrement currentVersionIndex and return investigation at that version
Parameters:
| Name | Type | Description |
|---|---|---|
investigationId |
string
|
The ID of the investigation. |
If the investigation is not found or if the index is out of bounds.
Error
- The investigation at the new index.
Promise.<IInvestigation>
# unlockInvestigation(investigationId, userId) → {Promise.<IInvestigation>}
Unlock an investigation. Only the user who locked it can unlock it.
Parameters:
| Name | Type | Description |
|---|---|---|
investigationId |
string
|
The investigation ID to unlock. |
userId |
string
|
The user ID attempting to unlock (must be the lock owner). |
The updated investigation.
Promise.<IInvestigation>
# updateInvestigation(investigationId, updateData, obj) → {Promise.<IUpdateInvestigationResponse>}
Updates an investigation using the new API format.
Parameters:
| Name | Type | Description |
|---|---|---|
investigationId |
string
|
The ID of the investigation to update. |
updateData |
IUpdateInvestigationDto
|
The update data in the new format, including string/number fields and step updates. |
obj |
object
|
Optional object used to determine if the update data should be built from scratch. |
needsBuildUpdate |
boolean
|
Whether the update data should be built from scratch. |
updatedBy |
Types.ObjectId
|
null
|
The user making the change (optional). |
isAiGenerated |
boolean
|
Whether this update is AI-generated (default: false). |
skipVersioning |
boolean
|
Whether to skip versioning (default: false). |
If the investigation is not found or is locked.
Error
- The result of the update operation.
Promise.<IUpdateInvestigationResponse>
# updateInvestigationByVersion(oldInvestigation, investigation, userId, isUserChangeExist) → {Promise.<IInvestigation>}
Updates investigation by adding new version.
Parameters:
| Name | Type | Description |
|---|---|---|
oldInvestigation |
IInvestigation
|
The latest investigation version. |
investigation |
IInvestigation
|
The entire investigation model. |
userId |
ObjectId
|
null
|
The ID of the user. |
isUserChangeExist |
boolean
|
Whether the change was made by the user (true) or AI (false). Defaults to false. |
- If an error occurs during the update process.
Error
- An investigation updated with new version.
Promise.<IInvestigation>
# validateRequest(schema) → {function}
Middleware factory for request validation
Parameters:
| Name | Type | Description |
|---|---|---|
schema |
object
|
The schema to validate the request |
body |
ZodSchema.<unknown>
|
The schema to validate the request body |
query |
ZodSchema.<unknown>
|
The schema to validate the request query |
params |
ZodSchema.<Record.<string, string>>
|
The schema to validate the request parameters |
Express middleware function
function