Skip to content

feat: add elysiajs #2114

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

Open
wants to merge 1 commit into
base: dev
Choose a base branch
from

Conversation

rodrigoburigool
Copy link

Add Elysia adapter

Copy link
Contributor

coderabbitai bot commented May 9, 2025

📝 Walkthrough

Walkthrough

A new Elysia middleware handler is introduced for integrating ZenStack's RPC API with Prisma, including error handling and schema loading. An index file re-exports the handler, and a comprehensive test suite is added to validate both RPC and REST handler behaviors using Elysia, Prisma, and Zod schemas.

Changes

File(s) Change Summary
packages/server/src/elysia/handler.ts Introduces ElysiaOptions interface and createElysiaHandler function for Elysia middleware, handling RPC API requests with Prisma.
packages/server/src/elysia/index.ts Adds a re-export of all exports from the handler module for simplified imports.
packages/server/tests/adapter/elysia.test.ts Adds integration tests for the Elysia adapter, covering RPC and REST handlers, CRUD operations, and schema loading.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant ElysiaApp
    participant Middleware
    participant Prisma
    participant RPCApiHandler

    Client->>ElysiaApp: HTTP Request (any method/path)
    ElysiaApp->>Middleware: Passes request to catch-all handler
    Middleware->>Prisma: getPrisma(context)
    alt Prisma client unavailable
        Middleware-->>Client: 500 Error (Prisma client not found)
    else Path missing
        Middleware-->>Client: 400 Error (Path missing)
    else
        Middleware->>RPCApiHandler: method, path, query, body, Prisma, metadata, schemas
        RPCApiHandler-->>Middleware: { status, body }
        Middleware-->>Client: Response with status and body
    end
Loading

Possibly related PRs

  • zenstackhq/zenstack#1739: Implements a similar adapter handler for the Hono framework, using analogous middleware and RPC API integration logic as in this Elysia adapter PR.

Tip

⚡️ Faster reviews with caching
  • CodeRabbit now supports caching for code and dependencies, helping speed up reviews. This means quicker feedback, reduced wait times, and a smoother review experience overall. Cached data is encrypted and stored securely. This feature will be automatically enabled for all accounts on May 16th. To opt out, configure Review - Disable Cache at either the organization or repository level. If you prefer to disable all data retention across your organization, simply turn off the Data Retention setting under your Organization Settings.

Enjoy the performance boost—your workflow just got faster.

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

‼️ IMPORTANT
Auto-reply has been disabled for this repository in the CodeRabbit settings. The CodeRabbit bot will not respond to your replies unless it is explicitly tagged.

  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

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

Other keywords and placeholders

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

CodeRabbit Configuration File (.coderabbit.yaml)

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

Documentation and Community

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

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (2)
packages/server/src/elysia/handler.ts (1)

27-33: Add type safety when retrieving Prisma client

The current implementation casts the Prisma client directly to DbClientContract without any type checking. Consider adding runtime type verification to ensure the object has the expected shape.

-const prisma = (await options.getPrisma({ request, body, set } as ElysiaContext)) as DbClientContract;
+const prismaClient = await options.getPrisma({ request, body, set } as ElysiaContext);
+
+// Validate that we have a proper Prisma client
+const prisma = prismaClient as DbClientContract;
+if (!prisma || typeof prisma.$transaction !== 'function') {
    set.status = 500;
    return {
        message: 'unable to get prisma from request context'
    };
}
packages/server/tests/adapter/elysia.test.ts (1)

180-183: Add test coverage for SuperJSON parsing

The unmarshal function supports SuperJSON parsing, but this functionality is never tested. Consider adding tests that utilize useSuperJson = true to ensure this path is covered.

You could add a test case similar to the existing ones but that uses SuperJSON for serialization:

it('supports SuperJSON serialization', async () => {
  // Test setup with SuperJSON
  // ...
  expect(await unmarshal(r, true)).toMatchObject({
    // expected structure
  });
});
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 922e3c4 and 7f8050b.

⛔ Files ignored due to path filters (1)
  • packages/server/package.json is excluded by !**/*.json
📒 Files selected for processing (3)
  • packages/server/src/elysia/handler.ts (1 hunks)
  • packages/server/src/elysia/index.ts (1 hunks)
  • packages/server/tests/adapter/elysia.test.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
packages/server/src/elysia/handler.ts (3)
packages/server/src/types.ts (1)
  • AdapterBaseOptions (32-56)
packages/server/src/shared.ts (1)
  • loadAssets (5-21)
packages/runtime/src/types.ts (1)
  • DbClientContract (91-93)
🔇 Additional comments (9)
packages/server/src/elysia/index.ts (1)

1-1: Clean barrel file for Elysia adapter exports

This re-export approach is clean and follows the module pattern used elsewhere in the codebase, providing a convenient entry point for consumers to import the Elysia handler.

packages/server/src/elysia/handler.ts (3)

1-6: Appropriate imports for Elysia adapter implementation

All necessary imports are correctly included, utilizing types and functionality from both Elysia and the ZenStack ecosystem.


10-15: Well-typed interface for Elysia options

The ElysiaOptions interface properly extends the base adapter options and adds the required getPrisma callback to retrieve a Prisma client from the request context.


21-24: Clean initialization in the handler factory

The implementation correctly loads model metadata and Zod schemas using the shared loadAssets function, and sets up the default request handler when none is provided.

packages/server/tests/adapter/elysia.test.ts (5)

1-12: Test setup has appropriate imports and configurations

The imports and setup code correctly include all necessary dependencies for testing the Elysia adapter.


13-83: Comprehensive RPC handler tests cover critical paths

The test suite for RPC handler covers all essential operations including querying, creating, updating, and deleting records, as well as more advanced functionality like filtering, aggregation, and grouping.


85-112: Custom load path test verifies schema loading flexibility

This test correctly verifies that the adapter can load model metadata and Zod schemas from a custom output path, confirming the adapter's ability to work with various project configurations.


115-172: REST handler tests provide adequate coverage

The REST handler tests properly validate CRUD operations and filtering capabilities using the REST endpoint format.


185-189: Clean helper function for Elysia app creation

The createElysiaApp helper function provides a clean way to set up an Elysia app with the middleware, promoting code reuse across tests.

Comment on lines +25 to +69
return async (app: Elysia) => {
app.all('/*', async ({ request, body, set }: ElysiaContext) => {
const prisma = (await options.getPrisma({ request, body, set } as ElysiaContext)) as DbClientContract;
if (!prisma) {
set.status = 500;
return {
message: 'unable to get prisma from request context'
};
}

const url = new URL(request.url);
const query = Object.fromEntries(url.searchParams);
const path = url.pathname;

if (!path) {
set.status = 400;
return {
message: 'missing path parameter'
};
}

try {
const r = await requestHandler({
method: request.method,
path,
query,
requestBody: body,
prisma,
modelMeta,
zodSchemas,
logger: options.logger,
});

set.status = r.status;
return r.body;
} catch (err) {
set.status = 500;
return {
message: `An unhandled error occurred: ${err}`
};
}
});

return app;
};
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Consider more robust error handling in the catch block

The error handling should avoid exposing raw error objects to clients, as this could potentially leak sensitive information.

 } catch (err) {
     set.status = 500;
     return {
-        message: `An unhandled error occurred: ${err}`
+        message: 'An internal server error occurred'
     };
 }

Additionally, consider logging the actual error details for debugging purposes:

console.error('Elysia handler error:', err);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant