Skip to content

feat (dashboard): generate hasura api with orval #3344

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

Draft
wants to merge 8 commits into
base: feat/remote-schemas
Choose a base branch
from

Conversation

dbm03
Copy link
Member

@dbm03 dbm03 commented May 22, 2025

PR Type

Enhancement


Description

  • Generate Hasura API with Orval

  • Add custom fetch utility for API requests

  • Create type definitions for Hasura operations

  • Implement API endpoints for database operations


Changes walkthrough 📝

Relevant files
Enhancement
19 files
custom-fetch.ts
Implement custom fetch utility for API requests                   
+33/-0   
default.ts
Generate API client for Hasura operations                               
+143/-0 
addRemoteSchemaArgs.ts
Define type for adding remote schema arguments                     
+16/-0   
addRemoteSchemaArgsDefinition.ts
Define type for remote schema definition                                 
+19/-0   
addRemoteSchemaArgsDefinitionHeadersItem.ts
Define type for remote schema header item                               
+16/-0   
boolExp.ts
Define type for boolean expressions                                           
+14/-0   
bulkRequest.ts
Define type for bulk request operations                                   
+18/-0   
bulkRequestType.ts
Define enum for bulk request types                                             
+18/-0   
bulkRunSqlOperation.ts
Define type for bulk SQL operations                                           
+15/-0   
bulkRunSqlOperationArgs.ts
Define type for bulk SQL operation arguments                         
+18/-0   
bulkRunSqlOperationType.ts
Define enum for bulk SQL operation types                                 
+18/-0   
columnPresets.ts
Define type for column preset values                                         
+14/-0   
commandOkResponse.ts
Define type for successful command responses                         
+15/-0   
commandOkResponseResultType.ts
Define enum for command response result types                       
+18/-0   
createArrayRelationshipArgs.ts
Define type for creating array relationship arguments       
+20/-0   
createArrayRelationshipArgsUsing.ts
Define type for array relationship creation options           
+12/-0   
createArrayRelationshipArgsUsingForeignKeyConstraintOn.ts
Define type for array relationship foreign key constraints
+14/-0   
createObjectRelationshipArgs.ts
Define type for creating object relationship arguments     
+20/-0   
createObjectRelationshipArgsUsing.ts
Define type for object relationship creation options         
+12/-0   
Configuration changes
3 files
orval.config.ts
Configure Orval for Hasura API generation                               
+37/-0   
.eslintrc.js
Add ESLint configuration for generated files                         
+23/-0   
.prettierrc.js
Add Prettier configuration for generated files                     
+7/-0     
Dependencies
1 files
package.json
Add Orval dependency and codegen script                                   
+2/-0     
Documentation
1 files
openapi.yaml
Add OpenAPI specification for Hasura API                                 
+1086/-0
Additional files
80 files
deletePermissionArgs.ts +20/-0   
deletePermissionArgsPermission.ts +12/-0   
dropPermissionArgs.ts +16/-0   
dropRelationshipArgs.ts +16/-0   
errorResponse.ts +14/-0   
executeMetadataOperation200.ts +11/-0   
executeMetadataOperationBody.ts +41/-0   
executeQuery200.ts +11/-0   
executeQueryBody.ts +11/-0   
exportMetadata.ts +13/-0   
exportMetadataResponse.ts +21/-0   
exportMetadataResponseMetadata.ts +12/-0   
exportMetadataResponseSourcesItem.ts +9/-0     
exportMetadataType.ts +18/-0   
index.ts +104/-0 
insertPermissionArgs.ts +20/-0   
insertPermissionArgsPermission.ts +18/-0   
migrationRequest.ts +19/-0   
migrationStep.ts +11/-0   
pgCreateArrayRelationship.ts +15/-0   
pgCreateArrayRelationshipType.ts +18/-0   
pgCreateDeletePermission.ts +15/-0   
pgCreateDeletePermissionType.ts +18/-0   
pgCreateInsertPermission.ts +15/-0   
pgCreateInsertPermissionType.ts +18/-0   
pgCreateObjectRelationship.ts +15/-0   
pgCreateObjectRelationshipType.ts +18/-0   
pgCreateSelectPermission.ts +15/-0   
pgCreateSelectPermissionType.ts +18/-0   
pgCreateUpdatePermission.ts +15/-0   
pgCreateUpdatePermissionType.ts +18/-0   
pgDropDeletePermission.ts +15/-0   
pgDropDeletePermissionType.ts +18/-0   
pgDropInsertPermission.ts +15/-0   
pgDropInsertPermissionType.ts +18/-0   
pgDropRelationship.ts +15/-0   
pgDropRelationshipType.ts +18/-0   
pgDropSelectPermission.ts +15/-0   
pgDropSelectPermissionType.ts +18/-0   
pgDropUpdatePermission.ts +15/-0   
pgDropUpdatePermissionType.ts +18/-0   
pgSuggestRelationships.ts +15/-0   
pgSuggestRelationshipsArgs.ts +17/-0   
pgSuggestRelationshipsResponse.ts +14/-0   
pgSuggestRelationshipsResponseArrayRelationshipsItem.ts +16/-0   
pgSuggestRelationshipsResponseArrayRelationshipsItemUsing.ts +12/-0   
pgSuggestRelationshipsResponseArrayRelationshipsItemUsingForeignKeyConstraintOn.ts +15/-0   
pgSuggestRelationshipsResponseObjectRelationshipsItem.ts +16/-0   
pgSuggestRelationshipsResponseObjectRelationshipsItemUsing.ts +12/-0   
pgSuggestRelationshipsType.ts +18/-0   
postgresErrorResponse.ts +18/-0   
postgresErrorResponseInternal.ts +18/-0   
postgresErrorResponseInternalError.ts +26/-0   
reloadRemoteSchemaArgs.ts +12/-0   
reloadRemoteSchemaOperation.ts +15/-0   
reloadRemoteSchemaOperationType.ts +18/-0   
remoteSchemaOperation.ts +15/-0   
remoteSchemaOperationType.ts +18/-0   
removeRemoteSchemaArgs.ts +12/-0   
removeRemoteSchemaOperation.ts +15/-0   
removeRemoteSchemaOperationType.ts +18/-0   
rolePermission.ts +12/-0   
runSqlRequest.ts +15/-0   
runSqlRequestArgs.ts +18/-0   
runSqlRequestType.ts +18/-0   
selectPermissionArgs.ts +20/-0   
selectPermissionArgsPermission.ts +18/-0   
sqlMigrationArgs.ts +18/-0   
sqlMigrationStep.ts +15/-0   
sqlMigrationStepType.ts +18/-0   
successResponse.ts +12/-0   
tableIdentifier.ts +14/-0   
trackTableArgs.ts +14/-0   
trackTableArgsTable.ts +14/-0   
trackTableStep.ts +15/-0   
trackTableStepType.ts +18/-0   
tuplesOkResponse.ts +15/-0   
tuplesOkResponseResultType.ts +18/-0   
updatePermissionArgs.ts +20/-0   
updatePermissionArgsPermission.ts +17/-0   

Need help?
  • Type /help how to ... in the comments thread for any questions about PR-Agent usage.
  • Check out the documentation for more information.
  • Copy link

    changeset-bot bot commented May 22, 2025

    ⚠️ No Changeset found

    Latest commit: 5c7d946

    Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

    This PR includes no changesets

    When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

    Click here to learn what changesets are, and how to add one.

    Click here if you're a maintainer who wants to add a changeset to this PR

    Copy link

    vercel bot commented May 22, 2025

    The latest updates on your projects. Learn more about Vercel for Git ↗︎

    Name Status Preview Updated (UTC)
    dashboard-staging ❌ Failed (Inspect) Jun 4, 2025 11:12am
    example-nextjs-server-components ✅ Ready (Inspect) Visit Preview Jun 4, 2025 11:12am
    example-react-apollo ✅ Ready (Inspect) Visit Preview Jun 4, 2025 11:12am
    example-sveltekit ✅ Ready (Inspect) Visit Preview Jun 4, 2025 11:12am
    example-vue-apollo ✅ Ready (Inspect) Visit Preview Jun 4, 2025 11:12am
    1 Skipped Deployment
    Name Status Preview Updated (UTC)
    dashboard ⬜️ Ignored (Inspect) Visit Preview Jun 4, 2025 11:12am

    @dbm03 dbm03 self-assigned this May 22, 2025
    @dbarrosop dbarrosop added the dashboard Nhost Dashboard label May 22, 2025
    @dbm03 dbm03 changed the title feat: generate hasura api with orval feat (dashboard): generate hasura api with orval May 22, 2025
    Copy link
    Contributor

    PR Reviewer Guide 🔍

    Here are some key observations to aid the review process:

    ⏱️ Estimated effort to review: 4 🔵🔵🔵🔵⚪
    🧪 No relevant tests
    🔒 Security concerns

    Sensitive information exposure:
    The custom fetch utility in 'dashboard/src/utils/hasura-api/custom-fetch.ts' allows passing an admin secret as a parameter. This could potentially expose sensitive information if not handled securely. Ensure that the admin secret is never exposed to client-side code and is properly protected in server-side implementations. Consider using environment variables or a secure secret management system to handle the admin secret.

    ⚡ Recommended focus areas for review

    Security Concern

    The custom fetch utility allows passing an admin secret, which could be a security risk if not handled properly. Ensure that the admin secret is securely managed and not exposed to client-side code.

    if (adminSecret) {
      headers['x-hasura-admin-secret'] = adminSecret;
    }
    Error Handling

    The generated API functions don't include explicit error handling. Consider adding try-catch blocks or error handling middleware to manage potential API errors gracefully.

    export const executeQuery = async (
      executeQueryBody: ExecuteQueryBody,
      options?: RequestInit,
    ): Promise<executeQueryResponse> => {
      return customFetch<executeQueryResponse>(getExecuteQueryUrl(), {
        ...options,
        method: 'POST',
        headers: { 'Content-Type': 'application/json', ...options?.headers },
        body: JSON.stringify(executeQueryBody),
      });
    };
    Configuration Review

    The Orval configuration file sets up API generation. Ensure that all necessary options are correctly configured, especially the mutator and query settings, to match the project's requirements.

    import { defineConfig } from 'orval';
    
    export default defineConfig({
      hasuraApi: {
        input: {
          target: 'openapi.yaml',
        },
        output: {
          mode: 'tags-split',
          target: 'generated',
          schemas: 'generated/schemas',
          client: 'fetch',
          override: {
            mutator: {
              path: 'custom-fetch.ts',
              name: 'customFetch',
            },
            query: {
              useQuery: true,
              useMutation: true,
            },
            operations: {
              metadataOperation: {
                // Handle the remote schemas operation
                operationName: () => 'executeMetadataOperation',
              },
            },
          },
          prettier: true,
        },
        hooks: {
          afterAllFilesWrite: {
            command: 'npx prettier --write "./src/utils/hasura-api/generated/**/*.ts"',
          },
        },
      },
    });

    Copy link
    Contributor

    PR Code Suggestions ✨

    Explore these optional code suggestions:

    CategorySuggestion                                                                                                                                    Impact
    Possible issue
    Require 'down' property for migrations

    The 'down' property should be included in the 'required' array of the
    MigrationRequest schema. This ensures that users always provide a way to revert
    migrations, which is crucial for maintaining database integrity and allowing
    rollbacks.

    dashboard/src/utils/hasura-api/openapi.yaml [416-439]

     MigrationRequest:
       type: object
       required:
         - name
         - up
    +    - down
         - datasource
       properties:
         name:
           type: string
           description: Name of the migration
           example: my_migration
         up:
           type: array
    -      description: Steps to execute for the migration. Always provide a down migration as well when creating a migration that modifies the database
    +      description: Steps to execute for the migration
           items:
             $ref: '#/components/schemas/MigrationStep'
         down:
           type: array
    -      description: Steps to execute to revert the migration. Always provide this when creating a migration that modifies the database
    +      description: Steps to execute to revert the migration
           items:
             $ref: '#/components/schemas/MigrationStep'
         datasource:
           type: string
           description: The data source to use
           example: default
    Suggestion importance[1-10]: 9

    __

    Why: Adding 'down' to the required fields is crucial for database integrity and rollback capability. This ensures that every migration has a defined reversion process, which is essential for maintaining a robust database schema management system.

    High
    Properly merge custom headers

    The function is not using the headers object created earlier. Merge it with the
    existing headers in options to ensure all headers are properly set, including the
    admin secret if provided.

    dashboard/src/utils/hasura-api/custom-fetch.ts [23-32]

     if (adminSecret) {
       headers['x-hasura-admin-secret'] = adminSecret;
     }
     
     const config: RequestInit = {
       ...options,
    -  headers,
    +  headers: {
    +    ...options.headers,
    +    ...headers,
    +  },
     };
     
     return fetch(fullUrl, config);
    Suggestion importance[1-10]: 8

    __

    Why: The suggestion correctly identifies that the headers object is not being properly merged with options.headers. This fix ensures all headers, including the admin secret, are correctly set in the request.

    Medium
    Add error handling for fetch

    Consider adding error handling for network failures or invalid responses. Wrap the
    fetch call in a try-catch block and handle potential errors to improve the
    robustness of the function.

    dashboard/src/utils/hasura-api/custom-fetch.ts [1-10]

     export const customFetch = async (
       url: string,
       options: RequestInit = {},
       appUrl?: string,
       adminSecret?: string,
     ): Promise<Response> => {
       // Allow overriding the base URL with appUrl parameter
       const baseUrl = appUrl || '';
       const fullUrl = `${baseUrl}${url}`;
     
    +  try {
    +    const response = await fetch(fullUrl, config);
    +    if (!response.ok) {
    +      throw new Error(`HTTP error! status: ${response.status}`);
    +    }
    +    return response;
    +  } catch (error) {
    +    console.error('Fetch error:', error);
    +    throw error;
    +  }
    +
    Suggestion importance[1-10]: 7

    __

    Why: Adding error handling improves the function's robustness by catching and logging network errors or invalid responses. This enhancement is important for better error management and debugging.

    Medium

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

    Successfully merging this pull request may close these issues.

    2 participants