-
Notifications
You must be signed in to change notification settings - Fork 68
Eng 420 introduce patient cohorts into our api #3962
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
Eng 420 introduce patient cohorts into our api #3962
Conversation
Part of ENG-420 Signed-off-by: Ramil Garipov <ramil@metriport.com>
Part of ENG-420 Signed-off-by: Ramil Garipov <ramil@metriport.com>
WalkthroughThis update introduces new domain types and Sequelize model classes for managing medical cohorts and their patient associations. It adds corresponding database migration scripts to create the necessary tables ("cohort" and "patient_cohort") and updates the model initialization logic to include the new models for Sequelize setup. Changes
Sequence Diagram(s)sequenceDiagram
participant Client
participant API
participant CohortModel
participant PatientCohortModel
participant Database
Client->>API: Request to create cohort
API->>CohortModel: Call setup/init
CohortModel->>Database: Create cohort record
Client->>API: Assign patient to cohort
API->>PatientCohortModel: Call setup/init
PatientCohortModel->>Database: Create patient_cohort association
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 (1)
🚧 Files skipped from review as they are similar to previous changes (1)
⏰ Context from checks skipped due to timeout of 90000ms (3)
✨ 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>
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: 2
🧹 Nitpick comments (4)
packages/core/src/domain/cohort.ts (1)
7-12
: Consider renamingcxId
for clarity
cxId
is an internal abbreviation that may not be obvious to new contributors.customerId
(or similar) would be self-explanatory and still map cleanly to thecx_id
DB column.packages/api/src/models/medical/cohort.ts (3)
13-31
: Avoid duplicating attributes & address linter warningYou build the attribute map twice (in
attributes()
and again insetup()
) and usesuper
inside a static context, which Biome flags. Prefer a single source of truth and explicit class names:- static override attributes() { - return { - ...super.attributes(), + static override attributes() { + return { + ...BaseModel.attributes(),Then inside
setup()
simply callCohortModel.attributes()
instead of rebuilding the object.
52-55
: Use explicit class name for clarity
this.NAME
inside a static method is valid but fails thenoThisInStatic
lint rule. Swap to the class identifier:- tableName: this.NAME, + tableName: CohortModel.NAME,
96-101
: Same lint issue applies here – replacethis.NAME
withCohortAssignmentModel.NAME
(andsuper
withBaseModelNoId
) to silence the warning.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (4)
packages/api/src/models/db.ts
(3 hunks)packages/api/src/models/medical/cohort.ts
(1 hunks)packages/api/src/sequelize/migrations/2025-06-17_00_create-cohort-tables.ts
(1 hunks)packages/core/src/domain/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/models/db.ts
packages/api/src/sequelize/migrations/2025-06-17_00_create-cohort-tables.ts
packages/core/src/domain/cohort.ts
packages/api/src/models/medical/cohort.ts
🧬 Code Graph Analysis (3)
packages/api/src/models/db.ts (1)
packages/api/src/models/medical/cohort.ts (2)
CohortModel
(5-57)CohortAssignmentModel
(59-109)
packages/core/src/domain/cohort.ts (1)
packages/shared/src/domain/base-domain.ts (3)
BaseDomainCreate
(1-3)BaseDomain
(10-12)BaseDomainNoId
(5-8)
packages/api/src/models/medical/cohort.ts (2)
packages/core/src/domain/cohort.ts (3)
Cohort
(14-14)MonitoringSettings
(3-5)CohortAssignment
(25-25)packages/api/src/models/_default.ts (1)
ModelSetup
(17-17)
🪛 Biome (1.9.4)
packages/api/src/models/medical/cohort.ts
[error] 15-15: Using super in a static context can be confusing.
super refers to a parent class.
Unsafe fix: Use the class name instead.
(lint/complexity/noThisInStatic)
[error] 98-98: Using super in a static context can be confusing.
super refers to a parent class.
(lint/complexity/noThisInStatic)
[error] 99-99: Using this in a static context can be confusing.
this refers to the class.
Unsafe fix: Use the class name instead.
(lint/complexity/noThisInStatic)
⏰ Context from checks skipped due to timeout of 90000ms (3)
- GitHub Check: check-pr / lint-build-test
- GitHub Check: check-pr / lint-build-test
- GitHub Check: Analyze (javascript)
🔇 Additional comments (4)
packages/core/src/domain/cohort.ts (1)
1-26
: Domain layer looks solidNew cohort-related domain types are well-structured, immutable and follow the existing
BaseDomain*
hierarchy. No correctness issues spotted.packages/api/src/models/db.ts (2)
32-33
: Model imports wired correctly
CohortModel
andCohortAssignmentModel
are imported next to their peers – good job keeping the registry centralised.
75-77
: Verify FK source model initialisation order
CohortAssignmentModel
references bothpatient
andcohort
tables.
PatientModel.setup
andCohortModel.setup
already appear earlier in the array, so Sequelize should resolve all FKs, but please run a quick migration + sync locally just in case.packages/api/src/models/medical/cohort.ts (1)
70-83
: ConfirmpatientId
datatype alignmentThe model sets
patientId
asUUID
; ensure thepatient
table column is alsouuid
(and update the migration as noted). A mismatch will surface only at runtime.
packages/api/src/sequelize/migrations/2025-06-17_00_create-cohort-tables.ts
Outdated
Show resolved
Hide resolved
packages/api/src/sequelize/migrations/2025-06-17_00_create-cohort-tables.ts
Outdated
Show resolved
Hide resolved
packages/api/src/sequelize/migrations/2025-06-17_00_create-cohort-tables.ts
Outdated
Show resolved
Hide resolved
packages/api/src/sequelize/migrations/2025-06-17_00_create-cohort-tables.ts
Outdated
Show resolved
Hide resolved
packages/api/src/sequelize/migrations/2025-06-17_00_create-cohort-tables.ts
Outdated
Show resolved
Hide resolved
packages/api/src/sequelize/migrations/2025-06-17_00_create-cohort-tables.ts
Outdated
Show resolved
Hide resolved
packages/api/src/sequelize/migrations/2025-06-17_00_create-cohort-tables.ts
Outdated
Show resolved
Hide resolved
packages/api/src/sequelize/migrations/2025-06-17_00_create-cohort-tables.ts
Outdated
Show resolved
Hide resolved
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: 3
♻️ Duplicate comments (1)
packages/api/src/sequelize/migrations/2025-06-17_00_create-cohort.ts (1)
18-22
: Add NOT-NULL in model or relax DB –cx_id
mismatchDB enforces
NOT NULL
oncx_id
. CurrentCohortModel.setup()
allows null values.
Once the model fix incohort.ts
is applied (see earlier comment) this will be aligned; otherwise inserts will fail.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (5)
packages/api/src/models/db.ts
(3 hunks)packages/api/src/models/medical/cohort.ts
(1 hunks)packages/api/src/sequelize/migrations/2025-06-17_00_create-cohort.ts
(1 hunks)packages/api/src/sequelize/migrations/2025-06-17_01_create-patient-cohort.ts
(1 hunks)packages/core/src/domain/cohort.ts
(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
- packages/api/src/models/db.ts
- packages/core/src/domain/cohort.ts
🧰 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
- class 8000 es, 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/sequelize/migrations/2025-06-17_00_create-cohort.ts
packages/api/src/sequelize/migrations/2025-06-17_01_create-patient-cohort.ts
packages/api/src/models/medical/cohort.ts
🪛 Biome (1.9.4)
packages/api/src/models/medical/cohort.ts
[error] 14-14: Using super in a static context can be confusing.
super refers to a parent class.
Unsafe fix: Use the class name instead.
(lint/complexity/noThisInStatic)
[error] 88-88: Using super in a static context can be confusing.
super refers to a parent class.
Unsafe fix: Use the class name instead.
(lint/complexity/noThisInStatic)
[error] 89-89: Using this in a static context can be confusing.
this refers to the class.
Unsafe fix: Use the class name instead.
(lint/complexity/noThisInStatic)
⏰ Context from checks skipped due to timeout of 90000ms (3)
- GitHub Check: check-pr / lint-build-test
- GitHub Check: check-pr / lint-build-test
- GitHub Check: Analyze (javascript)
🔇 Additional comments (3)
packages/api/src/models/medical/cohort.ts (1)
70-80
: Model expectsON DELETE CASCADE
; migration does not add itBoth
patientId
&cohortId
specifyonDelete: "CASCADE"
, but the join-table migration omitsonDelete
.
Either drop the option here or extend the migration withonDelete: "CASCADE"
for both FKs to match expectations.packages/api/src/sequelize/migrations/2025-06-17_01_create-patient-cohort.ts (2)
39-45
: Composite PK already created; settingprimaryKey: true
on each column in model is fineGood job naming the constraint explicitly; this avoids random names in different environments.
16-32
: Datatype / FK options inconsistent with model
patient_id
is declaredSTRING
, model usesUUID
.- No
onDelete: "CASCADE"
is provided, yet the model expects it.Please update to keep ORM ↔ DB in sync:
- patient_id: { - type: DataTypes.STRING, + patient_id: { + type: DataTypes.UUID, allowNull: false, references: { model: patientTableName, key: "id", }, + onDelete: "CASCADE", },…and apply the same to
cohort_id
.⛔ Skipped due to learnings
Learnt from: RamilGaripov PR: metriport/metriport#3962 File: packages/api/src/sequelize/migrations/2025-06-17_00_create-cohort-tables.ts:50-56 Timestamp: 2025-06-17T20:03:18.904Z Learning: In the Metriport codebase, the patient table ID is defined as DataTypes.STRING in the database schema, not UUID. Foreign key references to patient.id should use DataTypes.STRING to maintain consistency.
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: 1
🧹 Nitpick comments (1)
packages/api/src/sequelize/migrations/2025-06-17_01_create-patient-cohort.ts (1)
11-13
: Remove dead code or put it to use
patientCohortIndex
is commented-out and never referenced. Either delete it or wire it up; leaving commented constants behind clutters migrations and invites drift.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
packages/api/src/sequelize/migrations/2025-06-17_01_create-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/sequelize/migrations/2025-06-17_01_create-patient-cohort.ts
⏰ Context from checks skipped due to timeout of 90000ms (3)
- GitHub Check: check-pr / lint-build-test
- GitHub Check: check-pr / lint-build-test
- GitHub Check: Analyze (javascript)
🔇 Additional comments (1)
packages/api/src/sequelize/migrations/2025-06-17_01_create-patient-cohort.ts (1)
25-44
: ```shell
#!/bin/bashList migration files to identify patient table creation migration
ls packages/api/src/sequelize/migrations
</details> </blockquote></details> </details> <!-- This is an auto-generated comment by CodeRabbit for review status -->
packages/api/src/sequelize/migrations/2025-06-17_01_create-patient-cohort.ts
Outdated
Show resolved
Hide resolved
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: 1
♻️ Duplicate comments (3)
packages/api/src/models/medical/cohort.ts (3)
15-18
:cxId
is missing thefield: "cx_id"
mapping (repeat issue)Without the explicit mapping, Sequelize looks for a
cxId
column that doesn’t exist (migration createscx_id
).cxId: { type: DataTypes.UUID, allowNull: false, + field: "cx_id", },
29-43
:setup()
re-declares attributes and drifts fromattributes()
(repeat issue)The block duplicates the attribute bag, omits
allowNull: false
oncxId
, and will inevitably diverge from the canonicalattributes()
definition.- CohortModel.init( - { - ...BaseModel.attributes(), - cxId: { - type: DataTypes.UUID, - }, - name: { - type: DataTypes.STRING, - allowNull: false, - }, - monitoring: { - type: DataTypes.JSONB, - }, - }, + CohortModel.init( + CohortModel.attributes(), { ...BaseModel.modelOptions(sequelize), - tableName: this.NAME, + tableName: CohortModel.NAME, } );
60-70
:patientId
datatype diverges from migration – runtime cast errors aheadMigration defines
patient_id
asSTRING
; the model setsUUID
.
Align the types and re-enable cascading delete to keep behaviour consistent with the migration.- patientId: { - type: DataTypes.UUID, + patientId: { + type: DataTypes.STRING, allowNull: false, field: "patient_id", primaryKey: true, references: { model: "patient", key: "id", }, - // onDelete: "CASCADE", + onDelete: "CASCADE", },
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (3)
packages/api/src/models/medical/cohort.ts
(1 hunks)packages/api/src/sequelize/migrations/2025-06-17_01_create-patient-cohort.ts
(1 hunks)packages/core/src/domain/cohort.ts
(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
- packages/api/src/sequelize/migrations/2025-06-17_01_create-patient-cohort.ts
- packages/core/src/domain/cohort.ts
🧰 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/models/medical/cohort.ts
🧠 Learnings (1)
packages/api/src/models/m A93C edical/cohort.ts (1)
Learnt from: RamilGaripov
PR: metriport/metriport#3962
File: packages/api/src/sequelize/migrations/2025-06-17_00_create-cohort-tables.ts:50-56
Timestamp: 2025-06-17T20:03:18.904Z
Learning: In the Metriport codebase, the patient table ID is defined as DataTypes.STRING in the database schema, not UUID. Foreign key references to patient.id should use DataTypes.STRING to maintain consistency.
🪛 Biome (1.9.4)
packages/api/src/models/medical/cohort.ts
[error] 14-14: Using super in a static context can be confusing.
super refers to a parent class.
Unsafe fix: Use the class name instead.
(lint/complexity/noThisInStatic)
[error] 60-60: Using super in a static context can be confusing.
super refers to a parent class.
Unsafe fix: Use the class name instead.
(lint/complexity/noThisInStatic)
[error] 89-89: Using super in a static context can be confusing.
super refers to a parent class.
Unsafe fix: Use the class name instead.
(lint/complexity/noThisInStatic)
[error] 90-90: Using this in a static context can be confusing.
this refers to the class.
Unsafe fix: Use the class name instead.
(lint/complexity/noThisInStatic)
⏰ Context from checks skipped due to timeout of 90000ms (3)
- GitHub Check: check-pr / lint-build-test
- GitHub Check: check-pr / lint-build-test
- GitHub Check: Analyze (javascript)
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: 0
♻️ Duplicate comments (3)
packages/api/src/models/medical/cohort.ts (3)
61-70
:patientId
datatype should beSTRING
, notUUID
See migration2025-06-17_01_create-patient-cohort.ts
and earlier learning thatpatient.id
isSTRING
. Misaligned types will throw cast errors on insert / join.
71-80
: UncommentonDelete: "CASCADE"
oncohortId
for symmetric cleanup
Keeps join table tidy when a cohort is deleted and mirrors the (likely) cascade onpatientId
.
15-18
: Add explicitfield: "cx_id"
mapping to avoid runtime column mismatchThe migration creates the column as
cx_id
, but the model currently leaves the default (cxId
). Without an explicitfield
mapping, Sequelize will generateSELECT "cxId"
… and fail at runtime.cxId: { type: DataTypes.UUID, allowNull: false, + field: "cx_id", },
🧹 Nitpick comments (1)
packages/api/src/models/medical/cohort.ts (1)
87-88
: Minor: use the class name instead ofthis
in static contextStatic code is clearer and avoids Biome warnings:
- tableName: this.NAME, + tableName: PatientCohortModel.NAME,
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
packages/api/src/models/medical/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/models/medical/cohort.ts
🧠 Learnings (1)
packages/api/src/models/medical/cohort.ts (1)
Learnt from: RamilGaripov
PR: metriport/metriport#3962
File: packages/api/src/sequelize/migrations/2025-06-17_00_create-cohort-tables.ts:50-56
Timestamp: 2025-06-17T20:03:18.904Z
Learning: In the Metriport codebase, the patient table ID is defined as DataTypes.STRING in the database schema, not UUID. Foreign key references to patient.id should use DataTypes.STRING to maintain consistency.
🪛 Biome (1.9.4)
packages/api/src/models/medical/cohort.ts
[error] 14-14: Using super in a static context can be confusing.
super refers to a parent class.
Unsafe fix: Use the class name instead.
(lint/complexity/noThisInStatic)
[error] 60-60: Using super in a static context can be confusing.
super refers to a parent class.
Unsafe fix: Use the class name instead.
(lint/complexity/noThisInStatic)
[error] 87-87: Using super in a static context can be confusing.
super refers to a parent class.
Unsafe fix: Use the class name instead.
(lint/complexity/noThisInStatic)
[error] 88-88: Using this in a static context can be confusing.
this refers to the class.
Unsafe fix: Use the class name instead.
(lint/complexity/noThisInStatic)
⏰ Context from checks skipped due to timeout of 90000ms (3)
- GitHub Check: check-pr / lint-build-test
- GitHub Check: check-pr / lint-build-test
- GitHub Check: Analyze (javascript)
🔇 Additional comments (1)
packages/api/src/models/medical/cohort.ts (1)
29-43
: Stop duplicating attribute definitions; reuseCohortModel.attributes()
setup()
re-declares the attributes, silently droppingallowNull: false
oncxId
.
This creates drift between the model and DB schema and violates DRY.- CohortModel.init( - { - ...BaseModel.attributes(), - cxId: { - type: DataTypes.UUID, - }, - name: { - type: DataTypes.STRING, - allowNull: false, - }, - monitoring: { - type: DataTypes.JSONB, - }, - }, + CohortModel.init( + CohortModel.attributes(), { - ...BaseModel.modelOptions(sequelize), - tableName: this.NAME, + ...BaseModel.modelOptions(sequelize), + tableName: CohortModel.NAME, } );This keeps a single source of truth and preserves the NOT-NULL constraint.
[ suggest_essential_refactor ]
packages/api/src/sequelize/migrations/2025-06-17_01_create-patient-cohort.ts
Outdated
Show resolved
Hide resolved
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: 2
🧹 Nitpick comments (2)
packages/api/src/models/medical/patient-cohort.ts (2)
6-6
: RenameNAME
to comply with repo naming conventionsCoding-guidelines specify that constants/variables use
camelCase
; upper-snake is reserved neither for constants nor for classes.
Consider renaming totableName
(or similar) to stay consistent with the rest of the codebase.- static NAME = "patient_cohort"; + static tableName = "patient_cohort";
11-13
: Exposeassociate()
to definebelongsTo
relationsWithout associations, eager-loading or cascade deletes will not work.
Consider exporting anassociate(models)
method that adds:PatientCohortModel.belongsTo(models.PatientModel, { foreignKey: "patientId" }); PatientCohortModel.belongsTo(models.CohortModel, { foreignKey: "cohortId" });This keeps the relationship explicit and discoverable.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (4)
packages/api/src/models/db.ts
(3 hunks)packages/api/src/models/medical/cohort.ts
(1 hunks)packages/api/src/models/medical/patient-cohort.ts
(1 hunks)packages/api/src/sequelize/migrations/2025-06-17_01_create-patient-cohort.ts
(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
- packages/api/src/models/medical/cohort.ts
- packages/api/src/models/db.ts
- packages/api/src/sequelize/migrations/2025-06-17_01_create-patient-cohort.ts
🧰 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/models/medical/patient-cohort.ts
⏰ Context from checks skipped due to timeout of 90000ms (3)
- GitHub Check: check-pr / lint-build-test
- GitHub Check: check-pr / lint-build-test
- GitHub Check: Analyze (javascript)
packages/api/src/sequelize/migrations/2025-06-17_00_create-cohort.ts
Outdated
Show resolved
Hide resolved
Part of ENG-420 Signed-off-by: Ramil Garipov <ramil@metriport.com>
Issues:
Dependencies
Description
cohort
andpatient_cohort
Testing
cohort
table is goodpatient_cohort
table is goodcohort
table is goodpatient_cohort
table is goodRelease Plan
Summary by CodeRabbit
Summary by CodeRabbit
New Features
Database Changes