Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(@vben/request): export basic HttpResponse generic #4697

Merged
merged 1 commit into from
Oct 21, 2024

Conversation

gee1k
Copy link
Contributor

@gee1k gee1k commented Oct 20, 2024

Description

Type of change

Please delete options that are not relevant.

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • This change requires a documentation update
  • Please, don't make changes to pnpm-lock.yaml unless you introduce a new test example.

Checklist

ℹ️ Check all checkboxes - this will indicate that you have done everything in accordance with the rules in CONTRIBUTING.

  • If you introduce new functionality, document it. You can run documentation with pnpm run docs:dev command.
  • Run the tests with pnpm test.
  • Changes in changelog are generated from PR name. Please, make sure that it explains your changes in an understandable manner. Please, prefix changeset messages with feat:, fix:, perf:, docs:, or chore:.
  • My code follows the style guidelines of this project
  • I have performed a self-review of my own code
  • I have commented my code, particularly in hard-to-understand areas
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have added tests that prove my fix is effective or that my feature works
  • New and existing unit tests pass locally with my changes
  • Any dependent changes have been merged and published in downstream modules

Summary by CodeRabbit

  • New Features

    • Introduced a new type alias RequestResponse for improved type representation of responses.
  • Bug Fixes

    • Updated the download method to return a more specific response type, enhancing reliability in handling downloads.

Copy link

changeset-bot bot commented Oct 20, 2024

⚠️ No Changeset found

Latest commit: 4db7197

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
Contributor

coderabbitai bot commented Oct 20, 2024

Walkthrough

The changes in this pull request involve modifications to the FileDownloader class in the downloader.ts file and the introduction of a new type alias in the types.ts file. Specifically, the return type of the download method has been updated from Promise<AxiosResponse<Blob>> to Promise<RequestResponse<Blob>>, reflecting a shift to a custom response type. Additionally, a new type alias RequestResponse<T = any> has been added to represent Axios responses more specifically.

Changes

File Path Change Summary
packages/effects/request/src/request-client/modules/downloader.ts - Removed AxiosResponse from imports.
- Changed download method return type to Promise<RequestResponse<Blob>>.
- Updated get method call to use RequestResponse<Blob>.
- Retained AxiosRequestConfig import unchanged.
packages/effects/request/src/request-client/types.ts - Added new type alias RequestResponse<T = any> as an alias for AxiosResponse<T>.

Possibly related PRs

Suggested reviewers

  • vince292007

Poem

In the meadow where bunnies play,
A new type hops in, brightening the day.
With RequestResponse, we dance and cheer,
Downloading files without any fear!
Let's celebrate this change, oh what a delight,
For every download brings joy, pure and bright! 🐇✨


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?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • 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.

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 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: 0

🧹 Outside diff range and nitpick comments (2)
packages/effects/request/src/request-client/modules/downloader.ts (1)

Line range hint 22-26: LGTM: get method call updated correctly. Consider a minor improvement.

The update of the type parameter in the get method call from AxiosResponse<Blob> to RequestResponse<Blob> is consistent with the earlier changes and ensures type consistency throughout the method.

For improved code consistency, consider using the Blob type directly in the finalConfig object:

 const finalConfig: AxiosRequestConfig = {
   ...config,
-  responseType: 'blob',
+  responseType: 'blob' as const,
 };

This change makes the type more explicit and consistent with the usage in the get method call.

packages/effects/request/src/request-client/types.ts (1)

7-7: LGTM! Consider adding a brief comment for clarity.

The addition of the RequestResponse type alias is a good way to make the code more domain-specific. It provides a clear, project-specific name for the Axios response type while maintaining flexibility with the generic parameter.

Consider adding a brief comment to explain the purpose of this type alias, for example:

/** Alias for AxiosResponse to provide a more domain-specific type name */
type RequestResponse<T = any> = AxiosResponse<T>;
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between bfaa278 and 4db7197.

📒 Files selected for processing (2)
  • packages/effects/request/src/request-client/modules/downloader.ts (2 hunks)
  • packages/effects/request/src/request-client/types.ts (2 hunks)
🧰 Additional context used
🔇 Additional comments (5)
packages/effects/request/src/request-client/modules/downloader.ts (3)

1-5: LGTM: Import changes are consistent with type updates.

The addition of the RequestResponse import and the removal of the AxiosResponse import (as mentioned in the AI summary) align well with the changes in the method signature. This change supports the transition from Axios-specific types to custom types while maintaining the necessary AxiosRequestConfig import.


13-16: LGTM: Method signature updated correctly.

The return type change from Promise<AxiosResponse<Blob>> to Promise<RequestResponse<Blob>> is consistent with the transition to custom types. It maintains type safety for blob responses while decoupling from Axios-specific types. The unchanged method parameters correctly retain the use of AxiosRequestConfig.


Line range hint 1-33: Overall assessment: Changes are well-implemented and consistent.

The modifications in this file successfully transition from Axios-specific types to custom types while maintaining type safety and consistency. The changes align well with the PR objectives of exporting a basic HttpResponse generic. No breaking changes or potential issues were identified.

To ensure the RequestResponse type is correctly defined and exported, please run the following verification script:

✅ Verification successful

Verified: RequestResponse type is correctly defined and utilized.

The RequestResponse type is properly defined and exported in packages/effects/request/src/request-client/types.ts. Its usage in downloader.ts is consistent and maintains type safety. No issues were identified.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the RequestResponse type definition and export

# Test: Check if RequestResponse is defined and exported in types.ts
rg -A 5 'export.*RequestResponse' packages/effects/request/src/request-client/types.ts

# Test: Verify usage of RequestResponse in other files
rg 'RequestResponse' packages/effects/request/src/request-client/

Length of output: 681

packages/effects/request/src/request-client/types.ts (2)

51-51: LGTM! Export is correctly placed and maintains alphabetical order.

The RequestResponse type is appropriately exported along with other related types. This makes it available for use throughout the project, which aligns with the intention of the change. The alphabetical ordering of exports is maintained, which is good for readability and consistency.


Line range hint 1-53: Overall, the changes enhance type safety and readability. Consider extending this pattern to other Axios types.

The addition of the RequestResponse type alias is a positive change that makes the code more domain-specific and potentially easier to maintain. It's consistent with existing types and naming conventions in the file.

As a future improvement, consider applying this pattern to other Axios types used in the project. For example, you might want to create aliases for AxiosRequestConfig or AxiosError. This would further enhance the domain-specific nature of your types and make it easier to adapt if you ever need to switch underlying HTTP client libraries.

To ensure consistency across the codebase, let's check for other usages of AxiosResponse:

If there are other occurrences, consider updating them to use RequestResponse for consistency.

@gee1k
Copy link
Contributor Author

gee1k commented Oct 20, 2024

改动解释:例如我刚刚的一个业务需求是需要做文件导出下载功能,使用了 RequestClient 提供的 download 函数请求 Blob 数据。

然后我封装了一个 useDownload Hook 来进行创建 a 标签执行下载,我需要拿到 response 里的 content-disposition header 数据来获取文件名等信息,这时候原始的 AxiosResponse 类型没有导出导致我无法在 hook 里进行类型标注

@gee1k
Copy link
Contributor Author

gee1k commented Oct 20, 2024

下方代码两个 FIXME 处

import { message, notification } from 'ant-design-vue';

// FIXME: 等待类型导出
// import type { RequestResponse } from '@vben/request';

interface NavigatorWithMsSaveOrOpenBlob extends Navigator {
  msSaveOrOpenBlob: (blob: Blob, fileName: string) => void;
}

export interface DownloadOptions {
  isNotify?: boolean;
  fileName?: string;
  fileType?: string;
}

const defaultOptions: DownloadOptions = {
  isNotify: false,
  fileType: '.xlsx',
};

/**
 * @description 接收数据流生成 blob,创建链接,下载文件
 * @param {Function} api 导出表格的api方法 (必传)
 * @param {object} options 配置项
 * @param {boolean} options.isNotify 是否提示下载过程中的提示,默认为 false
 * @param {string} options.fileName 文件名,默认为服务器返回或当前时间戳
 * @param {string} options.fileType 文件类型,默认为服务器返回或 .xlsx
 */
export async function useDownload(
  api: () => Promise<any>,
  // FIXME: 等待类型导出
  // api: () => Promise<RequestResponse<Blob>>,
  options: DownloadOptions = defaultOptions,
) {
  const loadingClose = message.loading({
    content: '正在导出数据,请稍后...',
    duration: 0,
  });
  try {
    const res = await api();

    const fileType = options?.fileType || '.xlsx';

    const tempName = options?.fileName
      ? options.fileName + fileType
      : // eslint-disable-next-line unicorn/no-nested-ternary
        res.headers['content-disposition']
        ? decodeURI(
            res.headers['content-disposition'].split(';')[1].split('=')[1],
          ).replaceAll('"', '')
        : Date.now() + fileType;

    loadingClose();

    if (options?.isNotify) {
      notification.warning({
        message: '温馨提示',
        description: '如果数据庞大会导致下载缓慢哦,请您耐心等待!',
      });
    }
    if (
      res.status !== 200 ||
      res.data === null ||
      !(res.data instanceof Blob)
    ) {
      message.error('导出失败,请稍后再试!');
      return;
    }
    const blob = new Blob([res.data]);
    // 兼容 edge 不支持 createObjectURL 方法
    if (
      'msSaveOrOpenBlob' in
      (navigator as unknown as NavigatorWithMsSaveOrOpenBlob)
    ) {
      (
        window.navigator as unknown as NavigatorWithMsSaveOrOpenBlob
      ).msSaveOrOpenBlob(blob, tempName + fileType);
    }
    const blobUrl = window.URL.createObjectURL(blob);
    const exportFile = document.createElement('a');
    exportFile.style.display = 'none';
    exportFile.download = tempName;
    exportFile.href = blobUrl;
    document.body.append(exportFile);
    exportFile.click();
    // 去除下载对 url 的影响
    exportFile.remove();
    window.URL.revokeObjectURL(blobUrl);
  } catch {
    // console.log(error)
    loadingClose();
  }
}

@vince292007 vince292007 merged commit 88d2b3e into vbenjs:main Oct 21, 2024
14 checks passed
GavinLucky pushed a commit to GavinLucky/vue-vben-admin that referenced this pull request Oct 23, 2024
@github-actions github-actions bot locked and limited conversation to collaborators Nov 23, 2024
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants