-
-
Notifications
You must be signed in to change notification settings - Fork 95
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
feat(trpc): support client helpers for Nuxt #1762
Conversation
📝 Walkthrough📝 WalkthroughWalkthroughThis pull request introduces significant modifications to the Changes
Assessment against linked issues
Possibly related issues
Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
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 (
|
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: 33
🧹 Outside diff range and nitpick comments (49)
packages/plugins/trpc/tests/projects/nuxt-trpc-v11/server/trpc/routers/index.ts (1)
5-6
: LGTM: Proper type export with a minor suggestion.The export of the
AppRouter
type is correct and essential for maintaining type safety throughout the application. This aligns well with TypeScript best practices and the PR objectives.Consider enhancing the comment slightly for even more clarity:
- // export type definition of API + // Export type definition of API for use in other parts of the applicationThis minor change provides more context about the purpose and usage of the exported type.
packages/plugins/trpc/tests/projects/nuxt-trpc-v10/nuxt.config.ts (1)
1-8
: Overall, the Nuxt configuration looks good and addresses the PR objectives.The configuration successfully sets up the necessary options for integrating TRPC with Nuxt.js, which aligns with the PR's goal of supporting client helpers for Nuxt in TRPC.
For future enhancements, consider:
- Adding TypeScript configuration options if you're using TypeScript in your project.
- Configuring auto-imports for TRPC-related functions to improve developer experience.
- Setting up module options for 'trpc-nuxt' if any are available.
These suggestions can further streamline the development process and enhance the integration between TRPC and Nuxt.js.
packages/plugins/trpc/tests/projects/nuxt-trpc-v11/nuxt.config.ts (2)
4-4
: Consider environment-specific configuration for devtools.Devtools are currently enabled for all environments. While this is beneficial for development, it might not be suitable for production deployments.
Consider using environment variables or build-time conditions to enable devtools only in non-production environments. For example:
devtools: { enabled: process.env.NODE_ENV !== 'production' },
1-8
: Overall configuration looks good with room for future enhancements.The Nuxt configuration file is well-structured and includes the essential settings for integrating tRPC with Nuxt, aligning perfectly with the PR objectives. It provides a solid foundation for the feature implementation.
For future enhancements, consider:
- Adding type checking options (e.g.,
typescript.typeCheck: true
) to enforce stricter type checking during the build process.- Configuring module options for
trpc-nuxt
if any specific settings are required.- Setting up auto-imports for tRPC-related utilities to improve developer experience.
packages/plugins/trpc/tests/projects/nuxt-trpc-v10/server/api/trpc/[trpc].ts (1)
5-9
: LGTM: API handler setup is correct and aligns with PR objectives.The implementation correctly sets up a Nuxt API handler for TRPC using
createNuxtApiHandler
. The configuration withappRouter
andcreateContext
properly integrates the necessary TRPC components.Consider adding a brief comment explaining the purpose of this file and how it integrates TRPC with Nuxt. This could help developers who are less familiar with the TRPC-Nuxt integration. For example:
// This file sets up a Nuxt API handler for TRPC, allowing Nuxt to handle TRPC requests. // It uses the dynamic API routes feature of Nuxt (hence the [trpc].ts filename). export default createNuxtApiHandler({ router: appRouter, createContext, });packages/plugins/trpc/tests/projects/nuxt-trpc-v11/server/api/trpc/[trpc].ts (1)
6-9
: LGTM: API handler is correctly set upThe TRPC API handler for Nuxt is properly configured:
createNuxtApiHandler
is used to create the handler.appRouter
is correctly passed as therouter
option.createContext
function is provided to set up the request context.This setup aligns with the standard pattern for integrating TRPC with Nuxt.
Consider adding a type annotation to the exported handler for improved code readability:
export default createNuxtApiHandler({ router: appRouter, createContext, }) as ReturnType<typeof createNuxtApiHandler>;This explicit type annotation can help other developers understand the return type of the exported handler.
packages/plugins/trpc/tests/projects/nuxt-trpc-v10/server/trpc/routers/index.ts (2)
1-2
: LGTM! Consider clarifying the import name.The imports are appropriate for setting up a TRPC router in a Nuxt.js project. The use of a generated routers module is a good practice for maintaining a clean project structure.
Consider renaming the imported
createRouter
function to something more specific, likecreateCRUDRouter
, to better reflect its purpose:-import { createRouter as createCRUDRouter } from './generated/routers'; +import { createRouter as createTRPCRouter } from './generated/routers';This change would make the code more self-explanatory and consistent with the TRPC naming convention.
4-4
: LGTM! Consider adding a brief comment.The creation and export of the
appRouter
is correct and follows TRPC conventions. The use ofpublicProcedure
indicates that this router will handle public routes.Consider adding a brief comment to explain the purpose of this router:
+// Create the main application router with CRUD operations export const appRouter = createCRUDRouter(router, publicProcedure);
This comment would provide context for other developers who might work on this file in the future.
packages/plugins/trpc/tests/projects/nuxt-trpc-v10/server/trpc/context.ts (1)
4-10
: LGTM:createContext
function is well-implemented.The
createContext
function is correctly implemented according to TRPC's patterns. It's simple, well-documented, and provides the necessaryprisma
instance for database operations.For future scalability, consider:
- Adding more context properties as needed (e.g., user session, request metadata).
- Implementing async functionality if complex setup operations are required.
- Adding error handling if any setup steps could potentially fail.
packages/plugins/trpc/tests/projects/nuxt-trpc-v11/server/trpc/context.ts (2)
4-10
: LGTM:createContext
function is well-defined.The
createContext
function is correctly implemented and documented. It provides theprisma
instance in the context, which is essential for database access in TRPC resolvers.Consider the potential need to expand this function in the future to include request-specific information (e.g., user authentication data) if required by your application's architecture.
1-12
: Great job on setting up the TRPC context for Nuxt.js!This file provides a solid foundation for TRPC integration in a Nuxt.js project. It follows TRPC best practices, is well-documented, and ensures type safety. The context setup is concise and includes the necessary database access via the
prisma
instance.As the project grows, you may need to expand the context to include additional services or request-specific information. The current structure allows for easy extension when needed.
packages/plugins/trpc/tests/projects/nuxt-trpc-v10/plugins/client.ts (3)
1-3
: LGTM! Consider adding type annotations for clarity.The imports are appropriate for setting up a TRPC client in a Nuxt environment. Good use of Nuxt's tilde (~) alias for project root imports.
Consider adding explicit type annotations to improve code readability:
- import { httpBatchLink } from 'trpc-nuxt/client'; + import { httpBatchLink } from 'trpc-nuxt/client'; - import type { AppRouter } from '~/server/trpc/routers'; + import type { AppRouter } from '~/server/trpc/routers'; - import { createTRPCNuxtClient } from '~/server/trpc/routers/generated/client/nuxt'; + import { createTRPCNuxtClient } from '~/server/trpc/routers/generated/client/nuxt';
5-16
: LGTM! Consider adding error handling for production environments.The plugin is well-structured and correctly implements the TRPC client for Nuxt. Good use of type parameters and standard configuration.
For production environments, consider adding error handling to the
httpBatchLink
configuration:const client = createTRPCNuxtClient<AppRouter>({ links: [ httpBatchLink({ url: '/api/trpc', + fetch(url, options) { + return fetch(url, options).then(async (response) => { + if (!response.ok) { + const errorData = await response.json().catch(() => null); + throw new Error(errorData?.message || 'Network response was not ok'); + } + return response; + }); + }, }), ], });This addition will provide more robust error handling, especially useful in production environments.
18-22
: LGTM! Consider adding a type annotation for extra clarity.The plugin correctly provides the TRPC client to the Nuxt application, following the proper convention.
For improved type safety and documentation, consider adding a type annotation to the return object:
- return { + return { provide: { client, }, - }; + } as const;This
as const
assertion will ensure that theprovide
object is treated as a readonly object with aclient
property, which can help catch potential typos or misuses elsewhere in the codebase.packages/plugins/trpc/tests/projects/nuxt-trpc-v11/plugins/client.ts (3)
5-9
: LGTM: Plugin definition is correct. Consider enhancing the comment.The plugin is correctly defined using
defineNuxtPlugin
. The comment provides useful information about theuseQuery
composable.Consider expanding the comment to briefly explain what
useAsyncData
is, for developers who might not be familiar with Nuxt:/** * createTRPCNuxtClient adds a `useQuery` composable - * built on top of `useAsyncData`. + * built on top of `useAsyncData`, a Nuxt composable for handling + * asynchronous data fetching with automatic caching and revalidation. */
10-16
: LGTM: Client creation is correct. Consider making the API URL configurable.The TRPC client is correctly created with proper typing and configuration. The use of
httpBatchLink
is appropriate for efficient API calls.Consider making the API URL configurable to improve flexibility:
const client = createTRPCNuxtClient<AppRouter>({ links: [ httpBatchLink({ - url: '/api/trpc', + url: process.env.NUXT_PUBLIC_TRPC_API_URL || '/api/trpc', }), ], });This change allows for easy configuration of the API URL through environment variables, which can be useful in different deployment scenarios.
18-23
: LGTM: Plugin return statement is correct. Consider adding a type annotation.The plugin correctly provides the TRPC client to the Nuxt application, making it available for injection throughout the app.
Consider adding a type annotation to the
provide
object for improved clarity:return { - provide: { + provide: { + client: client as ReturnType<typeof createTRPCNuxtClient<AppRouter>>, }, };This change explicitly declares the type of the provided client, which can help with type inference in consuming components.
packages/plugins/trpc/tests/projects/nuxt-trpc-v10/server/trpc/trpc.ts (3)
1-13
: LGTM! Consider adding a brief example in the documentation.The import statements and tRPC initialization look good. The documentation comment is clear and informative, providing useful links to the tRPC documentation.
Consider adding a brief example of how to use the exported entities in the documentation comment. This could help developers quickly understand how to implement the tRPC setup in their Nuxt.js applications.
15-20
: LGTM! Consider adding documentation forrouter
andmiddleware
.The exported entities are correctly implemented and follow tRPC conventions. The comment for
publicProcedure
is helpful.Consider adding brief documentation comments for
router
andmiddleware
similar to the one forpublicProcedure
. This would provide consistency in documentation and help developers understand the purpose of each exported entity.For example:
/** * Public (unprotected) procedure */ export const publicProcedure = t.procedure; /** * Router instance for defining API endpoints */ export const router = t.router; /** * Middleware for adding custom logic to procedures */ export const middleware = t.middleware;
1-20
: Great implementation of tRPC setup for Nuxt.js!This file successfully sets up the root configuration for tRPC on the server side of a Nuxt.js application. It follows tRPC conventions and best practices, providing a solid foundation for integrating tRPC with Nuxt.js.
The implementation aligns well with the PR objectives of supporting client helpers for Nuxt. It exports the necessary entities (
publicProcedure
,router
, andmiddleware
) that developers will need to create their tRPC API endpoints.As the project grows, consider creating separate files for complex routers or middleware to maintain a clean and modular structure. This file serves as an excellent entry point for tRPC configuration.
packages/plugins/trpc/tests/projects/nuxt-trpc-v11/server/trpc/trpc.ts (3)
1-13
: LGTM! Consider using named import for improved clarity.The setup for tRPC is well-structured and follows best practices. The comments provide clear guidance on the file's purpose and usage.
Consider using a named import for
initTRPC
to improve code clarity:-import { initTRPC } from '@trpc/server'; +import { initTRPC } from '@trpc/server';This change aligns with common TypeScript conventions and makes it clearer which specific functionality is being imported.
15-20
: LGTM! Consider adding comments forrouter
andmiddleware
.The exported entities are correctly defined and provide the necessary components for building tRPC APIs.
For consistency and improved documentation, consider adding brief comments for
router
andmiddleware
similar to the one forpublicProcedure
:/** * Unprotected procedure **/ export const publicProcedure = t.procedure; + +/** + * Create a router + **/ export const router = t.router; + +/** + * Create reusable middleware + **/ export const middleware = t.middleware;These additional comments will help developers understand the purpose of each exported entity at a glance.
1-20
: Great implementation of tRPC setup for Nuxt!This file successfully establishes the foundation for integrating tRPC with Nuxt, aligning well with the PR objectives. It provides the necessary exports for building tRPC APIs while following best practices and conventions.
As the project grows, consider:
- Implementing protected procedures alongside the
publicProcedure
.- Creating separate files for complex routers or middlewares to maintain modularity.
- Documenting any Nuxt-specific considerations or patterns in comments for future developers.
These steps will ensure the codebase remains scalable and maintainable as the integration between tRPC and Nuxt evolves.
packages/plugins/trpc/src/client-helper/next.ts (2)
7-10
: LGTM: Function correctly delegates to React version.The
generateRouterTypingImports
function appropriately calls its React counterpart, maintaining consistency between Next.js and React implementations.Consider enhancing the comment to provide more context:
- // next shares the same typing imports as react + // Next.js shares the same router typing imports as React for tRPC integration
12-21
: LGTM: Function correctly delegates to React version.The
generateProcedureTyping
function appropriately calls its React counterpart, maintaining consistency between Next.js and React implementations.Consider enhancing the comment to provide more context:
- // next shares the same procedure typing as react + // Next.js shares the same procedure typing as React for tRPC integrationpackages/plugins/trpc/tests/projects/nuxt-trpc-v10/README.md (4)
5-21
: LGTM: Comprehensive setup instructionsThe setup section provides clear instructions for installing dependencies using various package managers (npm, pnpm, yarn, and bun). This ensures that users can follow the setup process regardless of their preferred tool.
Consider adding a brief note about Node.js version requirements, if any, to ensure users have the correct environment set up before installation.
41-73
: LGTM: Comprehensive production build instructionsThe production section provides clear instructions for building the application and previewing the production build using various package managers.
Consider adding a brief explanation of the difference between the development server and the production preview, to help users understand when to use each command.
75-75
: Consider expanding the deployment sectionWhile the link to the deployment documentation is valuable, this section could be expanded to provide more immediate value to users.
Consider adding:
- A brief overview of common deployment options for Nuxt 3 applications.
- Any specific considerations for deploying a Nuxt 3 application with TRPC integration.
- Links to popular hosting platforms that support Nuxt 3 deployments.
This additional information would give users a quick starting point for deployment without needing to immediately navigate away from the README.
1-75
: Consider adding TRPC-specific informationThe README provides a good overview of a standard Nuxt 3 project setup. However, given that this project is specifically about TRPC integration with Nuxt, it would be beneficial to include some TRPC-specific information.
Consider adding:
- A brief explanation of what TRPC is and how it's integrated with this Nuxt 3 starter.
- Any specific setup steps required for TRPC integration.
- Links to TRPC documentation and the trpc-nuxt package.
- A simple example of how to use TRPC in a Nuxt 3 project.
This additional information would make the README more tailored to the specific use case of this project and provide more immediate value to users looking to work with TRPC in a Nuxt 3 environment.
packages/plugins/trpc/tests/projects/nuxt-trpc-v11/README.md (4)
5-21
: LGTM: Comprehensive setup instructionsThe setup section provides clear instructions for installing dependencies using various package managers (npm, pnpm, yarn, and bun). This is user-friendly and accommodates different developer preferences.
Consider adding a note about Node.js version requirements, if any, to ensure users have the correct environment set up before installation.
41-73
: LGTM: Comprehensive production build and preview instructionsThe Production section clearly separates and explains the processes for building the application and previewing the production build. Commands for various package managers are correctly provided.
Consider adding a brief explanation of what the build process does (e.g., optimizes for production, generates static files) to give users more context.
75-75
: Enhance the Deployment sectionWhile the link to the deployment documentation is valuable, this section could be more informative.
Consider expanding this section with:
- A brief introduction to deployment options for Nuxt 3 applications.
- Mention of any preferred or recommended deployment platforms.
- A note on any Nuxt-specific considerations for deployment.
This additional context would make the README more comprehensive and helpful for users.
1-75
: Overall assessment: Well-structured and informative READMEThis README provides comprehensive guidance for setting up and running a Nuxt 3 project, which aligns well with the PR objective of supporting client helpers for Nuxt in the context of TRPC. The inclusion of commands for various package managers enhances usability.
While the README is not directly related to the TRPC client helpers, it serves as a valuable resource for developers working with Nuxt 3, which is the target framework for the TRPC integration mentioned in the PR objectives.
As you continue to develop the TRPC integration with Nuxt, consider adding a section to this README (or creating a separate TRPC-specific README) that explains:
- How to set up TRPC with Nuxt 3
- Any specific configurations needed for the client helpers
- Examples of using the TRPC client helpers in a Nuxt 3 project
This would further enhance the documentation and directly support the PR's goal of improving TRPC usability in Nuxt projects.
packages/plugins/trpc/tests/projects/nuxt-trpc-v10/app.vue (1)
1-40
: Overall: Good implementation with room for improvementThe file successfully demonstrates the integration of TRPC with a Nuxt application, aligning well with the PR objectives. It showcases both querying and mutating data using TRPC client helpers.
However, for production-ready code, consider the following improvements:
- Error handling: Add try-catch blocks in the
onCreate
function to handle potential errors during post creation.- Input validation: Implement input validation before creating new posts.
- Loading states: Add loading states for both the initial post fetch and during post creation to improve user experience.
- Typescript types: Consider defining explicit types for the post and author objects to improve type safety.
To implement these improvements, you could:
- Wrap the post creation logic in a try-catch block and display any errors to the user.
- Add a form with validation for creating new posts instead of using hardcoded values.
- Use Vue's
ref
to create loading state variables and display loading indicators in the template.- Define interfaces for
Post
andAuthor
types and use them throughout the component.These enhancements would make the code more robust and production-ready while maintaining the demonstrated TRPC-Nuxt integration.
packages/plugins/trpc/tests/projects/nuxt-trpc-v11/app.vue (2)
10-16
: Consider using variables for post dataThe post data (title, content, author ID) is hardcoded. Consider using variables or props for these values to make the component more flexible and reusable.
Here's a suggestion:
const newPostData = reactive({ title: 'New Post', content: 'This is a new post', authorId: '1' }); // Then use newPostData in the mutation calls data: { title: newPostData.title, content: newPostData.content, author: { connect: { id: newPostData.authorId } }, },Also applies to: 20-26
32-40
: Consider adding loading and error statesThe template doesn't show loading states or handle potential errors. Consider adding these to improve user experience.
Here's a suggestion:
<template> <h1>Home</h1> <div v-if="isLoading">Loading...</div> <div v-else-if="error">Error: {{ error.message }}</div> <div v-else> <ul> <li v-for="post in posts" :key="post.id">{{ post.title }} by {{ post.author.email }}</li> </ul> <button @click="onCreate" :disabled="isCreating">{{ isCreating ? 'Creating...' : 'Create Post' }}</button> </div> </template> <script setup lang="ts"> // ... existing code ... const isLoading = ref(true); const error = ref(null); const isCreating = ref(false); onMounted(async () => { try { await posts.value.$fetch(); } catch (e) { error.value = e; } finally { isLoading.value = false; } }); const onCreate = async () => { isCreating.value = true; try { // ... existing onCreate logic ... } catch (e) { console.error('Error creating post:', e); } finally { isCreating.value = false; } }; </script>This addition will provide feedback to the user during loading and error states, enhancing the overall user experience.
packages/plugins/trpc/tests/projects/nuxt-trpc-v10/schema.zmodel (2)
24-35
: LGTM: Well-structured User model with appropriate validations and access controlThe User model is well-defined with appropriate fields, validations, and access control rules:
- Email field has proper uniqueness and format validations.
- Password field is correctly omitted and marked for hashing.
- Access control rules allow signup and full access for authenticated users to their own data.
Consider adding a
name
field to the User model for a more complete user profile. For example:model User { id String @id @default(cuid()) + name String @length(2, 50) email String @unique @email @length(6, 32) password String @password @omit posts Post[] // ... (rest of the model remains the same) }
40-55
: LGTM: Well-structured Post model with appropriate fields, relations, and access controlThe Post model is well-defined with appropriate fields, relations, and access control rules:
- Timestamps are correctly managed with
@default(now())
and@updatedAt
.- The relation to the User model is properly defined.
- Access control rules allow read access for published posts and full access for the author.
Consider adding a length validation for the
content
field to prevent excessively long posts. For example:model Post { // ... (previous fields remain the same) - content String + content String @length(1, 10000) // ... (rest of the model remains the same) }This ensures that post content has a reasonable maximum length.
packages/plugins/trpc/tests/projects/t3-trpc-v10/src/pages/index.tsx (1)
Line range hint
1-38
: Summary of review for index.tsxThe changes in this file successfully implement the new post creation functionality and enhance the display of posts, aligning with the PR objectives. However, there are a few areas that could be improved:
- Privacy concerns: Both the console log and the UI display full email addresses, which could be a privacy issue.
- User experience: The post creation process lacks visual feedback and error handling.
- Code structure: The mutation function could be more robust with proper error handling.
Addressing these points would significantly improve the overall quality and user-friendliness of the implementation. Despite these suggestions, the core functionality appears to be correctly implemented.
packages/plugins/trpc/tests/projects/nuxt-trpc-v11/schema.zmodel (2)
27-38
: LGTM: User model is well-structured with appropriate access controls.The User model is well-defined with proper fields and relations. The access control rules are appropriate, allowing user creation and self-management. Security is enhanced by using @password and @omit for the password field.
Consider adding a unique constraint to the email field for additional data integrity:
- email String @unique @email @length(6, 32) + email String @unique @email @length(6, 32) @db.VarChar(32)This change ensures that the database column type matches the length constraint and may improve query performance.
43-58
: LGTM: Post model is well-structured with appropriate access controls.The Post model is well-defined with proper fields, relations, and timestamps. The access control rules are appropriate, allowing read access for published posts to signed-in users and full access to the author.
Consider adding a length constraint to the content field to prevent excessively long posts:
- content String + content String @length(1, 10000)This change ensures that post content has a reasonable maximum length, which can help with database performance and prevent potential abuse.
packages/plugins/trpc/res/client/v10/utils.ts (1)
37-46
: LGTM! Well-implemented flexible property picker with a suggestion for improvement.The
PickFrom<T, K>
utility type is correctly implemented to provide flexible picking of properties based on the input typeT
and keysK
. It handles different scenarios effectively:
- Returns arrays unchanged.
- For objects, it either returns the full object (if all keys match or if no keys are provided) or picks the specified properties.
This implementation is more versatile than the standard
Pick
type.Consider adding type annotations to improve readability:
export type PickFrom<T, K extends Array<string>> = T extends Array<any> ? T : T extends Record<string, any> ? keyof T extends K[number] ? T : K[number] extends never ? T : Pick<T, Extract<keyof T, K[number]>> : T;This change explicitly ensures that we're only picking keys that exist in
T
, which might prevent potential type errors in some edge cases.packages/plugins/trpc/res/client/v10/nuxt.ts (1)
1-1
: Avoid disabling ESLint globally.Disabling ESLint for the entire file may hide potential issues. Consider enabling ESLint and disabling specific rules if necessary, or addressing the underlying linting errors.
packages/plugins/trpc/res/client/v11/nuxt.ts (1)
1-1
: Avoid disabling all ESLint rules for the entire file.Disabling ESLint entirely might mask potential issues and reduce code quality. Consider specifying only the necessary rules to disable.
You can modify the ESLint disable comment to target specific rules:
-/* eslint-disable */ +/* eslint-disable specific-rule-to-disable */This approach maintains the benefits of linting while suppressing only the rules that are not applicable.
packages/plugins/trpc/res/client/v11/utils.ts (5)
Line range hint
4-4
: Include 'bigint' in 'Primitive' typeConsider adding
bigint
to thePrimitive
type union to cover all JavaScript primitive types introduced in ES2020.Apply this diff:
-type Primitive = string | Function | number | boolean | Symbol | undefined | null; +type Primitive = string | Function | number | boolean | Symbol | undefined | null | bigint;
Line range hint
7-18
: Ensure type compatibility in 'DeepOverride'The
DeepOverride
type recursively merges typesT
andR
. To enhance type safety and handle edge cases, consider adding a conditional check to handle arrays and special object types likeDate
andRegExp
.Consider updating the
DeepOverride
type as follows:export type DeepOverride<T, R> = T extends Primitive ? R + : T extends Array<infer U> + ? R extends Array<infer V> + ? Array<DeepOverride<U, V>> + : R : R extends Primitive ? R : { [K in keyof T]: K extends keyof R ? DeepOverride<T[K], R[K]> : T[K]; } & { [K in Exclude<keyof R, keyof T>]: R[K]; };
Line range hint
29-36
: Review license compliance for copied utility typesThe utility types
KeysOf
andPickFrom
are noted as being from'trpc-nuxt'
. Copying code from external libraries may have licensing implications. Ensure that using this code aligns with the project's licensing terms. If possible, consider importing these utilities directly from'trpc-nuxt'
or implement your own versions.
Line range hint
20-27
: Improve readability of 'DeepOverrideAtPath'The
DeepOverrideAtPath
type is complex and may benefit from added clarity. Adding comments or breaking down the type into smaller, reusable types can enhance readability and maintainability.Consider refactoring the type definition for better understanding.
Line range hint
5-5
: Typographical correction in commentThere's a minor grammatical error in the comment. Changing "denoted" to "denoting" improves readability.
Apply this diff:
- * Traverse to `Path` (denoted by dot separated string literal type) in `T`, and starting from there, + * Traverse to `Path` (denoting a dot separated string literal type) in `T`, and starting from there,
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
⛔ Files ignored due to path filters (40)
packages/plugins/trpc/tests/projects/nuxt-trpc-v10/package-lock.json
is excluded by!**/package-lock.json
,!**/*.json
packages/plugins/trpc/tests/projects/nuxt-trpc-v10/package.json
is excluded by!**/*.json
packages/plugins/trpc/tests/projects/nuxt-trpc-v10/public/favicon.ico
is excluded by!**/*.ico
,!**/*.ico
packages/plugins/trpc/tests/projects/nuxt-trpc-v10/server/trpc/routers/generated/client/Post.nuxt.type.ts
is excluded by!**/generated/**
,!**/generated/**
packages/plugins/trpc/tests/projects/nuxt-trpc-v10/server/trpc/routers/generated/client/User.nuxt.type.ts
is excluded by!**/generated/**
,!**/generated/**
packages/plugins/trpc/tests/projects/nuxt-trpc-v10/server/trpc/routers/generated/client/nuxt.ts
is excluded by!**/generated/**
,!**/generated/**
packages/plugins/trpc/tests/projects/nuxt-trpc-v10/server/trpc/routers/generated/client/utils.ts
is excluded by!**/generated/**
,!**/generated/**
packages/plugins/trpc/tests/projects/nuxt-trpc-v10/server/trpc/routers/generated/helper.ts
is excluded by!**/generated/**
,!**/generated/**
packages/plugins/trpc/tests/projects/nuxt-trpc-v10/server/trpc/routers/generated/routers/Post.router.ts
is excluded by!**/generated/**
,!**/generated/**
packages/plugins/trpc/tests/projects/nuxt-trpc-v10/server/trpc/routers/generated/routers/User.router.ts
is excluded by!**/generated/**
,!**/generated/**
packages/plugins/trpc/tests/projects/nuxt-trpc-v10/server/trpc/routers/generated/routers/index.ts
is excluded by!**/generated/**
,!**/generated/**
packages/plugins/trpc/tests/projects/nuxt-trpc-v10/server/tsconfig.json
is excluded by!**/*.json
packages/plugins/trpc/tests/projects/nuxt-trpc-v10/tsconfig.json
is excluded by!**/*.json
packages/plugins/trpc/tests/projects/nuxt-trpc-v11/package-lock.json
is excluded by!**/package-lock.json
,!**/*.json
packages/plugins/trpc/tests/projects/nuxt-trpc-v11/package.json
is excluded by!**/*.json
packages/plugins/trpc/tests/projects/nuxt-trpc-v11/public/favicon.ico
is excluded by!**/*.ico
,!**/*.ico
packages/plugins/trpc/tests/projects/nuxt-trpc-v11/server/trpc/routers/generated/client/Post.nuxt.type.ts
is excluded by!**/generated/**
,!**/generated/**
packages/plugins/trpc/tests/projects/nuxt-trpc-v11/server/trpc/routers/generated/client/User.nuxt.type.ts
is excluded by!**/generated/**
,!**/generated/**
packages/plugins/trpc/tests/projects/nuxt-trpc-v11/server/trpc/routers/generated/client/nuxt.ts
is excluded by!**/generated/**
,!**/generated/**
packages/plugins/trpc/tests/projects/nuxt-trpc-v11/server/trpc/routers/generated/client/utils.ts
is excluded by!**/generated/**
,!**/generated/**
packages/plugins/trpc/tests/projects/nuxt-trpc-v11/server/trpc/routers/generated/helper.ts
is excluded by!**/generated/**
,!**/generated/**
packages/plugins/trpc/tests/projects/nuxt-trpc-v11/server/trpc/routers/generated/routers/Post.router.ts
is excluded by!**/generated/**
,!**/generated/**
packages/plugins/trpc/tests/projects/nuxt-trpc-v11/server/trpc/routers/generated/routers/User.router.ts
is excluded by!**/generated/**
,!**/generated/**
packages/plugins/trpc/tests/projects/nuxt-trpc-v11/server/trpc/routers/generated/routers/index.ts
is excluded by!**/generated/**
,!**/generated/**
packages/plugins/trpc/tests/projects/nuxt-trpc-v11/server/tsconfig.json
is excluded by!**/*.json
packages/plugins/trpc/tests/projects/nuxt-trpc-v11/tsconfig.json
is excluded by!**/*.json
packages/plugins/trpc/tests/projects/t3-trpc-v10/src/server/api/routers/generated/client/Post.next.type.ts
is excluded by!**/generated/**
,!**/generated/**
packages/plugins/trpc/tests/projects/t3-trpc-v10/src/server/api/routers/generated/client/User.next.type.ts
is excluded by!**/generated/**
,!**/generated/**
packages/plugins/trpc/tests/projects/t3-trpc-v10/src/server/api/routers/generated/client/next.ts
is excluded by!**/generated/**
,!**/generated/**
packages/plugins/trpc/tests/projects/t3-trpc-v10/src/server/api/routers/generated/client/utils.ts
is excluded by!**/generated/**
,!**/generated/**
packages/plugins/trpc/tests/projects/t3-trpc-v10/src/server/api/routers/generated/routers/Post.router.ts
is excluded by!**/generated/**
,!**/generated/**
packages/plugins/trpc/tests/projects/t3-trpc-v10/src/server/api/routers/generated/routers/User.router.ts
is excluded by!**/generated/**
,!**/generated/**
packages/plugins/trpc/tests/projects/t3-trpc-v10/src/server/api/routers/generated/routers/index.ts
is excluded by!**/generated/**
,!**/generated/**
packages/plugins/trpc/tests/projects/t3-trpc-v11/src/server/api/routers/generated/client/Post.react.type.ts
is excluded by!**/generated/**
,!**/generated/**
packages/plugins/trpc/tests/projects/t3-trpc-v11/src/server/api/routers/generated/client/User.react.type.ts
is excluded by!**/generated/**
,!**/generated/**
packages/plugins/trpc/tests/projects/t3-trpc-v11/src/server/api/routers/generated/client/react.ts
is excluded by!**/generated/**
,!**/generated/**
packages/plugins/trpc/tests/projects/t3-trpc-v11/src/server/api/routers/generated/client/utils.ts
is excluded by!**/generated/**
,!**/generated/**
packages/plugins/trpc/tests/projects/t3-trpc-v11/src/server/api/routers/generated/routers/Post.router.ts
is excluded by!**/generated/**
,!**/generated/**
packages/plugins/trpc/tests/projects/t3-trpc-v11/src/server/api/routers/generated/routers/User.router.ts
is excluded by!**/generated/**
,!**/generated/**
packages/plugins/trpc/tests/projects/t3-trpc-v11/src/server/api/routers/generated/routers/index.ts
is excluded by!**/generated/**
,!**/generated/**
📒 Files selected for processing (43)
- packages/plugins/trpc/res/client/v10/next.ts (0 hunks)
- packages/plugins/trpc/res/client/v10/nuxt.ts (1 hunks)
- packages/plugins/trpc/res/client/v10/react.ts (0 hunks)
- packages/plugins/trpc/res/client/v10/utils.ts (1 hunks)
- packages/plugins/trpc/res/client/v11/next.ts (0 hunks)
- packages/plugins/trpc/res/client/v11/nuxt.ts (1 hunks)
- packages/plugins/trpc/res/client/v11/react.ts (0 hunks)
- packages/plugins/trpc/res/client/v11/utils.ts (0 hunks)
- packages/plugins/trpc/res/client/v11/utils.ts (1 hunks)
- packages/plugins/trpc/src/client-helper/index.ts (1 hunks)
- packages/plugins/trpc/src/client-helper/next.ts (1 hunks)
- packages/plugins/trpc/src/client-helper/nuxt.ts (1 hunks)
- packages/plugins/trpc/src/client-helper/react.ts (1 hunks)
- packages/plugins/trpc/src/generator.ts (7 hunks)
- packages/plugins/trpc/src/helpers.ts (0 hunks)
- packages/plugins/trpc/src/utils.ts (1 hunks)
- packages/plugins/trpc/tests/nuxt.test.ts (1 hunks)
- packages/plugins/trpc/tests/projects/nuxt-trpc-v10/.gitignore (1 hunks)
- packages/plugins/trpc/tests/projects/nuxt-trpc-v10/README.md (1 hunks)
- packages/plugins/trpc/tests/projects/nuxt-trpc-v10/app.vue (1 hunks)
- packages/plugins/trpc/tests/projects/nuxt-trpc-v10/nuxt.config.ts (1 hunks)
- packages/plugins/trpc/tests/projects/nuxt-trpc-v10/plugins/client.ts (1 hunks)
- packages/plugins/trpc/tests/projects/nuxt-trpc-v10/prisma/schema.prisma (1 hunks)
- packages/plugins/trpc/tests/projects/nuxt-trpc-v10/schema.zmodel (1 hunks)
- packages/plugins/trpc/tests/projects/nuxt-trpc-v10/server/api/trpc/[trpc].ts (1 hunks)
- packages/plugins/trpc/tests/projects/nuxt-trpc-v10/server/db.ts (1 hunks)
- packages/plugins/trpc/tests/projects/nuxt-trpc-v10/server/trpc/context.ts (1 hunks)
- packages/plugins/trpc/tests/projects/nuxt-trpc-v10/server/trpc/routers/index.ts (1 hunks)
- packages/plugins/trpc/tests/projects/nuxt-trpc-v10/server/trpc/trpc.ts (1 hunks)
- packages/plugins/trpc/tests/projects/nuxt-trpc-v11/.gitignore (1 hunks)
- packages/plugins/trpc/tests/projects/nuxt-trpc-v11/README.md (1 hunks)
- packages/plugins/trpc/tests/projects/nuxt-trpc-v11/app.vue (1 hunks)
- packages/plugins/trpc/tests/projects/nuxt-trpc-v11/nuxt.config.ts (1 hunks)
- packages/plugins/trpc/tests/projects/nuxt-trpc-v11/plugins/client.ts (1 hunks)
- packages/plugins/trpc/tests/projects/nuxt-trpc-v11/prisma/schema.prisma (1 hunks)
- packages/plugins/trpc/tests/projects/nuxt-trpc-v11/schema.zmodel (1 hunks)
- packages/plugins/trpc/tests/projects/nuxt-trpc-v11/server/api/trpc/[trpc].ts (1 hunks)
- packages/plugins/trpc/tests/projects/nuxt-trpc-v11/server/db.ts (1 hunks)
- packages/plugins/trpc/tests/projects/nuxt-trpc-v11/server/trpc/context.ts (1 hunks)
- packages/plugins/trpc/tests/projects/nuxt-trpc-v11/server/trpc/routers/generated-router-helper.ts (1 hunks)
- packages/plugins/trpc/tests/projects/nuxt-trpc-v11/server/trpc/routers/index.ts (1 hunks)
- packages/plugins/trpc/tests/projects/nuxt-trpc-v11/server/trpc/trpc.ts (1 hunks)
- packages/plugins/trpc/tests/projects/t3-trpc-v10/src/pages/index.tsx (1 hunks)
💤 Files with no reviewable changes (5)
- packages/plugins/trpc/res/client/v10/next.ts
- packages/plugins/trpc/res/client/v10/react.ts
- packages/plugins/trpc/res/client/v11/next.ts
- packages/plugins/trpc/res/client/v11/react.ts
- packages/plugins/trpc/src/helpers.ts
✅ Files skipped from review due to trivial changes (7)
- packages/plugins/trpc/tests/projects/nuxt-trpc-v10/.gitignore
- packages/plugins/trpc/tests/projects/nuxt-trpc-v10/prisma/schema.prisma
- packages/plugins/trpc/tests/projects/nuxt-trpc-v10/server/db.ts
- packages/plugins/trpc/tests/projects/nuxt-trpc-v11/.gitignore
- packages/plugins/trpc/tests/projects/nuxt-trpc-v11/prisma/schema.prisma
- packages/plugins/trpc/tests/projects/nuxt-trpc-v11/server/db.ts
- packages/plugins/trpc/tests/projects/nuxt-trpc-v11/server/trpc/routers/generated-router-helper.ts
🧰 Additional context used
🪛 GitHub Check: CodeQL
packages/plugins/trpc/src/utils.ts
[warning] 141-141: Overly permissive regular expression range
Suspicious character range that is equivalent to [A-Z\[\\\]^_`a-z].
[failure] 141-141: Inefficient regular expression
This part of the regular expression may cause exponential backtracking on strings starting with '@@Gen.A(' and containing many repetitions of 'a'.
[failure] 143-143: Inefficient regular expression
This part of the regular expression may cause exponential backtracking on strings starting with '(A:' and containing many repetitions of 'a'.
[failure] 147-147: Polynomial regular expression used on uncontrolled data
This regular expression that depends on library input may run slow on strings with many repetitions of '@@gen.'.
This regular expression that depends on library input may run slow on strings starting with '@@Gen.A(' and with many repetitions of 'a'.
[failure] 148-148: Polynomial regular expression used on uncontrolled data
This regular expression that depends on library input may run slow on strings with many repetitions of '.'.
[failure] 150-150: Polynomial regular expression used on uncontrolled data
This regular expression that depends on library input may run slow on strings with many repetitions of '('.
This regular expression that depends on library input may run slow on strings starting with '(A:' and with many repetitions of 'a'.
🔇 Additional comments (52)
packages/plugins/trpc/tests/projects/nuxt-trpc-v11/server/trpc/routers/index.ts (3)
1-1
: LGTM: Clear and purposeful import statement.The import statement is well-structured, using a relative path and providing a descriptive name for the imported function. This aligns well with the PR's objective of supporting TRPC in Nuxt projects.
3-3
: LGTM: Proper creation and export of the TRPC router.The
appRouter
is correctly created using the importedcreateCRUDRouter
function and exported for use in the application. This setup is essential for integrating TRPC with Nuxt and aligns with the PR objectives.
1-6
: Overall: Excellent implementation of TRPC router setup for Nuxt.This file successfully sets up a TRPC router for a Nuxt project, aligning perfectly with the PR objectives. The code is concise, clear, and follows best practices for TypeScript and TRPC integration. It provides the necessary exports for both the router and its type, enabling proper usage and type safety throughout the application.
Great job on implementing this crucial part of the TRPC-Nuxt integration!
packages/plugins/trpc/tests/projects/nuxt-trpc-v10/nuxt.config.ts (1)
5-7
: LGTM! Correct configuration for transpiling 'trpc-nuxt'.The inclusion of 'trpc-nuxt' in the
build.transpile
array is correct and aligns with the PR objectives. This configuration ensures that the 'trpc-nuxt' package is properly transpiled during the build process, which is essential for its integration with Nuxt.js.packages/plugins/trpc/tests/projects/nuxt-trpc-v11/nuxt.config.ts (2)
3-3
: Verify the intention behind the future compatibility date.The
compatibilityDate
is set to '2024-04-03', which is in the future. While this might be intentional for testing purposes or to ensure compatibility with upcoming Nuxt features, it could potentially lead to unexpected behavior or errors if the code relies on features not yet implemented.Could you confirm if this future date is intentional? If not, consider setting it to a current or recent date.
5-7
: Build configuration looks good.The build configuration correctly specifies transpilation for 'trpc-nuxt', which is necessary for proper integration of tRPC with Nuxt. This aligns well with the PR objectives of supporting client helpers for Nuxt with tRPC.
packages/plugins/trpc/tests/projects/nuxt-trpc-v10/server/api/trpc/[trpc].ts (1)
1-3
: LGTM: Imports are correct and aligned with PR objectives.The imports are appropriate for setting up a TRPC API handler in a Nuxt environment. The use of
trpc-nuxt
aligns with the PR objective of supporting client helpers for Nuxt.packages/plugins/trpc/tests/projects/nuxt-trpc-v11/server/api/trpc/[trpc].ts (2)
1-3
: LGTM: Imports are correctly set up for Nuxt TRPC integrationThe imports are well-structured and align with the PR objectives of supporting client helpers for Nuxt:
createNuxtApiHandler
from 'trpc-nuxt' is correctly imported to set up the TRPC API handler in a Nuxt environment.appRouter
andcreateContext
are imported from relative paths, indicating a modular project structure.This setup provides a solid foundation for integrating TRPC with Nuxt.
1-9
: Overall: Excellent implementation of TRPC API handler for NuxtThis file successfully implements a TRPC API handler for a Nuxt application, aligning perfectly with the PR objectives of supporting client helpers for Nuxt. Key points:
- Correct usage of 'trpc-nuxt' package.
- Proper import and use of
appRouter
andcreateContext
.- Concise and clear implementation of the API handler.
The code demonstrates a good understanding of both TRPC and Nuxt, providing a solid foundation for integrating TRPC functionalities within Nuxt applications. This implementation will greatly enhance the developer experience for those using TRPC in a Nuxt environment.
packages/plugins/trpc/tests/projects/nuxt-trpc-v10/server/trpc/routers/index.ts (2)
6-7
: LGTM! Good practice for type-safe usage.Exporting the
AppRouter
type is an excellent practice. It enables type-safe usage of the router throughout the application and ensures that the type definition stays in sync with the actual router implementation.The comment on line 6 provides a clear explanation of what's being exported, which is helpful for other developers.
1-7
: Overall, excellent implementation aligning with PR objectives.This file successfully sets up a TRPC router for a Nuxt.js project, which aligns well with the PR objectives of supporting client helpers for Nuxt in TRPC. The implementation follows TRPC conventions and good TypeScript practices, providing a solid foundation for integrating TRPC with Nuxt.js projects.
Key points:
- Appropriate imports from local and generated modules.
- Creation of an
appRouter
using CRUD operations.- Export of the
AppRouter
type for type-safe usage.These changes contribute to enhancing the developer experience when using TRPC with Nuxt, as outlined in the linked issue #1761.
packages/plugins/trpc/tests/projects/nuxt-trpc-v10/server/trpc/context.ts (3)
1-2
: LGTM: Imports are correct and necessary.The imports are appropriate for the context of this file.
inferAsyncReturnType
is used for type inference, andprisma
is imported for database access.
12-12
: LGTM:Context
type is correctly defined.The
Context
type is properly defined usinginferAsyncReturnType
. This ensures type safety and automatic updates ifcreateContext
changes.
1-12
: Overall implementation is solid and follows TRPC best practices.This file successfully sets up the context for a TRPC server in a Nuxt project. It provides:
- Correct imports
- A well-documented
createContext
function- A type-safe
Context
definitionThe implementation is concise, type-safe, and aligns well with TRPC patterns. It fulfills the PR objective of supporting client helpers for Nuxt in the TRPC plugin.
packages/plugins/trpc/tests/projects/nuxt-trpc-v11/server/trpc/context.ts (2)
1-2
: LGTM: Imports are correct and necessary.The imports are appropriate for the file's purpose.
inferAsyncReturnType
is used for type inference, andprisma
is used for database access in the context.
12-12
: LGTM:Context
type is correctly defined and exported.The
Context
type is properly defined usinginferAsyncReturnType
, which ensures type safety when using the context throughout the application. Exporting this type allows for consistent usage across different files.packages/plugins/trpc/tests/projects/nuxt-trpc-v10/plugins/client.ts (1)
1-23
: Overall, excellent implementation of TRPC client integration for Nuxt!This plugin successfully achieves the goal of integrating TRPC with Nuxt, as outlined in the PR objectives. It provides a well-structured and type-safe way to use TRPC in a Nuxt application. The implementation follows best practices and conventions, making it a valuable addition to the project.
The suggestions provided in the review are minor and aimed at further improving type safety and error handling. Great job on this implementation!
packages/plugins/trpc/tests/projects/nuxt-trpc-v11/plugins/client.ts (2)
1-3
: LGTM: Imports are well-structured and maintain type safety.The imports are appropriate for setting up a TRPC client in a Nuxt environment. The use of the
AppRouter
type import ensures type safety throughout the client setup.
1-23
: Summary: Successfully implements TRPC client integration for NuxtThis file effectively creates a Nuxt plugin that integrates a TRPC client, aligning well with the PR objectives of supporting client helpers for Nuxt. The implementation is type-safe, follows best practices, and provides a solid foundation for using TRPC in a Nuxt environment.
Key points:
- Proper use of Nuxt plugin architecture
- Type-safe TRPC client creation
- Efficient API communication with
httpBatchLink
- Client provided to the Nuxt application for easy access
The suggested improvements (configurable API URL, enhanced comments, and explicit type annotations) are minor and aimed at increasing flexibility and clarity.
This implementation successfully bridges the gap between TRPC and Nuxt, providing the necessary client types when using the "trpc-nuxt" package, as outlined in the PR objectives.
packages/plugins/trpc/src/client-helper/next.ts (2)
1-5
: LGTM: Imports are appropriate and well-structured.The imports from 'ts-morph' and './react' are correctly defined. Renaming the imported functions with 'ForReact' suffix helps distinguish them from the exported functions, improving code readability.
1-21
: Great implementation: Efficiently extends tRPC client helpers to Next.jsThis file successfully implements client helpers for Next.js by leveraging existing React implementations. The approach is efficient, reduces code duplication, and aligns well with the PR objectives of supporting client helpers for additional frameworks.
Key points:
- Reuses React implementations, following the DRY principle.
- Clear and concise code structure.
- Consistent naming conventions and file organization.
This implementation provides a solid foundation for supporting tRPC client helpers in Next.js projects.
packages/plugins/trpc/tests/projects/nuxt-trpc-v10/README.md (2)
1-3
: LGTM: Clear and concise introductionThe introduction provides a clear title and a helpful link to the Nuxt 3 documentation for further reading.
23-39
: LGTM: Clear development server instructionsThe development server section provides clear instructions for starting the server using various package managers. The inclusion of the server address (http://localhost:3000) is helpful for users.
packages/plugins/trpc/tests/projects/nuxt-trpc-v11/README.md (2)
1-3
: LGTM: Concise and informative introductionThe introduction clearly identifies the project and provides a helpful link to the Nuxt 3 documentation for further reading.
23-39
: LGTM: Clear development server instructionsThe Development Server section provides correct commands for starting the server using different package managers. The inclusion of the server URL (
http://localhost:3000
) is helpful for users.packages/plugins/trpc/tests/projects/nuxt-trpc-v10/app.vue (3)
1-5
: LGTM: Proper setup of TRPC client and queryThe TRPC client is correctly initialized using the Nuxt app, and the query to fetch posts with their authors is set up appropriately.
7-7
: LGTM: Mutation setup for post creationThe mutation for creating new posts is correctly set up using the TRPC client.
32-40
: LGTM: Template structure and data bindingThe template correctly renders the list of posts and provides a button to create new posts. The use of
v-for
with a:key
binding is a good practice for list rendering in Vue.packages/plugins/trpc/tests/projects/nuxt-trpc-v11/app.vue (2)
1-5
: LGTM: Proper use of Nuxt and tRPC clientThe use of
useNuxtApp()
to access the tRPC client and thefindMany
query with includedauthor
data aligns well with the PR objective of supporting Nuxt and demonstrates efficient data fetching.
32-40
: LGTM: Clear and concise template structureThe template structure is clear and concise. The use of
v-for
with a:key
for the list of posts is correct, and the button is properly connected to theonCreate
function.packages/plugins/trpc/tests/projects/nuxt-trpc-v10/schema.zmodel (3)
6-13
: LGTM: Appropriate datasource and generator configurationThe datasource and generator configurations are well-suited for a development environment. Using SQLite with a local file is perfect for testing and development purposes, while the Prisma Client JS generator is the correct choice for TypeScript/JavaScript projects.
15-19
: LGTM: trpc plugin configuration aligns with PR objectivesThe trpc plugin configuration is well-structured for the project's needs:
- The custom provider path is suitable for local development.
- The output path is correctly set to generate routers in the server directory.
- The
generateClientHelpers
option set to 'nuxt' directly addresses the PR's main objective of supporting client helpers for Nuxt with TRPC.This configuration effectively implements the feature request from issue #1761.
1-55
: Excellent schema implementation, fully aligned with PR objectivesThis schema file is well-structured and successfully implements the requirements for supporting TRPC with Nuxt:
- The datasource and generator configurations are appropriate for development.
- The trpc plugin is correctly configured to generate client helpers for Nuxt, addressing the main objective of the PR.
- The User and Post models are well-defined with appropriate fields, validations, and access control rules.
- The schema follows best practices for Prisma and ZenStack.
The implementation effectively addresses the feature request from issue #1761, providing a solid foundation for generating client helpers for TRPC when used with the Nuxt framework.
Great job on this implementation! The schema is clean, well-organized, and meets all the requirements outlined in the PR objectives.
packages/plugins/trpc/tests/projects/t3-trpc-v10/src/pages/index.tsx (1)
12-13
: LGTM: Addition of createPost mutationThe addition of the
createPost
mutation usingapi.post.post.create.useMutation()
is well-implemented and aligns with the PR's objective of supporting client helpers for Nuxt.packages/plugins/trpc/tests/projects/nuxt-trpc-v11/schema.zmodel (4)
6-9
: LGTM: Data source configuration is appropriate for development.The SQLite data source configuration is well-defined and suitable for a development or testing environment. Using a local file (
dev.db
) as the database is a common practice for such scenarios.
11-13
: LGTM: Generator configuration is correct for Prisma Client.The generator configuration correctly specifies the use of "prisma-client-js", which is appropriate for generating the Prisma client in a JavaScript/TypeScript environment.
15-22
: LGTM: tRPC plugin configuration aligns with PR objectives.The tRPC plugin configuration is well-defined and directly supports the PR's goal of implementing client helpers for Nuxt. Key points:
- The
generateClientHelpers
option is correctly set to 'nuxt'.- Import paths and output directory are appropriately configured for the project structure.
- The specified version (v11) matches the project requirements.
This configuration should enable the generation of the necessary client types for TRPC when used with the Nuxt framework, as requested in issue #1761.
1-58
: Overall: Excellent schema design that fulfills PR objectives.This schema file provides a robust foundation for a Nuxt.js application with tRPC integration. It successfully addresses the PR objectives by:
- Configuring the tRPC plugin to generate client helpers for Nuxt.
- Defining appropriate data models (User and Post) with well-thought-out fields and relations.
- Implementing sensible access control rules using ZenStack's @@Allow directives.
The schema is well-structured, follows best practices, and should effectively support the integration of TRPC with Nuxt as requested in issue #1761.
packages/plugins/trpc/tests/nuxt.test.ts (1)
1-17
: LGTM: Proper test setup and working directory management.The import statements, test suite setup, and working directory management are well-structured. The use of
beforeEach
andafterEach
hooks ensures that each test runs in isolation, preventing potential interference between tests.packages/plugins/trpc/res/client/v10/utils.ts (2)
34-35
: LGTM! Well-defined utility type for key extraction.The
KeysOf<T>
utility type is correctly implemented to create an array of string keys from the given typeT
. This can be particularly useful when working with object types and needing to manipulate or iterate over their keys.
33-46
: Summary: Valuable additions for type manipulation in TRPC-Nuxt integrationThe new utility types
KeysOf
andPickFrom
are excellent additions to the codebase. They provide powerful type manipulation capabilities that will be particularly useful in generating and working with client types for TRPC in a Nuxt environment. These additions align well with the PR objectives of supporting client helpers for Nuxt and will contribute to a smoother integration of TRPC with Nuxt applications.packages/plugins/trpc/res/client/v10/nuxt.ts (1)
7-12
: Function implementation is correct.The
createTRPCNuxtClient
function properly wraps_createTRPCNuxtClient
and applies the type assertion withDeepOverrideAtPath
, enhancing type safety for Nuxt.js applications.packages/plugins/trpc/res/client/v11/nuxt.ts (1)
7-12
: FunctioncreateTRPCNuxtClient
implementation looks correct.The function correctly wraps
_createTRPCNuxtClient
and applies the necessary type casting for enhanced type safety in a Nuxt.js context.packages/plugins/trpc/res/client/v11/utils.ts (1)
1-1
:⚠️ Potential issueIncorrect import statement syntax
The line
../v10/utils.ts
is not a valid TypeScript import statement. If you intend to import utilities from../v10/utils.ts
, please use the properimport
syntax.Apply this diff to fix the import statement:
-../v10/utils.ts +import * as utils from '../v10/utils';Or, if this line is unnecessary, consider removing it.
Likely invalid or redundant comment.
packages/plugins/trpc/src/client-helper/react.ts (1)
1-3
: Ensure correct import path forgetPrismaOperationTypes
.On line 3~, the import statement:
import { getPrismaOperationTypes } from '.';imports from the current directory's
index
file. Please confirm thatgetPrismaOperationTypes
is exported from theindex.ts
in the current directory. If not, consider specifying the correct relative path to the module.packages/plugins/trpc/src/client-helper/index.ts (1)
62-62
:⚠️ Potential issueEnsure 'clientType' is a valid key before accessing 'helpers[clientType]'
In line 62, the code accesses
helpers[clientType].generateProcedureTyping(...)
. To prevent potential runtime errors, add validation to ensure thatclientType
is a valid key in thehelpers
object before accessing it.Here's a script to verify the validity of
clientType
values:packages/plugins/trpc/src/generator.ts (6)
17-20
: Correct Import of Client Helper FunctionsThe import statements for
createClientHelperEntries
andgenerateClientTypingForModel
from./client-helper
ensure that the necessary functions for client helper generation are properly included.
23-30
: Proper Import of Supported Client Helpers and UtilitiesImporting
AllSupportedClientHelpers
andSupportedClientHelpers
from./utils
correctly brings in the types and constants required for validating and handling supported client helpers.
97-97
: Type Casting of 'generateClientHelpers'Casting
generateClientHelpers
toSupportedClientHelpers[] | undefined
is appropriate here since you've validated its contents earlier. This ensures type safety when passing it to thecreateAppRouter
function.
249-255
: Correct Invocation of 'createClientHelperEntries'The function
createClientHelperEntries
is properly called with the correct parameters, ensuring client helper entries are generated whengenerateClientHelpers
is defined.
337-338
: Initialization of 'generateOperations' ArrayThe
generateOperations
array is correctly initialized to collect operation details for client helper generation, which aids in maintaining accurate typing information.
369-378
: Proper Generation of Client Typings for ModelsThe
generateClientTypingForModel
function is correctly invoked to generate client typings for the specified model. This enhances type safety and ensures consistency across the codebase.
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
🧹 Outside diff range and nitpick comments (2)
packages/plugins/trpc/tests/projects/t3-trpc-v11/src/app/_components/post.tsx (1)
24-24
: Approve change, but consider further improvementsThe addition of optional chaining (
?.
) improves the robustness of the code. However, consider the following suggestions:
Since this is a
useSuspenseQuery
,latestPost1
should always be defined unless there's an error. You might want to add error handling if that's a concern.If this
console.log
is for debugging, consider removing it before merging to production or wrapping it in a development-only check.To improve type safety, you could add a type assertion for
latestPost1
:console.log((latestPost1 as NonNullable<typeof latestPost1>).author.email);This assumes
latestPost1
is always defined and allows you to safely accessauthor.email
without optional chaining.packages/plugins/trpc/src/client-helper/nuxt.ts (1)
21-25
: Consider renaming parameters for clarityThe parameters
opType
andbaseOpType
have similar names but represent different concepts, which might lead to confusion. Renaming them to more descriptive names can improve code readability.For example:
export function generateProcedureTyping( writer: CodeBlockWriter, - opType: string, + prismaOpType: string, modelName: string, - baseOpType: string, + trpcOpName: string, _version: string ) { - const procType = getProcedureTypeByOpName(baseOpType); - const { genericBase, argsType, argsOptional, resultType } = getPrismaOperationTypes(modelName, opType); + const procType = getProcedureTypeByOpName(trpcOpName); + const { genericBase, argsType, argsOptional, resultType } = getPrismaOperationTypes(modelName, prismaOpType);This makes it clearer that
prismaOpType
refers to the Prisma operation type, whiletrpcOpName
relates to the TRPC operation name.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
⛔ Files ignored due to path filters (8)
packages/plugins/trpc/tests/projects/nuxt-trpc-v10/server/trpc/routers/generated/client/Post.nuxt.type.ts
is excluded by!**/generated/**
,!**/generated/**
packages/plugins/trpc/tests/projects/nuxt-trpc-v10/server/trpc/routers/generated/client/User.nuxt.type.ts
is excluded by!**/generated/**
,!**/generated/**
packages/plugins/trpc/tests/projects/nuxt-trpc-v11/server/trpc/routers/generated/client/Post.nuxt.type.ts
is excluded by!**/generated/**
,!**/generated/**
packages/plugins/trpc/tests/projects/nuxt-trpc-v11/server/trpc/routers/generated/client/User.nuxt.type.ts
is excluded by!**/generated/**
,!**/generated/**
packages/plugins/trpc/tests/projects/t3-trpc-v10/src/server/api/routers/generated/client/Post.next.type.ts
is excluded by!**/generated/**
,!**/generated/**
packages/plugins/trpc/tests/projects/t3-trpc-v10/src/server/api/routers/generated/client/User.next.type.ts
is excluded by!**/generated/**
,!**/generated/**
packages/plugins/trpc/tests/projects/t3-trpc-v11/src/server/api/routers/generated/client/Post.react.type.ts
is excluded by!**/generated/**
,!**/generated/**
packages/plugins/trpc/tests/projects/t3-trpc-v11/src/server/api/routers/generated/client/User.react.type.ts
is excluded by!**/generated/**
,!**/generated/**
📒 Files selected for processing (7)
- packages/plugins/trpc/src/client-helper/index.ts (1 hunks)
- packages/plugins/trpc/src/client-helper/nuxt.ts (1 hunks)
- packages/plugins/trpc/src/client-helper/react.ts (1 hunks)
- packages/plugins/trpc/src/utils.ts (1 hunks)
- packages/plugins/trpc/tests/projects/nuxt-trpc-v10/app.vue (1 hunks)
- packages/plugins/trpc/tests/projects/nuxt-trpc-v11/app.vue (1 hunks)
- packages/plugins/trpc/tests/projects/t3-trpc-v11/src/app/_components/post.tsx (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (5)
- packages/plugins/trpc/src/client-helper/index.ts
- packages/plugins/trpc/src/client-helper/react.ts
- packages/plugins/trpc/src/utils.ts
- packages/plugins/trpc/tests/projects/nuxt-trpc-v10/app.vue
- packages/plugins/trpc/tests/projects/nuxt-trpc-v11/app.vue
🧰 Additional context used
if (procType === 'query') { | ||
writer.writeLine(` | ||
query: <T extends ${genericBase}>(input${inputOptional}: ${argsType}) => Promise<${resultType}>; | ||
useQuery: <T extends ${genericBase}, ResT = ${resultType}, DataE = ${errorType}, DataT = ResT, PickKeys extends KeysOf<DataT> = KeysOf<DataT>, DefaultT = null>(input${inputOptional}: MaybeRefOrGetter<${argsType}>, opts?: Omit<AsyncDataOptions<ResT, DataT, PickKeys, DefaultT>, 'watch'> & { | ||
trpc?: TRPCRequestOptions; | ||
queryKey?: string; | ||
watch?: AsyncDataOptions<ResT, DataT, PickKeys, DefaultT>['watch'] | false; | ||
}) => AsyncData<PickFrom<DataT, PickKeys> | DefaultT, DataE>; | ||
useLazyQuery: <T extends ${genericBase}, ResT = ${resultType}, DataE = ${errorType}, DataT = ResT, PickKeys extends KeysOf<DataT> = KeysOf<DataT>, DefaultT = null>(input${inputOptional}: MaybeRefOrGetter<${argsType}>, opts?: Omit<AsyncDataOptions<ResT, DataT, PickKeys, DefaultT>, 'lazy' | 'watch'> & { | ||
trpc?: TRPCRequestOptions; | ||
queryKey?: string; | ||
watch?: AsyncDataOptions<ResT, DataT, PickKeys, DefaultT>['watch'] | false; | ||
}) => AsyncData<PickFrom<DataT, PickKeys> | DefaultT, DataE>; | ||
`); | ||
} else if (procType === 'mutation') { | ||
writer.writeLine(` | ||
mutate: <T extends ${genericBase}>(input${inputOptional}: ${argsType}) => Promise<${resultType}>; | ||
useMutation: <T extends ${genericBase}, ResT = ${resultType}, DataE = ${errorType}, DataT = ResT, PickKeys extends KeysOf<DataT> = KeysOf<DataT>, DefaultT = null>(opts?: Omit<AsyncDataOptions<ResT, DataT, PickKeys, DefaultT>, 'lazy'> & { | ||
trpc?: TRPCRequestOptions; | ||
}) => AsyncData<PickFrom<DataT, PickKeys> | DefaultT, DataE> & { | ||
mutate: <T extends ${genericBase}, ResT = ${resultType}, DataE = ${errorType}, DataT = ResT, PickKeys extends KeysOf<DataT> = KeysOf<DataT>>(input${inputOptional}: ${argsType}) => Promise<UnwrapRef<AsyncData<PickFrom<DataT, PickKeys> | null, DataE>['data']>>; | ||
}; | ||
`); | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion
Refactor to eliminate code duplication between 'query' and 'mutation' cases
The code within the if (procType === 'query')
and else if (procType === 'mutation')
blocks is similar, with variations in the generated code strings. To enhance maintainability and reduce repetition, consider refactoring by creating a helper function that handles the shared logic and accepts parameters for the differences.
Here's an example of how you might abstract the common code:
writer.block(() => {
- if (procType === 'query') {
- writer.writeLine(`
- // Code for query
- `);
- } else if (procType === 'mutation') {
- writer.writeLine(`
- // Code for mutation
- `);
- }
+ generateProcedureCode(procType);
});
+function generateProcedureCode(procType: string) {
+ let codeString = '';
+ if (procType === 'query') {
+ codeString = `
+ // Refactored code for query
+ `;
+ } else if (procType === 'mutation') {
+ codeString = `
+ // Refactored code for mutation
+ `;
+ }
+ writer.writeLine(codeString);
+}
This approach reduces duplication and makes future modifications easier.
Committable suggestion was skipped due to low confidence.
Fixes #1761