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

Add TypeScript GraphQL resolvers and update Fastify server configuration #25

Merged
merged 36 commits into from
Jan 12, 2024

Conversation

claygorman
Copy link
Contributor

@claygorman claygorman commented Jan 12, 2024

Type

enhancement, bug_fix


Description

  • Added TypeScript types for GraphQL resolvers and updated existing types with new fields.
  • Implemented Query and Mutation resolvers for issues, including fetching, creating links, updating, and deleting issues.
  • Introduced TypeScript types for database models to represent entities like User, Project, Issue, etc.
  • Implemented Query and Mutation resolvers for projects, including fetching projects, creating tags, and managing project users.
  • Configured the Hocuspocus server with methods for fetching, storing, and authenticating users.
  • Created and configured the Fastify server instance, including CORS setup and routes for cache stats and file uploads.
  • Implemented Query, Mutation, and Board resolvers for boards, including fetching boards, updating details, and resolving issues.
  • Handled Fastify hooks for pre-validation to process multipart requests and add user information to the request.
  • Merged all GraphQL resolvers and defined miscellaneous resolvers such as DateTime and file upload mutations.

Changes walkthrough

Relevant files                                                                                                                                 
Enhancement
10 files
resolvers-types.ts                                                                                   
    backend/src/__generated__/resolvers-types.ts

    Added a large generated TypeScript file containing types for
    GraphQL resolvers, including queries, mutations, and various
    types such as Asset, Board, Issue, Project, etc.

+1135/-0
graphql.ts                                                                                                   
    frontend/gql/__generated__/graphql.ts

    Updated the generated GraphQL TypeScript file with new types
    and fields, such as Custom_Field_Type, DateTime scalar
    type, and updated several existing types with new fields and
    comments.

+79/-24
index.ts                                                                                                       
    backend/src/resolvers/issue/index.ts

    Added a new resolver file for issues with implementations
    for Query and Mutation resolvers, including fetching
    issues, creating issue links, updating issues, and deleting
    issues.

+452/-0
types.ts                                                                                                       
    backend/src/db/models/types.ts

    Introduced TypeScript types for database models, including
    User, ProjectTag, ProjectCustomField,
    ProjectPermission, Project, IssueStatus,
    IssueComment, IssueTag, Board, IssueLink,
    IssueBoard, and Issue.

+330/-0
index.ts                                                                                                       
    backend/src/resolvers/project/index.ts

    Added a new resolver file for projects with implementations
    for Query and Mutation resolvers, including fetching
    projects, creating project tags, adding and removing users
    from projects, and creating projects.

+363/-0
hocuspocus-server.ts                                                                               
    backend/src/services/hocuspocus-server.ts

    Added a new TypeScript file to configure the Hocuspocus
    server with methods for fetching, storing, and
    authenticating users.

+157/-0
index.ts                                                                                                       
    backend/src/server/index.ts

    Added a new TypeScript file to create and configure the
    Fastify server instance, including setting up CORS, content
    type parsers, and routes for cache stats and file uploads.

+132/-0
index.ts                                                                                                       
    backend/src/resolvers/board/index.ts

    Added a new resolver file for boards with implementations
    for Query, Mutation, and Board resolvers, including
    fetching boards, updating board details, and resolving board
    issues.

+124/-0
fastify-hooks.ts                                                                                       
    backend/src/server/fastify-hooks.ts

    Added a new TypeScript file to handle Fastify hooks,
    specifically for pre-validation to process multipart
    requests and add user information to the request.

+119/-0
index.ts                                                                                                       
    backend/src/resolvers/index.ts

    Added a new TypeScript file to merge all GraphQL resolvers
    and define miscellaneous resolvers such as DateTime and
    file upload mutations.

+87/-0

✨ Usage guide:

Overview:
The describe tool scans the PR code changes, and generates a description for the PR - title, type, summary, walkthrough and labels. The tool can be triggered automatically every time a new PR is opened, or can be invoked manually by commenting on a PR.

When commenting, to edit configurations related to the describe tool (pr_description section), use the following template:

/describe --pr_description.some_config1=... --pr_description.some_config2=...

With a configuration file, use the following template:

[pr_description]
some_config1=...
some_config2=...
Enabling\disabling automation
  • When you first install the app, the default mode for the describe tool is:
pr_commands = ["/describe --pr_description.add_original_user_description=true" 
                         "--pr_description.keep_original_user_title=true", ...]

meaning the describe tool will run automatically on every PR, will keep the original title, and will add the original user description above the generated description.

  • Markers are an alternative way to control the generated description, to give maximal control to the user. If you set:
pr_commands = ["/describe --pr_description.use_description_markers=true", ...]

the tool will replace every marker of the form pr_agent:marker_name in the PR description with the relevant content, where marker_name is one of the following:

  • type: the PR type.
  • summary: the PR summary.
  • walkthrough: the PR walkthrough.

Note that when markers are enabled, if the original PR description does not contain any markers, the tool will not alter the description at all.

Custom labels

The default labels of the describe tool are quite generic: [Bug fix, Tests, Enhancement, Documentation, Other].

If you specify custom labels in the repo's labels page or via configuration file, you can get tailored labels for your use cases.
Examples for custom labels:

  • Main topic:performance - pr_agent:The main topic of this PR is performance
  • New endpoint - pr_agent:A new endpoint was added in this PR
  • SQL query - pr_agent:A new SQL query was added in this PR
  • Dockerfile changes - pr_agent:The PR contains changes in the Dockerfile
  • ...

The list above is eclectic, and aims to give an idea of different possibilities. Define custom labels that are relevant for your repo and use cases.
Note that Labels are not mutually exclusive, so you can add multiple label categories.
Make sure to provide proper title, and a detailed and well-phrased description for each label, so the tool will know when to suggest it.

Utilizing extra instructions

The describe tool can be configured with extra instructions, to guide the model to a feedback tailored to the needs of your project.

Be specific, clear, and concise in the instructions. With extra instructions, you are the prompter. Notice that the general structure of the description is fixed, and cannot be changed. Extra instructions can change the content or style of each sub-section of the PR description.

Examples for extra instructions:

[pr_description] 
extra_instructions="""
- The PR title should be in the format: '<PR type>: <title>'
- The title should be short and concise (up to 10 words)
- ...
"""

Use triple quotes to write multi-line instructions. Use bullet points to make the instructions more readable.

More PR-Agent commands

To invoke the PR-Agent, add a comment using one of the following commands:

  • /review: Request a review of your Pull Request.
  • /describe: Update the PR title and description based on the contents of the PR.
  • /improve [--extended]: Suggest code improvements. Extended mode provides a higher quality feedback.
  • /ask <QUESTION>: Ask a question about the PR.
  • /update_changelog: Update the changelog based on the PR's contents.
  • /add_docs 💎: Generate docstring for new components introduced in the PR.
  • /generate_labels 💎: Generate labels for the PR based on the PR's contents.
  • /analyze 💎: Automatically analyzes the PR, and presents changes walkthrough for each component.

See the tools guide for more details.
To list the possible configuration parameters, add a /config comment.

See the describe usage page for a comprehensive guide on using this tool.

Several frontend components were updated to fix minor spelling issues and import order. The backend node script has been updated to use TypeScript files instead of JavaScript. The backend package.json has been updated with newer dependencies and included build script. Some string literals were also changed in the backend server to lower case.
This update focuses on enhancing TypeScript compatibility by introducing a new dev dependency "ts-node" for better TypeScript runtime support. The "type" field is added to package.json making the project a module, and a new command "dev:ts" has been added to allow running the project using ts-node. A "built" exception is placed in .dockerignore. Command for running the development server inside Docker was adjusted accordingly.
Updated Docker and ignore files to better handle typescript build files, and switched to SWC for faster compilation. The changes include updating the output directory from 'built' to 'dist', adding SWC as a dev dependency, and adding 'dist' to the list of docker ignored paths.
This commit completely removes all database migration files in the backend/src/db/migrations directory. The files include migrations for creating tables such as "projects", "users", "boards", "issue_statuses", and more. It seems like some foundational changes are planned for the structure of the backend database necessitating the removal of all these migrations.
This commit includes several updates across multiple files for the backend, including revising import paths, updating build and execution scripts, and refining TypeScript configuration. The primary focus has been improving compatibility between files and making sure necessary configurations are appropriately updated.
This commit completely removes all database migration files in the backend/src/db/migrations directory. The files include migrations for creating tables such as "projects", "users", "boards", "issue_statuses", and more. It seems like some foundational changes are planned for the structure of the backend database necessitating the removal of all these migrations.
The `docker-compose-clay.yml` file was removed as it's no longer needed. The backend code on `index.ts` was refactored, moving several interface definitions to a new typings file at `backend/src/typings/index.ts`. A minor adjustment was also made to handling multipart requests. A `pnpm-lock.yaml` file was created for project dependencies.
The update includes major restructuring in the backend codebase, primarily focused on introducing individual Fastify handlers for different server functionalities. Also, backend typings and model definitions have been moved to a different file. Dependencies and scripts in package.json have been updated, and new files fastify-ws.ts and hocuspocus.ts have been added. Finally, the Dockerfile.local and .tool-versions files have been adjusted accordingly.
This code revision refactors the database models on the backend. The refactoring process involves enhancing and integrating Sequelize TypeScript typings, replacing 'DataTypes' with more specific Sequelize model types, and improving the correct typing of certain variables and return types. This will for sure facilitate scaling and ongoing development by boosting type safety, understanding, and editor-aided inspections of the models.
We have introduced a new type, MinioGetObjectResponse, in the server index for better data structure comprehension. This change reflects an update in the way we handle files in the '/uploads/:file' route, removing the previously needed '@ts-ignore' and enhancing TypeScript integration. This should streamline file processing in the backend and improve overall code clarity.
The CORS settings in the server index file have been refactored. The previous CORS settings relied on hard-coded conditions, this update introduces the usage of a separate handler function for setting up CORS OPTIONS. This will ensure modularity and improves the flexibility of the CORS configuration.
The User import was updated in apollo.ts to reflect its new location. In index.ts, the Fastify request import was expanded to enable a fleshed out request handler for 'multipart' content types. In fastify-ws.ts, the handling of 'multipart' requests was refined and moved to occur earlier in the preValidation hook. This helps ensure that multipart requests, notably for file uploads, are processed properly across the application.
A new caching mechanism has been introduced using NodeCache to handle user authentication and reduce database queries. The changes refactored the authentication process in the backend by moving the user authentication from Apollo and Fastify-WS to Fastify hooks. This change facilitates more efficient request handling in the server, improving performance. Furthermore, a new utility function, `hash`, is added to aid in creating cache keys.
The code refactor primarily targets improving readability by breaking the server configuration into discrete functions. Additionally, a cache mechanism has been introduced for token verification process. This adjustment aims to boost performance by reducing redundant requests to JWT verification API whenever a valid token is presented.
Added type annotations to 'fetch' and 'store' methods in hocuspocus-server.ts. Additionally, simplified a condition check in 'store' method for 'issueComment' entityType.
The code updates in hocuspocus-server.ts include the usage of types for better data handling and enhanced exception handling. It also includes changing the way JWT is verified with the addition of the VerifyJwtResponse type for more precise data extraction. Improvements finalize on refining the user fetching process from the database using the User type.
Optimized Sequelize usage by using the `init` function instead of `define` in backend database models. This improvement led to more strict TypeScript typings, which increases code stability and makes development easier. Naming conventions were also adjusted for better semantic clarity. Manual updates on model associations and import paths were done accordingly. Resolvers were then adjusted to match the updated models.
Optimized Sequelize usage by using the `init` function instead of `define` in backend database models. This improvement led to more strict TypeScript typings, which increases code stability and makes development easier. Naming conventions were also adjusted for better semantic clarity. Manual updates on model associations and import paths were done accordingly. Resolvers were then adjusted to match the updated models.
The ESLint configuration file for the backend has been renamed from .eslintrc to .eslintrc.json. Consequently, the reference to this file in .lintstagedrc has been updated to reflect this change.
Several properties across different models in `backend/src/db/models/types.ts` have been updated to use `CreationOptional`. This change provides better clarity that these properties can be undefined during instance creation. Additionally, the build script in `backend/package.json` has been simplified and the unnecessary `--resolve-extensions=.js` flag removed.
This commit introduces a new `codegen.ts` file for configuring GraphQL code generation using `@graphql-codegen/cli`. Besides, it includes a large set of generated TypeScript types for existing GraphQL queries, mutations, and input types. This supports better type safety and autocompletion when working with GraphQL on the backend.
The versions of '@graphql-codegen/cli', '@graphql-codegen/typescript', '@graphql-codegen/typescript-resolvers', and '@babel/traverse' have been fixed and updated in the pnpm-lock.yaml. The changes remove the range (caret) from the version specification, which ensures that the exact listed versions are used, improving the reliability of the build process.
The code has been refactored to enhance TypeScript type safety by changing import statements to import type where applicable. Linting scripts have been updated with the integration of 'oxlint' and 'eslint'. This leads to improved code quality and adherence to coding standards. Additionally, the 'hocuspocus-server.ts' file has been refactored to improve the overall readability of the code.
The type definitions for 'uuid' have been added to the project's backend dependencies. This addition is visible in both package.json and pnpm-lock.yaml files, ensuring consistency and addressing possible type checking needs for 'uuid' in the backend.
The 'module-alias', 'sharp', and '@types/module-alias' dependencies along with their related entries have been deleted from the pnpm-lock.yaml file. This commit also includes the removal of several additional subdependencies, improving the project's overall dependency management and reducing the install size.
The file 'backend/src/__generated__/resolvers-types.ts' was deleted. This file was auto-generated and used types definitions for GraphQL resolvers. Its removal suggests a clean up or a change in the approach for handling schema and type definitions.
Dependencies for the backend have been updated with the addition of "dataloader-sequelize". Also, the code for resolving graphql queries in the backend has been refactored to improve readability and maintainability. This includes the use of database calls for fetching data and using a custom "Date" scalar for date values in the graphql schema.
This update changes 'Date' to 'DateTime' across GraphQL resolvers and generated types. The code now utilizes 'graphql-scalars' for the DateTime scalar implementation, resulting in improved clarity and consistency. The 'Date' scalar used previously was manually crafted hence changed for better clarity and functionality. Several query and mutation resolvers are updated to accommodate this change.
The identifiers used in project/index, issue-comment/index, board/index and user/index resolvers have been converted to numbers. This change aids in uniformity and prevents potential type-related bugs. Resolvers are also updated to use DataLoader for caching, reducing the number of database queries executing a significant performance enhancement.
AssetModel is now being imported into the user resolver in the backend. This has been used to properly type the variable findOldAvatarAsset. This will ensure more accurate and safer type-checking within the resolvers.
…ponents

This commit focuses on two main changes to the codebase. First, it streamlines the way data is mapped from database queries in resolver functions - unnecessary array spreads are removed, simplifying the array returns. Secondly, it modifies how dates are handled in a number of frontend components to use 'DateTime.fromISO' instead of 'DateTime.fromMillis', reflecting the way dates are stored and returned from the backend.
Removed 'include' query parameter from the project resolver to simplify the database query. Updated the issue resolver to handle issueId as a Number type to ensure correct issue-board relationship. Modified the board resolver to fetch issues from viewState and handle data accordingly. These changes help improve code maintainability and consistency.
The MyWebSocket interface has been extended by adding 'id', 'user', and 'namespace' optional properties. Following this extension, the way connection sockets are handled in the 'wsServer.handleConnection' method was also refactored. Instead of directly injecting the properties into the socket, a separate handleConnectionSocket object was created, which then gets passed to the method.
The handshake connection and message handling is now encapsulated within a separate `wsPlugin` function. This streamlines the main `fastifyWsHandler` function by allowing it to focus on fastify-specific configuration and registration tasks, improving code readability and maintainability.
Copy link
Contributor

PR Analysis

  • 🎯 Main theme: Migration from JavaScript to TypeScript for several backend components and GraphQL resolvers.
  • 📝 PR summary: The PR introduces TypeScript to the project by updating backend components, GraphQL resolvers, and configurations to use TypeScript. It also includes updates to Docker configurations, package.json, and the removal of old database migration files.
  • 📌 Type of PR: Enhancement
  • ⏱️ Estimated effort to review [1-5]: 4, because the PR involves a migration to TypeScript which includes changes to multiple files and configurations, as well as the removal of database migration files which may require careful consideration of the impact on the existing database schema and data.
  • 🔒 Security concerns: No security concerns found

PR Feedback

💡 General suggestions: The migration to TypeScript is a significant change that can help improve the maintainability and robustness of the codebase. It is important to ensure that all TypeScript types and interfaces are correctly defined and that the code adheres to TypeScript best practices. Additionally, the removal of database migration files suggests that there are changes to the database schema, which should be reviewed carefully to ensure that they do not negatively impact the existing data and functionality.

🤖 Code feedback:
relevant filebackend/src/__generated__/resolvers-types.ts
suggestion      

Consider using TypeScript enums for string literal types such as BoardStyle and Custom_Field_Type to ensure consistency and prevent typos across the codebase. [important]

relevant lineexport enum BoardStyle {

relevant filebackend/src/resolvers/issue/index.ts
suggestion      

Ensure that the context parameter in resolver functions is typed to provide better autocompletion and error checking. [important]

relevant lineconst Query: QueryResolvers = {

relevant filebackend/src/server/index.ts
suggestion      

For the CORS handler, consider creating a utility function to handle the origin checks to improve modularity and testability of the code. [medium]

relevant lineconst corsHandler: OriginFunction = (origin, cb) => {

relevant filebackend/src/server/fastify-hooks.ts
suggestion      

Extract the logic for user authentication and caching into a separate service or middleware to reduce complexity and improve the separation of concerns within the fastifyHooksHandler. [important]

relevant lineconst addUserToRequest = async (request: CustomFastifyRequest, reply: FastifyReply) => {


✨ Usage guide:

Overview:
The review tool scans the PR code changes, and generates a PR review. The tool can be triggered automatically every time a new PR is opened, or can be invoked manually by commenting on any PR.
When commenting, to edit configurations related to the review tool (pr_reviewer section), use the following template:

/review --pr_reviewer.some_config1=... --pr_reviewer.some_config2=...

With a configuration file, use the following template:

[pr_reviewer]
some_config1=...
some_config2=...
Utilizing extra instructions

The review tool can be configured with extra instructions, which can be used to guide the model to a feedback tailored to the needs of your project.

Be specific, clear, and concise in the instructions. With extra instructions, you are the prompter. Specify the relevant sub-tool, and the relevant aspects of the PR that you want to emphasize.

Examples for extra instructions:

[pr_reviewer] # /review #
extra_instructions="""
In the code feedback section, emphasize the following:
- Does the code logic cover relevant edge cases?
- Is the code logic clear and easy to understand?
- Is the code logic efficient?
...
"""

Use triple quotes to write multi-line instructions. Use bullet points to make the instructions more readable.

How to enable\disable automation
  • When you first install PR-Agent app, the default mode for the review tool is:
pr_commands = ["/review", ...]

meaning the review tool will run automatically on every PR, with the default configuration.
Edit this field to enable/disable the tool, or to change the used configurations

About the 'Code feedback' section

The review tool provides several type of feedbacks, one of them is code suggestions.
If you are interested only in the code suggestions, it is recommended to use the improve feature instead, since it dedicated only to code suggestions, and usually gives better results.
Use the review tool if you want to get a more comprehensive feedback, which includes code suggestions as well.

Auto-labels

The review tool can auto-generate two specific types of labels for a PR:

  • a possible security issue label, that detects possible security issues (enable_review_labels_security flag)
  • a Review effort [1-5]: x label, where x is the estimated effort to review the PR (enable_review_labels_effort flag)
Extra sub-tools

The review tool provides a collection of possible feedbacks about a PR.
It is recommended to review the possible options, and choose the ones relevant for your use case.
Some of the feature that are disabled by default are quite useful, and should be considered for enabling. For example:
require_score_review, require_soc2_review, enable_review_labels_effort, and more.

More PR-Agent commands

To invoke the PR-Agent, add a comment using one of the following commands:

  • /review: Request a review of your Pull Request.
  • /describe: Update the PR title and description based on the contents of the PR.
  • /improve [--extended]: Suggest code improvements. Extended mode provides a higher quality feedback.
  • /ask <QUESTION>: Ask a question about the PR.
  • /update_changelog: Update the changelog based on the PR's contents.
  • /add_docs 💎: Generate docstring for new components introduced in the PR.
  • /generate_labels 💎: Generate labels for the PR based on the PR's contents.
  • /analyze 💎: Automatically analyzes the PR, and presents changes walkthrough for each component.

See the tools guide for more details.
To list the possible configuration parameters, add a /config comment.

See the review usage page for a comprehensive guide on using this tool.

@claygorman
Copy link
Contributor Author

/describe

@github-actions github-actions bot changed the title Move to ts Add TypeScript GraphQL resolvers and update Fastify server configuration Jan 12, 2024
@github-actions github-actions bot added enhancement New feature or request bug_fix labels Jan 12, 2024
Copy link
Contributor

PR Description updated to latest commit (ee766c3)

@claygorman claygorman merged commit 27ea86a into master Jan 12, 2024
1 of 2 checks passed
@claygorman claygorman deleted the move-to-ts branch January 12, 2024 21:25
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug_fix enhancement New feature or request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant