-
Notifications
You must be signed in to change notification settings - Fork 72
feat(api): added endpoints for cohorts #3976
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
Part of ENG-420 Signed-off-by: Ramil Garipov <ramil@metriport.com>
WalkthroughThis change introduces a comprehensive cohort management feature in the medical API. It adds database associations, command handlers for creating, updating, deleting, and querying cohorts, as well as bulk patient assignment/removal logic. New Express routes, DTOs, and validation schemas are implemented for RESTful cohort operations, with supporting model and error-handling enhancements. Changes
Sequence Diagram(s)sequenceDiagram
participant Client
participant API_Router
participant CohortCmd
participant DB
%% Cohort Creation
Client->>API_Router: POST /cohort (name, monitoring)
API_Router->>CohortCmd: createCohort({cxId, name, monitoring})
CohortCmd->>DB: Check for existing cohort (cxId, name)
DB-->>CohortCmd: Exists? (yes/no)
alt Exists
CohortCmd-->>API_Router: Throw BadRequestError
API_Router-->>Client: 400 Error
else Not Exists
CohortCmd->>DB: Insert new cohort
DB-->>CohortCmd: Cohort created
CohortCmd-->>API_Router: Cohort data
API_Router-->>Client: 201 Created + CohortDTO
end
%% Bulk Assign Patients to Cohort
Client->>API_Router: POST /cohort/:id/patient (patientIds or all)
API_Router->>CohortCmd: bulkAssignPatientsToCohort(params)
CohortCmd->>DB: Validate cohort exists
CohortCmd->>DB: Insert PatientCohort records (bulk)
DB-->>CohortCmd: Insert result
CohortCmd->>DB: Get updated patient IDs/count
DB-->>CohortCmd: List/count
CohortCmd-->>API_Router: Cohort + patientIds/count
API_Router-->>Client: 201 Created + CohortWithPatientIdsAndCountDTO
%% Bulk Remove Patients from Cohort
Client->>API_Router: DELETE /cohort/:id/patient (patientIds or all)
API_Router->>CohortCmd: bulkRemovePatientsFromCohort(params)
CohortCmd->>DB: Validate cohort exists
CohortCmd->>DB: Delete PatientCohort records (conditional)
DB-->>CohortCmd: Deleted count
CohortCmd-->>API_Router: Count
API_Router-->>Client: 204 No Content + count (JSON)
sequenceDiagram
participant Client
participant API_Router
participant CohortCmd
participant DB
%% Get All Cohorts with Patient Counts
Client->>API_Router: GET /cohort
API_Router->>CohortCmd: getCohorts({cxId})
CohortCmd->>DB: Query all cohorts for cxId
loop For each cohort
CohortCmd->>DB: Count assigned patients
end
CohortCmd-->>API_Router: List of cohorts with counts
API_Router-->>Client: 200 OK + [CohortWithCountDTO]
%% Update Cohort
Client->>API_Router: PUT /cohort/:id (name, monitoring)
API_Router->>CohortCmd: updateCohort({id, eTag, cxId, ...})
CohortCmd->>DB: Get cohort by id/cxId
CohortCmd->>DB: Check name uniqueness
CohortCmd->>DB: Update cohort fields
DB-->>CohortCmd: Updated cohort
CohortCmd-->>API_Router: Cohort data
API_Router-->>Client: 200 OK + CohortDTO
%% Delete Cohort
Client->>API_Router: DELETE /cohort/:id
API_Router->>CohortCmd: deleteCohort({id, cxId})
CohortCmd->>DB: Count assigned patients
alt Patients assigned
CohortCmd-->>API_Router: Throw BadRequestError
API_Router-->>Client: 400 Error
else No patients
CohortCmd->>DB: Delete cohort
DB-->>CohortCmd: Success
CohortCmd-->>API_Router: void
API_Router-->>Client: 204 No Content
end
Warning There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure. 🔧 ESLint
npm error code ERR_SSL_WRONG_VERSION_NUMBER 📜 Recent review detailsConfiguration used: CodeRabbit UI 📒 Files selected for processing (6)
🚧 Files skipped from review as they are similar to previous changes (6)
⏰ Context from checks skipped due to timeout of 90000ms (2)
✨ Finishing Touches
🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
Part of ENG-420 Signed-off-by: Ramil Garipov <ramil@metriport.com>
Part of ENG-420 Signed-off-by: Ramil Garipov <ramil@metriport.com>
Part of ENG-420 Signed-off-by: Ramil Garipov <ramil@metriport.com>
Part of ENG-420 Signed-off-by: Ramil Garipov <ramil@metriport.com>
Part of ENG-420 Signed-off-by: Ramil Garipov <ramil@metriport.com>
Part of ENG-420 Signed-off-by: Ramil Garipov <ramil@metriport.com>
cfa8308
to
179e8fe
Compare
Part of ENG-420 Signed-off-by: Ramil Garipov <ramil@metriport.com>
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 10
🧹 Nitpick comments (6)
packages/api/src/command/medical/cohort/delete-cohort.ts (1)
17-17
: Remove unnecessary return statement.The explicit
return;
statement is unnecessary in TypeScript functions that returnPromise<void>
.- log(`Done.`); - return; + log(`Done.`);packages/api/src/routes/medical/schemas/cohort.ts (1)
12-12
: Consider separate schemas for create vs update operations.Using an alias makes create and update schemas identical, but update operations typically have different validation requirements (e.g., optional fields, restricted updates).
Consider defining a separate update schema if future requirements differ:
-export const cohortUpdateSchema = cohortCreateSchema; +export const cohortUpdateSchema = z.object({ + name: z.string().optional(), + monitoring: monitoringSchema.optional(), +});This allows for more flexible validation where update fields can be optional.
packages/api/src/routes/medical/patient.ts (2)
552-552
: Fix incorrect parameter documentation.The comment mentions
cohortId
as a parameter, but it's actually in the request body.- * @param req.param.cohortId The ID of the cohort to assign the patient to. + * @param req.body.cohortId The ID of the cohort to assign the patient to.
575-575
: Fix incorrect parameter documentation.The comment mentions
cohortId
as a parameter, but it's actually in the request body.- * @param req.param.cohortId The ID of the cohort to unassign the patient from. + * @param req.body.cohortId The ID of the cohort to unassign the patient from.packages/api/src/command/medical/cohort/get-cohort.ts (1)
54-65
: Consider performance optimization for getCohorts function.The current implementation makes N+1 database queries (1 for cohorts + 1 for each cohort's patient count). For large numbers of cohorts, this could become a performance bottleneck.
Consider implementing a single query solution using database aggregation or joins to fetch all cohort counts in one operation:
export async function getCohorts({ cxId }: { cxId: string }): Promise<CohortWithCount[]> { - const cohorts = await CohortModel.findAll({ - where: { cxId }, - }); - - return Promise.all( - cohorts.map(async cohort => ({ - cohort: cohort.dataValues, - count: await getCountOfPatientsAssignedToCohort({ cohortId: cohort.id }), - })) - ); + // Consider implementing a single query with LEFT JOIN and GROUP BY + // to fetch cohorts with patient counts in one database operation + const cohorts = await CohortModel.findAll({ + where: { cxId }, + // Add appropriate joins and aggregation here + }); + + return cohorts.map(cohort => ({ + cohort: cohort.dataValues, + count: cohort.patientCount || 0, // Assuming count comes from aggregation + })); }packages/api/src/command/medical/cohort/patient-cohort/patient-cohort.ts (1)
141-148
: Consider adding validation for bulk removal operations.When removing specific patient IDs, consider validating that the patient IDs exist and belong to the specified context before attempting removal.
Add validation for patient IDs when not removing all:
await getCohortModelOrFail({ id: cohortId, cxId }); + // Validate patient IDs if specific patients are being removed + if (data.patientIds && !data.all) { + const patientValidationResults = await Promise.allSettled( + data.patientIds.map(patientId => getPatientOrFail({ id: patientId, cxId })) + ); + + const invalidPatientIds = patientValidationResults + .filter((result): result is PromiseRejectedResult => result.status === "rejected") + .map(result => result.reason?.additionalInfo?.id || 'unknown') + .filter(id => id !== 'unknown'); + + if (invalidPatientIds.length > 0) { + throw new BadRequestError( + `Some patients do not exist: [${invalidPatientIds.join(", ")}]`, + undefined, + { invalidPatientIds: JSON.stringify(invalidPatientIds) } + ); + } + } const whereClause = data.all ? { cohortId } : { cohortId, patientId: { [Op.in]: data.patientIds } };
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (12)
packages/api/src/command/medical/cohort/create-cohort.ts
(1 hunks)packages/api/src/command/medical/cohort/delete-cohort.ts
(1 hunks)packages/api/src/command/medical/cohort/get-cohort.ts
(1 hunks)packages/api/src/command/medical/cohort/patient-cohort/patient-cohort.ts
(1 hunks)packages/api/src/command/medical/cohort/update-cohort.ts
(1 hunks)packages/api/src/routes/medical/cohort.ts
(1 hunks)packages/api/src/routes/medical/dtos/cohortDTO.ts
(1 hunks)packages/api/src/routes/medical/dtos/patient-cohort.ts
(1 hunks)packages/api/src/routes/medical/index.ts
(2 hunks)packages/api/src/routes/medical/patient.ts
(3 hunks)packages/api/src/routes/medical/schemas/cohort.ts
(1 hunks)packages/api/src/routes/medical/schemas/patient-cohort.ts
(1 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
`**/*.ts`: - Use the Onion Pattern to organize a package's code in layers - Try to use immutable code and avoid sharing state across different functions, objects, and systems - Try...
**/*.ts
: - Use the Onion Pattern to organize a package's code in layers
- Try to use immutable code and avoid sharing state across different functions, objects, and systems
- Try to build code that's idempotent whenever possible
- Prefer functional programming style functions: small, deterministic, 1 input, 1 output
- Minimize coupling / dependencies
- Avoid modifying objects received as parameter
- Only add comments to code to explain why something was done, not how it works
- Naming
- classes, enums:
PascalCase
- constants, variables, functions:
camelCase
- file names:
kebab-case
- table and column names:
snake_case
- Use meaningful names, so whoever is reading the code understands what it means
- Don’t use negative names, like
notEnabled
, preferisDisabled
- For numeric values, if the type doesn’t convey the unit, add the unit to the name
- Typescript
- Use types
- Prefer
const
instead oflet
- Avoid
any
and casting fromany
to other types- Type predicates: only applicable to narrow down the type, not to force a complete type conversion
- Prefer deconstructing parameters for functions instead of multiple parameters that might be of
the same type- Don’t use
null
inside the app, only on code interacting with external interfaces/services,
like DB and HTTP; convert toundefined
before sending inwards into the code- Use
async/await
instead of.then()
- Use the strict equality operator
===
, don’t use abstract equality operator==
- When calling a Promise-returning function asynchronously (i.e., not awaiting), use
.catch()
to
handle errors (seeprocessAsyncError
andemptyFunction
depending on the case)- Date and Time
- Always use
buildDayjs()
to createdayjs
instances- Prefer
dayjs.duration(...)
to create duration consts and keep them asduration
- Prefer Nullish Coalesce (??) than the OR operator (||) to provide a default value
- Avoid creating arrow functions
- Use truthy syntax instead of
in
- i.e.,if (data.link)
notif ('link' in data)
- Error handling
- Pass the original error as the new one’s
cause
so the stack trace is persisted- Error messages should have a static message - add dynamic data to MetriportError's
additionalInfo
prop- Avoid sending multiple events to Sentry for a single error
- Global constants and variables
- Move literals to constants declared after imports when possible (avoid magic numbers)
- Avoid shared, global objects
- Avoid using
console.log
andconsole.error
in packages other than utils, infra and shared,
and try to useout().log
instead- Avoid multi-line logs
- don't send objects as a second parameter to
console.log()
orout().log()
- don't create multi-line strings when using
JSON.stringify()
- Use
eslint
to enforce code style- Use
prettier
to format code- max column length is 100 chars
- multi-line comments use
/** */
- scripts: top-level comments go after the import
packages/api/src/routes/medical/index.ts
packages/api/src/command/medical/cohort/delete-cohort.ts
packages/api/src/command/medical/cohort/create-cohort.ts
packages/api/src/routes/medical/schemas/cohort.ts
packages/api/src/routes/medical/patient.ts
packages/api/src/routes/medical/dtos/cohortDTO.ts
packages/api/src/command/medical/cohort/update-cohort.ts
packages/api/src/routes/medical/dtos/patient-cohort.ts
packages/api/src/routes/medical/schemas/patient-cohort.ts
packages/api/src/routes/medical/cohort.ts
packages/api/src/command/medical/cohort/get-cohort.ts
packages/api/src/command/medical/cohort/patient-cohort/patient-cohort.ts
🔇 Additional comments (12)
packages/api/src/routes/medical/index.ts (1)
6-6
: LGTM! Clean integration of cohort routes.The import and route registration follow the established patterns used by other medical routes in this file. The placement maintains alphabetical ordering and consistent structure.
Also applies to: 21-21
packages/api/src/command/medical/cohort/delete-cohort.ts (1)
6-18
: Excellent safety implementation for cohort deletion.The function properly validates that no patients are assigned before allowing deletion, preventing data integrity issues. The error handling and logging are well-implemented.
packages/api/src/routes/medical/dtos/patient-cohort.ts (1)
3-13
: Clean and well-structured DTO implementation.The DTO definition and mapping function are simple, type-safe, and follow functional programming principles. The naming is clear and consistent.
packages/api/src/command/medical/cohort/update-cohort.ts (1)
7-28
: Well-structured update command with proper concurrency control.The function implements good practices with version validation for concurrent updates and follows the async/await pattern correctly. The type definitions are clean and extend base types appropriately.
packages/api/src/routes/medical/dtos/cohortDTO.ts (1)
4-23
: Excellent DTO implementation with clean type definitions.The DTO structure is well-designed with appropriate optional fields, and the mapping function effectively uses the spread operator with
toBaseDTO
. The implementation follows functional programming principles and TypeScript best practices.packages/api/src/routes/medical/schemas/patient-cohort.ts (1)
1-18
: LGTM! Well-structured validation schemas.The schemas are well-designed with proper conditional validation using
refine
for the bulk removal schema. The code follows TypeScript best practices and naming conventions.packages/api/src/routes/medical/cohort.ts (1)
144-144
: Let’s locate the actual definitions and exports inget-cohort.ts
:#!/bin/bash set -eo pipefail echo "Looking for usages of both functions:" rg -n "getCohortWithCountOrFail" -n packages/api/src/command/medical/cohort/get-cohort.ts || true rg -n "getCohortWithPatientIdsOrFail" -n packages/api/src/command/medical/cohort/get-cohort.ts || true echo -e "\nListing all exports in the module:" rg -n "^export" -n packages/api/src/command/medical/cohort/get-cohort.ts || truepackages/api/src/command/medical/cohort/get-cohort.ts (1)
9-10
: Type definitions look good and follow naming conventions.The type definitions are well-structured and use descriptive names that clearly convey their purpose.
packages/api/src/command/medical/cohort/patient-cohort/patient-cohort.ts (4)
1-12
: Imports and dependencies are well-organized.The imports follow the coding guidelines with proper organization and the use of appropriate utilities and models.
14-27
: Type definitions are clear and follow naming conventions.The type definitions properly capture the required parameters for bulk operations with appropriate optional fields.
29-42
: Efficient parallel validation in assignCohort function.Good use of
Promise.all()
to validate cohort, patient, and existing assignment in parallel, which improves performance.
135-137
: Input validation logic is correct.The validation properly ensures that either
patientIds
orall
flag is provided, preventing invalid operations.
packages/api/src/command/medical/cohort/patient-cohort/patient-cohort.ts
Outdated
Show resolved
Hide resolved
packages/api/src/command/medical/cohort/patient-cohort/patient-cohort.ts
Outdated
Show resolved
Hide resolved
const cohorts = await CohortModel.findAll({ | ||
where: { cxId }, | ||
}); | ||
|
||
return Promise.all( | ||
cohorts.map(async cohort => ({ | ||
cohort: cohort.dataValues, | ||
count: await getCountOfPatientsAssignedToCohort({ cohortId: cohort.id }), | ||
})) | ||
); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This can be much more efficient w/ a DB join
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
implemented, but i hate the way the code looks now.. I think it might be worth keeping this version over this new one that doesnt look nearly as neat
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
There's neat code and there's efficient code. Doing joins in the DB should be straightforward and not considered an early optimization, so I'd rather have it and have the code slightly more complicated.
Have you confirmed the actual SQL that gets executed w/ the new Sequelize code, to make sure it's a single query?
Also, the response and/or call to cohort.get(countAttr)
is likely any
? Since there's no count
on `CohortModel. Maybe worth flagging that w/ a comment or something?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yes, confirmed that it's a single command.
Added the comment and type casting
packages/api/src/command/medical/cohort/patient-cohort/patient-cohort.ts
Outdated
Show resolved
Hide resolved
packages/api/src/command/medical/cohort/patient-cohort/patient-cohort.ts
Outdated
Show resolved
Hide resolved
packages/api/src/command/medical/cohort/patient-cohort/patient-cohort.ts
Outdated
Show resolved
Hide resolved
packages/api/src/command/medical/cohort/patient-cohort/patient-cohort.ts
Outdated
Show resolved
Hide resolved
packages/api/src/command/medical/cohort/patient-cohort/patient-cohort.ts
Outdated
Show resolved
Hide resolved
if (invalidPatientIds.length > 0) { | ||
log(`Found ${invalidPatientIds.length} invalid patients`); | ||
throw new BadRequestError( | ||
`Some patients do not exist: [${invalidPatientIds.join(", ")}]`, |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
fixed, static error messages please
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I actually did this because I wasn't seeing the additional details in the response. Will add that to the error handler
packages/api/src/command/medical/cohort/patient-cohort/patient-cohort.ts
Outdated
Show resolved
Hide resolved
export async function bulkRemovePatientsFromCohort({ | ||
cohortId, | ||
cxId, | ||
data, |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Why data
and not patientIds
+ all
?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
deconstructed the object on the route
|
||
return res | ||
.status(status.CREATED) | ||
.json({ message: "Patient(s) assigned to cohort", count: countAssigned }); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think we should return the same shape as GET /cohort/:id/patient
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Taken to Slack for discussions - link
Part of ENG-420
Issues:
Dependencies
Description
Testing
Release Plan
Summary by CodeRabbit
New Features
Bug Fixes
Tests