Skip to content

Conversation

RamilGaripov
Copy link
Contributor

@RamilGaripov RamilGaripov commented Jun 6, 2025

Part of ENG-420

Issues:

Dependencies

Description

  • Added endpoints for Cohorts
  • Video demonstration of how the endpoints execute in Postman - link

Testing

  • Local
    • Create a new collection on Postman
      • Test all endpoints
  • Staging
    • Create a new collection on Postman
      • Test all endpoints
  • Production
    • Create a new collection on Postman
      • Test all endpoints

Release Plan

  • Merge this

Summary by CodeRabbit

  • New Features

    • Introduced comprehensive cohort management: create, update, delete, and retrieve cohorts with patient counts and assignments.
    • Added REST API endpoints for cohort lifecycle and bulk patient assignment/removal.
    • Implemented validation schemas for cohorts and patient assignment inputs.
    • Provided data transfer objects (DTOs) for consistent cohort and patient-cohort data representation.
    • Enhanced patient filtering by IDs in retrieval operations.
  • Bug Fixes

    • Enhanced error responses to include additional contextual information when available.
  • Tests

    • Added tests validating input schema logic for patient selection and assignment.

Part of ENG-420

Signed-off-by: Ramil Garipov <ramil@metriport.com>
Copy link

linear bot commented Jun 6, 2025

Copy link

coderabbitai bot commented Jun 6, 2025

Walkthrough

This 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

File(s) Change Summary
.../command/medical/cohort/create-cohort.ts
.../update-cohort.ts
.../delete-cohort.ts
Added async functions for creating, updating, and deleting cohorts, including validation and error handling.
.../command/medical/cohort/get-cohort.ts Added functions for retrieving cohorts, including by ID, name, and with patient counts or IDs.
.../command/medical/cohort/patient-cohort/bulk-assign.ts
bulk-remove.ts
get-count.ts
get-assigned-ids.ts
Added functions for bulk assigning/removing patients to/from cohorts and for counting/retrieving assigned patients.
.../command/medical/patient/get-patient-read-only.ts Extended getPatientIds to filter by optional patient IDs array.
.../models/db.ts Added model associations for Cohort, Patient, and PatientCohort entities.
.../models/medical/cohort.ts
patient.ts
patient-cohort.ts
Added static associate methods and foreign key references for model relationships.
.../routes/medical/cohort.ts Implemented Express router for cohort CRUD and patient assignment/removal endpoints.
.../routes/medical/dtos/cohortDTO.ts
patient-cohort.ts
Added DTO types and mapping functions for cohorts and patient-cohort associations.
.../routes/medical/schemas/cohort.ts
patient-cohort.ts
shared.ts
Introduced Zod schemas for validating cohort and patient assignment/removal payloads.
.../routes/medical/schemas/tests/shared.test.ts Added tests for patient assignment/removal schema validation.
.../routes/medical/index.ts Registered the cohort router in the main medical API routing module.
.../routes/helpers/default-error-handler.ts Enhanced error handler to include additional info in error responses.

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)
Loading
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
Loading

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

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

npm error code ERR_SSL_WRONG_VERSION_NUMBER
npm error errno ERR_SSL_WRONG_VERSION_NUMBER
npm error request to https://10.0.0.28:4873/punycode/-/punycode-2.3.1.tgz failed, reason: C0ECEF03927F0000:error:0A00010B:SSL routines:ssl3_get_record:wrong version number:../deps/openssl/openssl/ssl/record/ssl3_record.c:354:
npm error
npm error A complete log of this run can be found in: /.npm/_logs/2025-06-20T17_10_39_713Z-debug-0.log


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a989c2c and ec48599.

📒 Files selected for processing (6)
  • packages/api/src/command/medical/cohort/patient-cohort/bulk-assign.ts (1 hunks)
  • packages/api/src/command/medical/patient/get-patient-read-only.ts (1 hunks)
  • packages/api/src/models/db.ts (1 hunks)
  • packages/api/src/models/medical/patient.ts (2 hunks)
  • packages/api/src/routes/medical/index.ts (2 hunks)
  • packages/api/src/routes/medical/schemas/shared.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (6)
  • packages/api/src/routes/medical/index.ts
  • packages/api/src/models/db.ts
  • packages/api/src/models/medical/patient.ts
  • packages/api/src/command/medical/patient/get-patient-read-only.ts
  • packages/api/src/command/medical/cohort/patient-cohort/bulk-assign.ts
  • packages/api/src/routes/medical/schemas/shared.ts
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: check-pr / lint-build-test
  • GitHub Check: Analyze (javascript)
✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need 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)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

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>
@RamilGaripov RamilGaripov force-pushed the eng-420-introduce-cohort-endpoints branch from cfa8308 to 179e8fe Compare June 18, 2025 18:36
Part of ENG-420

Signed-off-by: Ramil Garipov <ramil@metriport.com>
@RamilGaripov RamilGaripov marked this pull request as ready for review June 18, 2025 19:08
Copy link

@coderabbitai coderabbitai bot left a 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 return Promise<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

📥 Commits

Reviewing files that changed from the base of the PR and between d90706f and 3d3c621.

📒 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, prefer isDisabled
    • For numeric values, if the type doesn’t convey the unit, add the unit to the name
  • Typescript
    • Use types
    • Prefer const instead of let
    • Avoid any and casting from any 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 to undefined 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 (see processAsyncError and emptyFunction depending on the case)
    • Date and Time
      • Always use buildDayjs() to create dayjs instances
      • Prefer dayjs.duration(...) to create duration consts and keep them as duration
  • 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) not if ('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 and console.error in packages other than utils, infra and shared,
    and try to use out().log instead
  • Avoid multi-line logs
    • don't send objects as a second parameter to console.log() or out().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 in get-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 || true
packages/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 or all flag is provided, preventing invalid operations.

Comment on lines 55 to 64
const cohorts = await CohortModel.findAll({
where: { cxId },
});

return Promise.all(
cohorts.map(async cohort => ({
cohort: cohort.dataValues,
count: await getCountOfPatientsAssignedToCohort({ cohortId: cohort.id }),
}))
);
Copy link
Member

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

Copy link
Contributor Author

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

Copy link
Member

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?

Copy link
Contributor Author

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

if (invalidPatientIds.length > 0) {
log(`Found ${invalidPatientIds.length} invalid patients`);
throw new BadRequestError(
`Some patients do not exist: [${invalidPatientIds.join(", ")}]`,
Copy link
Member

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

Copy link
Contributor Author

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

export async function bulkRemovePatientsFromCohort({
cohortId,
cxId,
data,
Copy link
Member

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?

Copy link
Contributor Author

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 });
Copy link
Member

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

Copy link
Contributor Author

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

@RamilGaripov RamilGaripov deleted the eng-420-introduce-cohort-endpoints branch June 20, 2025 17:12
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants