Skip to content
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

chore: bump mongoose from 8.0.0 to 8.8.3 in /backend in the npm_and_yarn group across 1 directory #210

Merged
merged 34 commits into from
Jan 16, 2025

Conversation

dependabot[bot]
Copy link
Contributor

@dependabot dependabot bot commented on behalf of github Dec 3, 2024

Bumps the npm_and_yarn group with 1 update in the /backend directory: mongoose.

Updates mongoose from 8.0.0 to 8.8.3

Release notes

Sourced from mongoose's releases.

8.8.3 / 2024-11-26

  • fix: disallow using $where in match
  • perf: cache results from getAllSubdocs() on saveOptions, only loop through known subdoc properties #15055 #15029
  • fix(model+query): support overwriteDiscriminatorKey for bulkWrite updateOne and updateMany, allow inferring discriminator key from update #15046 #15040

8.8.2 / 2024-11-18

  • fix(model): handle array filters when casting bulkWrite #15036 #14978
  • fix(model): make diffIndexes() avoid trying to drop default timeseries collection index #15035 #14984
  • fix: save execution stack in query as string #15039 durran
  • types(cursor): correct asyncIterator and asyncDispose for TypeScript with lib: 'esnext' #15038
  • docs(migrating_to_8): add note about removing findByIdAndRemove #15024 dragontaek-lee

8.8.1 / 2024-11-08

  • perf: make a few micro-optimizations to help speed up findOne() #15022 #14906
  • fix: apply embedded discriminators to subdoc schemas before compiling top level model so middleware applies correctly #15001 #14961
  • fix(query): add overwriteImmutable option to allow updating immutable properties without disabling strict mode #15000 #8619

8.8.0 / 2024-10-31

  • feat: upgrade mongodb -> ~6.10 #14991 #14877
  • feat(query): add schemaLevelProjections option to query to disable schema-level select: false #14986 #11474
  • feat: allow defining virtuals on arrays, not just array elements #14955 #2326
  • feat(model): add applyTimestamps() function to apply all schema timestamps, including subdocuments, to a given POJO #14943 #14698
  • feat(model): add hideIndexes option to syncIndexes() and cleanIndexes() #14987 #14868
  • fix(query): make sanitizeFilter disable implicit $in #14985 #14657
  • fix(model): avoid unhandled error if createIndex() throws a sync error #14995
  • fix(model): avoid throwing TypeError if bulkSave()'s bulkWrite() fails with a non-BulkWriteError #14993
  • types: added toJSON:flattenObjectIds effect #14989
  • types: add __v to lean() result type and ModifyResult #14990 #12959
  • types: use globalThis instead of global for NativeDate #14992 #14988
  • docs(change-streams): fix markdown syntax highlighting for script output example #14994

8.7.3 / 2024-10-25

  • fix(cursor): close underlying query cursor when calling destroy() #14982 #14966
  • types: add JSONSerialized helper that can convert HydratedDocument to JSON output type #14981 #14451
  • types(model): convert InsertManyResult to interface and remove unnecessary insertedIds override #14977
  • types(connection): add missing sanitizeFilter option #14975
  • types: improve goto definition for inferred schema definitions #14968 forivall
  • docs(migration-guide-v7): correct link to the section "Id Setter" #14973 rb-ntnx

8.7.2 / 2024-10-17

  • fix(document): recursively clear modified subpaths when setting deeply nested subdoc to null #14963 #14952
  • fix(populate): handle array of ids with parent refPath #14965
  • types: make Buffers into mongodb.Binary in lean result type to match runtime behavior #14967
  • types: correct schema type inference when using nested typeKey like type: { type: String } #14956 #14950

... (truncated)

Changelog

Sourced from mongoose's changelog.

8.8.3 / 2024-11-26

  • fix: disallow using $where in match
  • perf: cache results from getAllSubdocs() on saveOptions, only loop through known subdoc properties #15055 #15029
  • fix(model+query): support overwriteDiscriminatorKey for bulkWrite updateOne and updateMany, allow inferring discriminator key from update #15046 #15040

8.8.2 / 2024-11-18

  • fix(model): handle array filters when casting bulkWrite #15036 #14978
  • fix(model): make diffIndexes() avoid trying to drop default timeseries collection index #15035 #14984
  • fix: save execution stack in query as string #15039 durran
  • types(cursor): correct asyncIterator and asyncDispose for TypeScript with lib: 'esnext' #15038
  • docs(migrating_to_8): add note about removing findByIdAndRemove #15024 dragontaek-lee

8.8.1 / 2024-11-08

  • perf: make a few micro-optimizations to help speed up findOne() #15022 #14906
  • fix: apply embedded discriminators to subdoc schemas before compiling top level model so middleware applies correctly #15001 #14961
  • fix(query): add overwriteImmutable option to allow updating immutable properties without disabling strict mode #15000 #8619

8.8.0 / 2024-10-31

  • feat: upgrade mongodb -> ~6.10 #14991 #14877
  • feat(query): add schemaLevelProjections option to query to disable schema-level select: false #14986 #11474
  • feat: allow defining virtuals on arrays, not just array elements #14955 #2326
  • feat(model): add applyTimestamps() function to apply all schema timestamps, including subdocuments, to a given POJO #14943 #14698
  • feat(model): add hideIndexes option to syncIndexes() and cleanIndexes() #14987 #14868
  • fix(query): make sanitizeFilter disable implicit $in #14985 #14657
  • fix(model): avoid unhandled error if createIndex() throws a sync error #14995
  • fix(model): avoid throwing TypeError if bulkSave()'s bulkWrite() fails with a non-BulkWriteError #14993
  • types: added toJSON:flattenObjectIds effect #14989
  • types: add __v to lean() result type and ModifyResult #14990 #12959
  • types: use globalThis instead of global for NativeDate #14992 #14988
  • docs(change-streams): fix markdown syntax highlighting for script output example #14994

8.7.3 / 2024-10-25

  • fix(cursor): close underlying query cursor when calling destroy() #14982 #14966
  • types: add JSONSerialized helper that can convert HydratedDocument to JSON output type #14981 #14451
  • types(model): convert InsertManyResult to interface and remove unnecessary insertedIds override #14977
  • types(connection): add missing sanitizeFilter option #14975
  • types: improve goto definition for inferred schema definitions #14968 forivall
  • docs(migration-guide-v7): correct link to the section "Id Setter" #14973 rb-ntnx

8.7.2 / 2024-10-17

  • fix(document): recursively clear modified subpaths when setting deeply nested subdoc to null #14963 #14952
  • fix(populate): handle array of ids with parent refPath #14965
  • types: make Buffers into mongodb.Binary in lean result type to match runtime behavior #14967

... (truncated)

Commits
  • bb98dcf chore: release 8.8.3
  • 862d1a5 Merge pull request #15055 from Automattic/vkarpov15/gh-15029
  • 8f774f0 address code review comments
  • 768d460 Merge branch 'vkarpov15/sift-where'
  • c9e86bf fix: disallow using $where in match
  • b76ca9d Merge pull request #15046 from Automattic/vkarpov15/gh-15040
  • 7639fc6 perf: cache results from getAllSubdocs() on saveOptions, only loop through kn...
  • 83db613 fix(model+query): support overwriteDiscriminatorKey for bulkWrite updateOne a...
  • b34aba6 chore: release 8.8.2
  • f450083 docs(migrating_to_8): add note about removing findByIdAndRemove
  • Additional commits viewable in compare view

Dependabot compatibility score

You can trigger a rebase of this PR by commenting @dependabot rebase.


Dependabot commands and options

You can trigger Dependabot actions by commenting on this PR:

  • @dependabot rebase will rebase this PR
  • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
  • @dependabot merge will merge this PR after your CI passes on it
  • @dependabot squash and merge will squash and merge this PR after your CI passes on it
  • @dependabot cancel merge will cancel a previously requested merge and block automerging
  • @dependabot reopen will reopen this PR if it is closed
  • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
  • @dependabot show <dependency name> ignore conditions will show all of the ignore conditions of the specified dependency
  • @dependabot ignore <dependency name> major version will close this group update PR and stop Dependabot creating any more for the specific dependency's major version (unless you unignore this specific dependency's major version or upgrade to it yourself)
  • @dependabot ignore <dependency name> minor version will close this group update PR and stop Dependabot creating any more for the specific dependency's minor version (unless you unignore this specific dependency's minor version or upgrade to it yourself)
  • @dependabot ignore <dependency name> will close this group update PR and stop Dependabot creating any more for the specific dependency (unless you unignore this specific dependency or upgrade to it yourself)
  • @dependabot unignore <dependency name> will remove all of the ignore conditions of the specified dependency
  • @dependabot unignore <dependency name> <ignore condition> will remove the ignore condition of the specified dependency and ignore conditions
    You can disable automated security fix PRs for this repo from the Security Alerts page.

Note
Automatic rebases have been disabled on this pull request as it has been open for over 30 days.

hiyaryan and others added 24 commits July 8, 2024 19:12
Adds the tsconfig.json file.
Moves and renames index.js to src/index.ts.
Updates package.json dev script to use tsx with hot reload.
Adds build, start, and start:prod scripts to package.json.
Adds pm2, tsx, and typescript to dev dependencies.
Prior to TS, nodemon was used to serve the backend with hot reloads in development. It has been replaced with tsx and required the following changes.

 - The backend Dockerfile nodemon global installation and command to run it in legacy mode have been replaced with a single command, npm run dev.

 - The index.js volume in the backend service of Docker compose has been renamed to index.ts.
* Initial testing setup for TypeScript files using mongodb-memory-server.

- Updated `package.json`:
  - Changed the development script to use `tsc --watch` instead of `tsx watch`.
  - Added development dependencies: `@babel/preset-typescript`, `@types/express`, `@types/jest`, `mongodb-memory-server`, and `ts-node`.

- Modified `db.js`:
  - Replaced default import with named import for `mongoose`.
  - Exported `mongoose` as `db` to ensure consistent type definitions.

- Updated `index.ts`:
  - Added comments and structured the server startup logic.
  - Implemented a graceful shutdown mechanism using `process.on` to listen for SIGINT and SIGTERM signals.

- Created `index.test.ts`:
  - Added initial Jest tests to verify server startup in non-production mode.
  - Mocked console.log and added assertions to check server behavior.

- Modified Jest setup and teardown scripts:
  - Simplified the setup by combining imports and logging the seeding process.
  - Added a console log statement in the teardown script for clarity.

* Enable type checking for tests.

Adds tsconfig.test.json with options set for type checking.
Fixes TS errors in index.test.ts after applying type checking.
Removes unnecessary assignment of NODE_ENV to test in test script.
Updates test script to use tsc for type checking before transpilation.

* Remove extra whitespace.

* Improve readability and correct mongoose usage.

Refactors short-circuiting to single line conditionals.
Imports mongoose from mongoose instead of exporting from db.js.
Adds documentation to seed.js.

* Lint and reformat code.

Adds new rules to .eslintrc.cjs.
Adds new eslint packages to enforce common rule sets.
Lints and reformats code based on updated rules.
Updates lint script to use npx with --fix flag.
Enhances the ESLint configuration to support TypeScript by adding the @typescript-eslint/parser and @typescript-eslint/eslint-plugin. The ESLint configuration now extends the recommended rules from @typescript-eslint, and includes a rule to catch unused variables in TypeScript files.
* Migrate backend/routes to TS (#139)

Migrated routes modules to TS along with tests. Added empty file for
access.ts

* Unit test access.ts (#139)

* Install types for unit testing (#139)

* Fix typo in compose.yaml

* Remove comment in access.test.ts (#139)

* Rewrite access.ts test with supertest (#139)

Changed unit tests for access.ts to use supertest and check for path
existence, i.e. non-404 status code. Previous unit tests didn't
work well with typescript due to mismatch between express router
type definition and actual object.

* Fix unit tests after merge (#139)

Reinstalled @types/supertest and fixed file extension in test imports.

* Resolve issue with module paths in jest (#139)

Jest seems to have an issue resolving paths for typescript modules
getting imported with a .js path after transpilation. This seems
to be a common issue for many users, and a common way of getting
around it is by setting the moduleNameMapper key in the jest config
to drop the file extension for .js imports.

* Update docker volume paths (#139)

* Auto fix package-lock formatting (#139)

* Run linter (#139)

* Fix lint error.

Imports should be alphabetical.
Added white space between imports and the jest.mock call for better readability.

---------

Co-authored-by: Ryan James Meneses <github@ryanmeneses.com>
* Migrate utils to TS (#139)

This commit breaks all unit tests due to an issue with the jest
gloablsetup and globalteardown scripts. The module imports in them seem
to happen outside of code transformation, so the ExpressError file
can't be found.

* Unit test catchAsync (#139)

* Unit test ExpressError (#139)

* Unit test utils/aes.ts (#139)

* Run linter for utils migration (#139)

* Remove seed.js from Jest global scripts (#139)

Using seed.js in jest globalSetup and globalTeardown scripts was causing
issues with imports because they seem to run before code transformation.
This means that any files imported in seed.js that have .ts extension
will break the script when running unit tests.

This commit removes seeding the db from the globalSetup and
globalTeardown scripts, and leaves setting up the memory mongodb
in them. It also rewrites index.test.ts to seed the db before
running tests, as an example for how tests that use the db should
set up and clean up.

* Let Express set port for test environment. (#160)

* Use arguments to run tests on separate port with yargs.

Removes MEMORY environment variable.
Uses yargs to pass arguments to the application on launch.
 - Adds yargs to dependecies list.
 - Passes port=3001 to test instances of the app.
Resolves lint error in index.test.ts regarding imports out of order.

* Remove yargs dependency.

* Refactor server startup to dynamically assign port.

Adds new getPort and isPortInUse utility functions to dynamically assign a port in a test environment.
Updates index.ts to use the getPort function in a new async startServer function that wraps the pre-existing code.
Updates the index.ts test from a hardcoded port to matching the console log for a port between 1 to 5 digits.

* Add getPort unit tests.

* Let express assign port in test env (#139)

Rewrite getPort to allow express to assign open port in test environment
by returning 0.

* Remove getPort.

Removed get port and moved port assignment into the startServer function.
Removed the Server import and assigned server to a returned instance of the Server obj
ect created in startServer.
Throw an error if the server is listening on a non-IP socket.
Update the condition block for NODE_ENV === 'production' to reflect changes made in no
n-production environments.
Reorganized file: moved all function definitions to the bottom of the file.
Updated server listening messages for more clarity.

---------

Co-authored-by: David Lu <ludavid33@gmail.com>

* Resolve linter errors.

Removes unused import from seed.js.
Reorders imports in aes.ts.
Updates Promise return type from `any` to `unknown` in catchAsync.ts.
 - This ensures that the type of the resolved value is checked before use, providing better type safety.

---------

Co-authored-by: Ryan James Meneses <58452495+hiyaryan@users.noreply.github.com>
Co-authored-by: Ryan James Meneses <github@ryanmeneses.com>
* Migrate store.js to TS with unit tests.

Renames store.js to store.ts.
Updates function name connectStore to createStore which more accurately describes its functionality.
Changes createStore from default export to named export to make imports more explicit.
Imports Store from express-session to use its type.
Adds conditional checks for REDIS_HOST and REDIS_PORT env variables.
Updates app.js import to use new createStore name.
Adds unit tests.

* Migrate app.js to TS with one unit test and bug fix.

Adds required types packages to devDependencies.
Adds id to User interface added to Express from Passport in order to use id on an Express.User type.
Tests the error handlers.
- Ensures ExpressErrors are being passed to error handler.
- Fixes a bug where the 404 catch-all was not passing the error to the error handler because the error handler was missing the next parameter.

* Remove duplicate test.

Deleted test, `should return a Store object when store is "redis"`, due to similarity to test, `should create and return a RedisStore when store is "redis"`.
* refactor: Migrate models/entry to TS

* fix: Pass in options to joi validate

When changing entry models to TS, I did not realize that we were
passing in options to validate. This broke the validateEntryAnalysis
function. This commit passes along the options to the joi.validate call.

* refactor!: Rewrite entry models for methods

Rewrote models to incorporate methods and static methods explicitly.

* refactor!: Migrate Config model to TS

* refactor!: Migrate Journal model to TS

* refactor!: Start of migrating User to ts

This commit still has typescript errors in it.

* refactor!: Migrated User model to TS

This commit installs @types/passport-local-mongoose, and required
some finessing with the instance and static methods. These changes
are based on the test case in the @types/passport-local-mongoose
github repo.

* refactor: run linter on models

* refactor: move User methods to UserType

The passport-local-mongoose types don't play well with how Mongoose
suggests you implement instance and static methods with Typescript.
I wasn't able to get the model to see the instance methods when
using the mongoose types that passport-local-mongoose overwrote, so
I did what they did and put all the instance method signatures into
the schema interface.

* test: add test case descriptions for User model

* test: add unit tests for Entry validation

* style: fix linting errors

* test: update test db endpoint

memory mongodb assigns URI dynamically, so we need to read from an
environment variable rather than hardcode localhost for the test env

* test: add models/user.ts unit tests and apply necessary fixes (#175)

* test: add models/user.ts unit tests and apply necessary fixes

- Adds unit tests with 100% line coverage for models/user.ts.
- Defines checkEmail as a static method in the UserModel interface, ensuring it is treated as a class-level method.
- Updates the return type of checkEmail to a Promise<boolean> to reflect its usage.

* Apply suggestions from code review.

- Use toBeDefined() or toBeTruthy() instead of not.toBeNull() because undefined !== null and if validation succeeds, error is undefined, otherwise it is set.
- Replace %s with $desc in the test description to prevent jest from printing the entire object to the console.
- Specify the exact number of validation errors expected by replacing expect(error?.details.length).toBeGreaterThan(1); with expect(error?.details.length).toBe(3);.
- Replace baseJoi() with registrationJoi() because baseJoi() doesn't have properties for fname and lname.

Co-authored-by: David Lu <ludavid33@gmail.com>

* test: update unit tests based on code review feedback

- Restore original environment variables before each `Email sending methods` unit test.
- Remove unused parameter `desc`.
- Remove unnecessary `async`'s and `await`'s.
- Fix `sends an email with nodemailer` test.
  - Set environment variables to test values used in `User.sendMail` method.
  - Update unit test name to `sends an email with User method sendMail`.
- Remove duplicate `null` type from `Email sending methods` test suite.

---------

Co-authored-by: David Lu <ludavid33@gmail.com>

* test: add EntryAnalysis model unit tests and address reviews (#170)

* test: create unit tests for EntryAnalysis model

db.ts needed to change endpoint for test environment because it gets
dynamically assigned by mongo memory db

* refactor: break up getAnalysisContent method

* test: clean up entryAnalysis unit test

Clean up case that 'gets analysis content from an entry'

* lint: fix linter errors

* refactor: rename method in entryAnalysis

* test: unit tests for removeLegacyApiKey

Code coverage for entryAnalysis now over 80%

* test: add Config model unit tests

* refactor: remove unknown from joi method signature

* test: add test file for models/config

* fix: update config model to match Joi validation

Set model to be required field in Mongoose schema.

* test: add unit tests for Config model

* lint: fix linter errors

* lint: remove desc from tests

* test: add test for pre save middleware

- Ensure updated_at is updated before the document is saved.

---------

Co-authored-by: Ryan James Meneses <github@ryanmeneses.com>

* test: add Journal model unit tests (#178)

* test: add unit test file for journal model

* test: add journal model unit tests

* lint: fix linter errors

* lint: prettier auto-format for journal

* test: add EntryConversation model unit tests, bug fixes, and explicit types (#171)

* test: add file for entryConversation unit tests

* test: unit test EntryConversation joi validation

* test: test for getChatContent in EntryConversation

* lint: fix linter errors for entryConversation

* refactor: extract methods from getChatContent

* test: add entryConversation unit tests

Line coverage now 90.9%

* fix: correct and define types, CdGpt bug fix, and additional coverage.

- `CdGpt` fixes and type definitions
  - Fix type in `CdGpt` of `entryAnalysis` to `EntryAnalysisType`.
  - Make `CdGpt` properties with defaults optional fixing errors on new `CdGpt` instances.

- `EntryAnalysis` type definitions and error handling
  - Define type on `EntryAnalysisType` as `EntryType` from `Entry` model.
  - Check that `OPENAI_API_KEY` is defined in env vars in `EntryAnalysis.getAnalysisContent`.

- `EntryConversation` type definitions and additional coverage
  - Remove all ESLint ignore comments.
  - Remove all `any`s and explicitly define types from `CdGpt` and `EntryAnalysis`.
  - Add additional coverage for error cases in private function `getAnalysisCompletion` called by `EntryConversation.getChatContent`.

* fix: address code review

- Remove `Entry` and `EntryAnalysis` interfaces from `CdGpt` and use `EntryAnalysisType` from `entryAnalysis` model.
- Remove unused eslint enable comments `no-explicit-any`.
- Remove unnecessary arguments from new `CdGpt` instance in `getAnalysisCompletion` using default values.
- Reset env vars in unit tests.

* fix: add required email field to mockUser

- Fix failing tests due to failing validation of missing required `email` field for mocked `User`.

* refactor: fix populate type in seedChatMessages

Previous commit changed EntryAnalysis.entry type to EntryType rather
than ObjectId to handle populated documents, which breaks the mongoose
schema for EntryAnalysis. The suggested way to do this is to use
generics with the populate method
(https://mongoosejs.com/docs/typescript/populate.html).

This commit implements this by moving the populate call from
entryConversation to CdGpt.seedChatMessages, and refactors the unit
tests for affected classes.

* refactor: add comment about analysisCompletion

See comment for all details

---------

Co-authored-by: Ryan James Meneses <github@ryanmeneses.com>

* fix: entryConversation unit tests and config

Config was changed to make model.chat and model.analysis optional fields.
This broke the unit tests in entryConversation because the
getChatContent method relies on Config, and expects model.analysis
to be a string. By making that property optional, it could be undefined
rather than always a string even on an empty field.

This commit checks for an undefined model.analysis property in
entryConversation.getChatContent and changes the failing unit tests
to have config.model stubs defined with an empty object as their value.

---------

Co-authored-by: Ryan James Meneses <58452495+hiyaryan@users.noreply.github.com>
Co-authored-by: Ryan James Meneses <github@ryanmeneses.com>
* refactor: Start adding tests for entry controller

Added tests for getting and creating entries. getAnalysisContent
in EntryAnalysis was breaking test suite for some reason. It appeared
that using Config in the method caused an issue with the model
compilation within Jest runtime, but I'm not sure why. I pulled it out
from the file and put it in the entry services to fix it.

In-progress, so may be broken.

* refactor: add documentation for entry services

Added JSDocs for functions in entry services and broke up
createEntryAnalysis into 2 functions.

* refactor: create getPopulatedEntry function

* refactor: write functions for entry reads

Refactored entry controllers to move read calls into functions in
entry services

* revert: createEntry controller to ts migration branch

To limit the scope of this branch, I reverted changes I made to the
createEntry function in the entry contorllers to match the
139-ts-migration branch

* refactor: add more comments entry service

* Apply suggestions from code review

Co-authored-by: Ryan James Meneses <58452495+hiyaryan@users.noreply.github.com>

---------

Co-authored-by: Ryan James Meneses <58452495+hiyaryan@users.noreply.github.com>
* refactor!: migrate access middleware to TS with unit tests

* Apply suggestions from code review.

- Move `@types/jsonwebtoken` package to backend package.json.
- Organize dependencies list in alphabetical order.
- Remove unnecessary comment from head of access.ts.
- Remove unnecessary `req.isAuthenticated` check.
  - Remove associated test.
- Reset environment variables `afterAll` unit tests in test suite.
* refactor!: migrate validation middleware to TS with unit tests
- Refactor validation middleware to TS with explicit types.
- Refactor duplicate error handling code into function `throwValidationError`.
- Add unit tests with 100% coverage.
  - All `models` are mocked - model validation is tested in tests/models.
  - Ensures middleware is called and validation errors are handled.

* fix: use mockReturnValueOnce for single-call validation scenarios
…tions (#195)

* refactor: refactor entry into service layer
- Refactor business logic for create, update, and delete operations in entry controller into a service layer.
- Add unit tests.

* refactor: address code review comments
- Rename EntryRequestBody and EntryConversationRequestBody.
- Clean up comments.

* refactor: update jest.teardown.cjs
- Integrate feedback from code review combining two lines into one.

* refactor: integrate code review comments
- Integrate comments from code review for entry services.
- Remove unnecessary error handling from some methods.
- Clean up comments and rename some variables and types.
- Update unit tests.

* refactor: flatten try-catch blocks in controller
- Incorporate code review comment to avoid nested try-catch blocks in entry controller.

* refactor: fix spelling in test

* fix(comment): update comments
- Improve consistency and clarity of existing comments.

---------

Co-authored-by: Ryan James Meneses <58452495+hiyaryan@users.noreply.github.com>
- Fix build error: Argument of type '(err: ExpressError) => Promise<void>' is not assignable to parameter of type 'NextFunction'.
Bumps the npm_and_yarn group with 1 update in the /backend directory: [mongoose](https://github.com/Automattic/mongoose).


Updates `mongoose` from 8.0.0 to 8.8.3
- [Release notes](https://github.com/Automattic/mongoose/releases)
- [Changelog](https://github.com/Automattic/mongoose/blob/master/CHANGELOG.md)
- [Commits](Automattic/mongoose@8.0.0...8.8.3)

---
updated-dependencies:
- dependency-name: mongoose
  dependency-type: direct:production
  dependency-group: npm_and_yarn
...

Signed-off-by: dependabot[bot] <support@github.com>
@dependabot dependabot bot added dependencies Pull requests that update a dependency file minor Related to a minor release labels Dec 3, 2024
davidzlu and others added 3 commits December 27, 2024 19:35
…194)

* refactor: getAccount refactor into service
- Move code for getting account into new service layer module in models/services/account.ts and added unit tests for `getAccount`.

* fix: resolve tsc build error in app.ts
- `app.ts` had a build error due to the `User` type mismatching between the `passport` and `passport-local-mongoose` packages. 
 - Fix error with custom `Express.user` type modification to extend `UserType`.
- Clean up `User` and the previous workaround.

* refactor: integrate code review comments
- Integrate code review comments for `getAccount` refactor.

* refactor: refactor updateJournal
- Move code for updating journal into service layer function and added unit tests for `updateJournal`.

* refactor: refactor updateAccount
- Move business logic for `updateAccount` into account services.
- Split into `updateProfile`, `updatePassword`, and `updateConfig`.
- Add unit tests.

* refactor: refactor deleteItem
- Refactor `deleteItem` into `deleteConfig` and `deleteAccount` service functions, and write unit tests.

* refactor: refactor register controller function
- Refactor controller function to move account creation into `createAccount` service function.
- Move `validateJournal` call earlier in middleware chain.
- Add unit test for `createAccount`.

* refactor: refactor verifyEmail
- Refactor `verifyEmail` into `verifyEmail` service function, and add unit tests for `verifyEmail` service function.

* refactor: refactor resetPassword
- Refactor `resetPassword` in access controller into `resetPassword` service function.
- Add unit tests.

* fix: pass errors thrown in access service layer
- Have controller check if error thrown by service function and pass to error handler instead of creating 500 `ExpressError`.

* refactor: refactor forgotPassword
- Refactor `forgotPassword` into `forgotPassword` service function and rewrite using async/await instead of callback style. 
- Add unit tests.

* refactor: refactor login
- Refactor `login` controller handler into several functions.
- Add unit tests for `ensureUserJournal`.

* refactor: refactor tokenLogin
- Refactor `tokenLogin` in access controller.

* fix: fix order of arguments for resetPassword call
- Arguments for `AccountServices.resetPassword` were passed in the wrong order for the `resetPassword` controller handler. 
 - Correct order of arguments resolving associated errors.

* refactor: apply suggestions from code review
Co-authored-by: Ryan James Meneses <58452495+hiyaryan@users.noreply.github.com>

---------

Co-authored-by: Ryan James Meneses <github@ryanmeneses.com>
Co-authored-by: Ryan James Meneses <58452495+hiyaryan@users.noreply.github.com>
* test: initial entry controller unit tests
- Set up test suite.
  - Mock `EntryServices`, `Request`, `Response`, and `NextFunction`.
- Create test suite for `EntryController`.
  - Add tests for `getAllEntries`.

* test: add createEntry tests
- Add `createEntry` tests.
- Update mocks.
  - Simplify `mockReq`.
  - Make `mockNext` a `jest.Mock`.
- Remove mocked services that there are no tests for.
- Update `getEntry` wrt the updated `mockReq`.

* test: add additional getAllEntries test

* refactor: rename getAllEntriesInJournal to getAllEntries

* test: add getAnEntry tests

* test: add updateEntry, deleteEntry, and getEntryAnalysis tests
- Add unit tests for `updateEntry`.
- Add unit tests for `deleteEntry`.
- Add unit tests for `getEntryAnalysis`.
  - Resolve error: `entryAnalysis.toObject` is not a function.
    - Remove unnecessary `toObject` cast.

* test: add updateEntryAnalysis tests
- Add `updateEntryAnalysis` tests.
- Remove unnecessary `toObject` cast on `entryAnalysis` returned from `updateEntryAnalysis` service.

* test: add getEntryConversation, createEntryConversation, and updateEntryConversation tests

- Add `getEntryConversation` tests.
  - Remove unnecessary `toObject` cast.
- Add `createEntryConversation` tests.
  - Remove unused logic to check for empty response.
    - An error will be thrown by `getAnalysisCompletion` in entryConversation.ts before this logic is reached.
- Add `updateEntryConversation` tests.
  - Remove unnecessary `toObject` cast.
  - Note that flash messages are not sent on successful update (see FIXME).

* test: ensure an error is returned if journal.config is not found
- Add test to `createEntry` test sub-suite.

* fix: remove duplicate mock
* test: initial `access` controller tests
- Add mocks.
  - Mock `Journal.findById`.
  - Mock `ExpressError`.
  - Mock all access services.
  - Mock `Request`, `Response`, and, `next`.
- Create Entry Controller Tests test suite.
- Clear mocks before each test sub-suite.
- Add `updateJournal` test suite.

* test: add account `access` controller tests
- Test `getAccount` controller.
- Test `updateAccount` controller.
- Test `deleteItem` controller.
  - Add `req.query` to `mockReq`.
  - Update controller to handle invalid `query` items.

* test: add `login` `access` controller tests
- Test `login` controller.
  - Import `passport` for overriding and spying on its methods in tests.
  - Mock `User.findOne`.
  - Mock `passport.authenticate` with `jest.mock` to control the callback’s return values.
  - Mock `ensureJournalExists` access service.

* test: add `tokenLogin` `access` controller tests
- Test `tokenLogin` controller.
  - Mock `getPopulatedJournal` access service.
  - Ensure `RELEASE_PHASE` is not `beta`.
    - Note: `beta` conditions are not being tested.

* test: add `forgotPassword` and `resetPassword` access controller tests
- Test `forgotPassword` and `resetPassword` access controllers.
 - Mock `forgotPassword` and `resetPassword` access services.

* test: add `logout` access controller tests
- Test `logout` controller.
  - Add `req.logout` mock to `mockReq`.

* fix: resolve method `req.login` does not exist on `Request` object
- Test `register` access controller.
  - Mock `createAccount` access service.
- Incorrect log in method used to log in user on registration.
  - Result is unreachable code due to `req.login` not existing on the `Request` object.
  - Update `req.login` to `req.logIn` to use `passport` method existing on `Request`.

* test: add `verifyEmail` access controller tests
- Test `verifyEmail` access controller.
  - Mock `verifyEmail` access service.

* refactor: move `access` services file
- Move `access` services to `services/access/access.ts`.
- Reflect structure of `access.test.ts` test file.
- Update file paths in `access` controller and its tests.
- `login` test failed in CI due to `JWT_SECRET` not being defined.
  - Resolve error by defining `JWT_SECRET` in the test.
- Local mongo db could not be seeded.
  - JS files could not be resolved in `data` dir.
  - Resolve issue using `tsx` in new `package.json` `seed` script.

- Update `cdj_init.sh` to use `seed` script.

- Resolves entry deletion issue.
  - If local db is not properly seeded, replica set will not be initialized.
    - Replica sets are used to delete data accross multiple documents.
    - An entry is composed of multiple documents.
- Error displaying chat messages.
  - Due to incorrect data format returned from controller.
  - Resolve issue using `toObject`.

- Update `EntryService` mocks in associated tests to resolve with `toObject`.
- Analysis sometimes does not show up on new entry or request for new analysis.
  - Due to incorrect data format returned from controller.
  - Resolve using `toObject` on data passed to `res`.
- Env vars differ per environment.
  - `production` uses `ATLAS_URI`.
  - `development` uses `MONGO_URI`.

- Server error prevented app from starting.
  - Due to `MONGO_URI` not being defined in `production`.
  - Resolve by moving retrieval of env vars inside env specific conditionals.
- Error in conditional logic to establish connection to dev db.
  - Results in error always being thrown in `development`.
  - Resolve by negating check for `localUri`.
@hiyaryan hiyaryan merged commit 6a20903 into main Jan 16, 2025
1 check passed
@dependabot dependabot bot deleted the dependabot/npm_and_yarn/backend/npm_and_yarn-740cedace6 branch January 16, 2025 22:07
@hiyaryan hiyaryan added patch Related to a patch release and removed minor Related to a minor release labels Jan 16, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
dependencies Pull requests that update a dependency file patch Related to a patch release
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants