Members
# ASSISTANT_GREETING_MESSAGE
Assistant greeting message to the user
# constant AssistantSchema
Embedded schema representing assistant responses in the chat history.
# 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 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 FieldHistoryEntrySchema
Field History Entry Schema - Schema for a single history entry
# constant Investigation
Investigation Model This is the main model file that assembles all components
# constant InvestigationMetadataSchema
Investigation Metadata Schema - Metadata for an investigation
# constant InvestigationSchema
Investigation Schema Definition This file contains the main mongoose schema definition for investigations
# 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 ObjectSchema
Object Schema - 3D object with position, rotation, size, view and components
# constant Prompt
Prompt model providing access to reusable LLM prompt templates.
# constant StepSchema
Step Schema - Individual step in an investigation Each field is now wrapped with EditableFieldSchema for AI/human editing capabilities
# 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
# 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 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 subjectsFactory
Maps subject codes to their corresponding full names or educational levels.
- "K" => Kindergarten
- "1"-"5" => Elementary
- "6"-"8" => Middle
- "B" => Biology
- "C" => Chemistry
- "P" => Physics
Example
const subjectsFactory = {
K: "Kindergarten",
"1": "Elementary",
"2": "Elementary",
"3": "Elementary",
"4": "Elementary",
"5": "Elementary",
"6": "Middle",
"7": "Middle",
"8": "Middle",
B: "Biology",
C: "Chemistry",
P: "Physics",
};
Methods
# 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
# 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()
Establish Redis connection for caching and pub/sub use cases.
# 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
# createSampleInvestigation() → {IInvestigation}
Create a sample investigation based on the Galileo Cloud interface
The sample investigation
IInvestigation
# enrichInvestigationResponse(investigation, dto, grpcClient, profileCache) → {Promise.<void>}
Enriches an investigation response DTO with detailed author and editor profile information.
Fetches user profiles from the Auth gRPC service (or cache if provided) 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. |
profileCache |
Map.<string, (IUserProfile|Promise.<IUserProfile>)>
|
Optional cache to store/reuse fetched user profiles. |
- Enriches the
dtoobject in-place.
Promise.<void>
# 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
# fetchUserProfile(userId, profileCache, grpcClient) → {Promise.<IUserProfile>}
Fetches a user profile using a multi-layered caching strategy.
The function attempts to retrieve the profile in the following order:
- Memoization cache (if provided) to prevent duplicate fetches in-flight.
- Redis cache for fast retrieval.
- gRPC Auth service if cache misses occur.
- Falls back to null fields if gRPC fails (best-effort approach).
If a profileCache map is provided, this function will store both in-flight promises
and resolved profiles to handle concurrent requests safely.
Parameters:
| Name | Type | Description |
|---|---|---|
userId |
string
|
The ID of the user whose profile is being fetched. |
profileCache |
Map.<string, (IUserProfile|Promise.<IUserProfile>)>
|
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, andemailfields (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) → {IInvestigationResponseDto}
Convert Investigation database model to Response DTO
Parameters:
| Name | Type | Description |
|---|---|---|
field |
IEditableField.<unknown>
|
The editable field to convert |
defaultValue |
unknown
|
The default value to use if the field is null or undefined |
- The formatted response DTO
IInvestigationResponseDto
# getDatabaseStatus() → {object}
Snapshot of the current MongoDB connection state.
Connection metadata.
object
# 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>
# getLogger() → {Logger}
Get the logger from the async local storage context
Logger instance with request ID, or base logger if no context
Logger
# 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
# 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>
# 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>
# 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
# 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
# async seedInvestigation() → {Promise.<void>}
Main seed function
A promise that resolves when the seed script is completed
Promise.<void>
# setupConnectionEventListeners()
Register listeners for Mongo connection lifecycle events.
# setupRedisEventListeners(client)
Internal helper that wires Redis connection lifecycle logging.
Parameters:
| Name | Type | Description |
|---|---|---|
client |
Redis
|
Connected Redis instance. |
# 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
# 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