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: 使用 mockm #4011

Closed
wants to merge 6 commits into from
Closed

feat: 使用 mockm #4011

wants to merge 6 commits into from

Conversation

wll8
Copy link

@wll8 wll8 commented Aug 2, 2024

Description

使用 mockm, 因为:

Type of change

Please delete options that are not relevant.

  • New feature (non-breaking change which adds functionality)
  • 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 mock authentication API with /api/auth/codes and /api/auth/login endpoints.
    • Added user-specific menu retrieval through /api/menu/all.
    • Implemented user information retrieval with a new endpoint /api/user/info.
    • Launched a new configuration framework for the mock API.
    • Added a new Vite plugin for integrating the mock server.
  • Documentation

    • Updated README to clarify the mock service's JSON-based storage usage.
    • Rebranded references from "Nitro Mock Server" to "Mockm Mock Server" throughout documentation.
  • Bug Fixes

    • Fixed issues in handling environment variables related to mock services.
  • Chores

    • Updated .gitignore and .eslintignore configurations to streamline development.
    • Added new dependency for process management.
    • Removed unnecessary mock configuration properties from application settings.
    • Renamed environment variable from VITE_NITRO_MOCK to VITE_MOCKM_MOCK across configurations.

Copy link

changeset-bot bot commented Aug 2, 2024

⚠️ No Changeset found

Latest commit: 708fb5e

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 Aug 2, 2024

Walkthrough

The recent changes reflect a substantial reorganization of the codebase, particularly in the mock service architecture. Transitioning from "Nitro" to "Mockm" enhances clarity and aligns with the new project direction. Key updates include the addition of new API modules for authentication, user information, and menu handling, alongside improved documentation and dependency management. This restructuring aims to streamline development workflows and better integrate mock services into the development environment.

Changes

Files Change Summary
.prettierignore, internal/lint-configs/... Removed .nitro from Prettier ignore and ESLint configuration, allowing related files to be linted.
apps/backend-mock/.eslintignore Introduced .eslintignore to exclude all files from ESLint checks.
apps/backend-mock/README.md Updated to clarify deployment process and added instructions for running the mock service.
apps/backend-mock/api/*.cjs Added new API modules for authentication, menu, and user info, each responding to relevant requests.
apps/backend-mock/mm.config.cjs New mock backend service configuration file with API routing and response handling.
apps/backend-mock/package.json Updated to use commonjs type; added mockm dependency and modified existing scripts.
apps/backend-mock/util.cjs Introduced new response handling functions and modified exports for mock data.
apps/web-*/.env.development Renamed environment variable from VITE_NITRO_MOCK to VITE_MOCKM_MOCK for clarity.
apps/web-*/vite.config.mts Changed proxy target from localhost to 127.0.0.1 for improved reliability.
docs/src/... Updated documentation to reflect new "Mockm" branding and changes in API configurations.
internal/vite-config/... Introduced a comprehensive Vite plugin system, replacing old mock references with new ones.
turbo.json Removed dependency configuration for @vben/backend-mock#build, streamlining the build process.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant MockServer
    participant API

    Client->>API: Request authentication data
    API->>MockServer: Check credentials
    MockServer-->>API: Return token
    API-->>Client: Provide authentication success
Loading
sequenceDiagram
    participant Client
    participant MockServer
    participant API

    Client->>API: Request user info
    API->>MockServer: Validate token
    MockServer-->>API: Return user details
    API-->>Client: Provide user info
Loading

🐇 In the garden, bright and spry,
A new mock server hops on by!
With Mockm's charm, the code's refined,
Clean and swift, it's well-designed.
So gather round, let's celebrate,
Our joyful code, oh, isn't it great? 🌼✨


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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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 as 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.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

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

Outside diff range, codebase verification and nitpick comments (1)
apps/backend-mock/mm.config.cjs (1)

1-5: Missing implementation of useResponseError function

The function useResponseError imported in apps/backend-mock/mm.config.cjs is not implemented in the codebase. This could lead to runtime errors. Please ensure that the useResponseError function is correctly implemented.

  • apps/backend-mock/util.cjs: Implement the useResponseError function.
Analysis chain

Ensure utility functions are correctly implemented.

The configuration imports utility functions from ./util.cjs. Verify that these functions are correctly implemented and tested.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the implementation and testing of utility functions imported from `./util.cjs`.

# Test: Search for the implementation of utility functions in `./util.cjs`.
rg --type js -A 5 $'wrapApiData'
rg --type js -A 5 $'useResponseSuccess'
rg --type js -A 5 $'useResponseError'

Length of output: 107


Script:

#!/bin/bash
# Description: Verify the implementation of utility functions imported from `./util.cjs`.

# Test: Search for the implementation of utility functions in `./util.cjs` using ast-grep.
ast-grep --lang javascript --pattern 'function wrapApiData($_) { $$$ }'
ast-grep --lang javascript --pattern 'function useResponseSuccess($_) { $$$ }'
ast-grep --lang javascript --pattern 'function useResponseError($_) { $$$ }'

Length of output: 983


Script:

#!/bin/bash
# Description: Verify the presence of the `useResponseError` function in the entire codebase.

# Test: Search for the implementation of `useResponseError` in the entire codebase.
rg --type js -A 5 'function useResponseError'

Length of output: 47

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 5301591 and f59b222.

Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
Files selected for processing (37)
  • .prettierignore (1 hunks)
  • apps/backend-mock/.eslintignore (1 hunks)
  • apps/backend-mock/README.md (1 hunks)
  • apps/backend-mock/api/auth.cjs (1 hunks)
  • apps/backend-mock/api/menu.cjs (1 hunks)
  • apps/backend-mock/api/user.cjs (1 hunks)
  • apps/backend-mock/apiWeb.json (1 hunks)
  • apps/backend-mock/httpData/.gitignore (1 hunks)
  • apps/backend-mock/httpData/apiWeb.json (1 hunks)
  • apps/backend-mock/mm.config.cjs (1 hunks)
  • apps/backend-mock/package.json (1 hunks)
  • apps/backend-mock/util.cjs (5 hunks)
  • apps/web-antd/.env.development (1 hunks)
  • apps/web-antd/vite.config.mts (1 hunks)
  • apps/web-ele/.env.development (1 hunks)
  • apps/web-ele/vite.config.mts (1 hunks)
  • apps/web-naive/.env.development (1 hunks)
  • apps/web-naive/vite.config.mts (1 hunks)
  • docs/src/en/index.md (1 hunks)
  • docs/src/guide/essentials/package.json (1 hunks)
  • docs/src/guide/essentials/server.md (4 hunks)
  • docs/src/guide/essentials/settings.md (1 hunks)
  • docs/src/guide/introduction/vben.md (1 hunks)
  • docs/src/index.md (1 hunks)
  • internal/lint-configs/eslint-config/src/configs/ignores.ts (1 hunks)
  • internal/lint-configs/eslint-config/src/custom-config.ts (1 hunks)
  • internal/vite-config/index.ts (1 hunks)
  • internal/vite-config/package.json (1 hunks)
  • internal/vite-config/src/config/application.ts (1 hunks)
  • internal/vite-config/src/plugins/index.ts (3 hunks)
  • internal/vite-config/src/plugins/mockm-mock.ts (1 hunks)
  • internal/vite-config/src/typing.ts (3 hunks)
  • internal/vite-config/src/utils/env.ts (2 hunks)
  • internal/vite-config/typing.ts (1 hunks)
  • package.json (1 hunks)
  • scripts/vsh/src/check-dep/index.ts (1 hunks)
  • turbo.json (1 hunks)
Files skipped from review due to trivial changes (16)
  • .prettierignore
  • apps/backend-mock/.eslintignore
  • apps/backend-mock/httpData/.gitignore
  • apps/backend-mock/httpData/apiWeb.json
  • apps/web-antd/.env.development
  • apps/web-antd/vite.config.mts
  • apps/web-ele/.env.development
  • apps/web-ele/vite.config.mts
  • apps/web-naive/.env.development
  • apps/web-naive/vite.config.mts
  • docs/src/en/index.md
  • docs/src/guide/essentials/settings.md
  • docs/src/index.md
  • internal/lint-configs/eslint-config/src/custom-config.ts
  • internal/vite-config/src/config/application.ts
  • package.json
Additional context used
Markdownlint
apps/backend-mock/README.md

21-21: null
Dollar signs used before commands without showing output

(MD014, commands-show-output)


22-22: null
Dollar signs used before commands without showing output

(MD014, commands-show-output)


9-9: null
Fenced code blocks should have a language specified

(MD040, fenced-code-language)

Additional comments not posted (50)
apps/backend-mock/apiWeb.json (1)

1-4: LGTM!

The JSON structure is simple and appears to be correctly formatted.

apps/backend-mock/package.json (3)

8-8: Specify the module system.

The addition of the "type": "commonjs" field specifies the module system used in the project, aligning it with Node.js conventions.


10-10: Add a new script for mockm.

The new "mm": "npx mockm" script indicates a shift in the development workflow, potentially replacing previous build and start processes with a new mock server setup.


12-13: Add mockm as a development dependency.

The addition of "mockm": "1.1.27-alpha.2" to the devDependencies section signifies that mockm is now considered a development-only dependency.

apps/backend-mock/README.md (3)

5-5: Clarify the description.

The updated description clarifies that the service does not require database installation and uses JSON-based storage, enhancing the deployment process.


7-15: Add file structure section.

The new file structure section provides an overview of the project layout, enhancing clarity for developers.

Tools
Markdownlint

9-9: null
Fenced code blocks should have a language specified

(MD040, fenced-code-language)


27-29: Add references for mockm and mockjs.

The new references provide useful links to the mockm and mockjs documentation, enhancing usability for developers.

apps/backend-mock/api/menu.cjs (1)

1-10: LGTM! Import and export statements are appropriate.

The import statements bring in necessary utilities and mock data, and the export statement defines the configuration for the mockm library.

apps/backend-mock/api/user.cjs (1)

1-8: LGTM! Import and export statements are appropriate.

The import statements bring in necessary utilities and mock data, and the export statement defines the configuration for the mockm library.

turbo.json (1)

Line range hint 1-28:
LGTM! Simplified build configuration.

The removal of the dependency configuration for @vben/backend-mock#build simplifies the build process. Ensure that the build process is still functioning correctly without this dependency.

Verify the impact on the build process.

Ensure that the build process is still functioning correctly without the dependency on @vben/backend-mock#build.

internal/lint-configs/eslint-config/src/configs/ignores.ts (1)

Line range hint 1-37:
Verify the implications of removing the '/.nitro' pattern.**

The removal of the '**/.nitro' pattern means that files or directories matching this pattern will now be included in linting checks. Ensure that this change does not introduce any unintended linting errors or issues.

Verification successful

No immediate issues found with the removal of the '/.nitro' pattern.**

The search did not find any .nitro directories or files in the current codebase. While this suggests that removing the '**/.nitro' pattern from the linting ignores is unlikely to have a significant impact, it is advisable to monitor future additions to the codebase for any .nitro directories or files that would then be subject to linting.

  • No .nitro directories or files found in the current codebase.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the implications of removing the '**/.nitro' pattern from the linting ignores.

# Test: Search for files or directories matching the '.nitro' pattern to ensure they are lint-free.
rg --type python -A 5 $'.nitro'

Length of output: 61


Script:

#!/bin/bash
# Description: Verify the implications of removing the '**/.nitro' pattern from the linting ignores.

# Test: Search for files or directories matching the '.nitro' pattern across the entire codebase.
rg '.nitro'

Length of output: 307

apps/backend-mock/mm.config.cjs (2)

12-37: LGTM! Ensure the configuration is correctly integrated.

The configuration for mockm looks good. Ensure that it is correctly integrated into the project and that all API routes, proxy settings, and response handlers are functioning as expected.


7-11: Ensure documentation is up-to-date.

The configuration references documentation for mockm. Ensure that the documentation is up-to-date and accurately reflects the current configuration.

Verification successful

Documentation is up-to-date.

The configuration references documentation for mockm, and the provided URL leads to a comprehensive and current page detailing the configuration options.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the documentation for mockm configuration.

# Test: Check the documentation URL to ensure it is up-to-date.
curl -s https://hongqiye.com/doc/mockm/config/option.html | grep -i 'mockm configuration options'

Length of output: 99


Script:

#!/bin/bash
# Description: Fetch the content of the mockm configuration documentation page for manual inspection.

# Fetch and display the content of the documentation page.
curl -s https://hongqiye.com/doc/mockm/config/option.html

Length of output: 95869

internal/vite-config/package.json (1)

Line range hint 1-45:
Verify the implications of removing the "nitropack" dependency.

The removal of the "nitropack" dependency suggests a shift away from using the Nitropack library. Ensure that this change does not introduce any issues or break existing functionality.

apps/backend-mock/api/auth.cjs (1)

1-10: LGTM!

The import statements and module exports are correctly defined.

Also applies to: 12-17

docs/src/guide/essentials/package.json (3)

1-16: LGTM!

The package metadata and scripts are correctly defined.


17-28: LGTM!

The package files, main/module/types, and exports are correctly defined.


29-54: LGTM!

The package dependencies and devDependencies are correctly defined.

scripts/vsh/src/check-dep/index.ts (1)

13-14: LGTM!

The modification correctly integrates @vben/backend-mock into the dependency check process.

internal/vite-config/src/utils/env.ts (2)

72-72: Ensure the new environment variable VITE_MOCKM_MOCK is correctly set.

Verify that VITE_MOCKM_MOCK is correctly defined and used in the environment configuration.

Verification successful

The new environment variable VITE_MOCKM_MOCK is correctly set and used.

The variable VITE_MOCKM_MOCK is defined and utilized in the codebase, as well as documented appropriately.

  • internal/vite-config/src/utils/env.ts: Definition and usage.
  • docs/src/guide/essentials/settings.md: Documentation reference.
  • docs/src/guide/essentials/server.md: Documentation reference.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the correct usage of the new environment variable `VITE_MOCKM_MOCK`.

# Test: Search for the definition and usage of `VITE_MOCKM_MOCK`. Expect: Correct definition and usage.
rg --type env -A 5 $'VITE_MOCKM_MOCK'

Length of output: 64


Script:

#!/bin/bash
# Description: Verify the correct usage of the new environment variable `VITE_MOCKM_MOCK`.

# Test: Search for the definition and usage of `VITE_MOCKM_MOCK`. Expect: Correct definition and usage.
rg 'VITE_MOCKM_MOCK'

Length of output: 419


89-89: Ensure the new variable mockmMock is correctly used in the codebase.

Verify that all instances of mockmMock are correctly used and integrated.

Verification successful

The new variable mockmMock is correctly used and integrated in the codebase.

The variable mockmMock is consistently used across multiple files, including configuration and plugin setup, with proper type definitions.

  • internal/vite-config/index.ts
  • internal/vite-config/src/typing.ts
  • internal/vite-config/typing.ts
  • internal/vite-config/src/utils/env.ts
  • internal/vite-config/src/plugins/index.ts
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the correct usage of the new variable `mockmMock`.

# Test: Search for the usage of `mockmMock`. Expect: Correct usage and integration.
rg --type python -A 5 $'mockmMock'

Length of output: 64


Script:

#!/bin/bash
# Description: Verify the correct usage of the new variable `mockmMock`.

# Test: Search for the usage of `mockmMock` in TypeScript files. Expect: Correct usage and integration.
rg --type ts -A 5 $'mockmMock'

Length of output: 3202

docs/src/guide/introduction/vben.md (1)

21-21: Ensure the new mock data solution "Mockm" is correctly documented.

Verify that "Mockm" is correctly documented and integrated into the guide.

Verification successful

The new mock data solution "Mockm" is correctly documented and integrated.

The term "Mockm" is consistently used and well-documented across various sections of the guide, ensuring clarity and correctness.

  • docs/src/guide/introduction/vben.md
  • docs/src/index.md
  • docs/src/guide/essentials/settings.md
  • docs/src/guide/essentials/server.md
  • docs/src/en/index.md
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the correct documentation of the new mock data solution "Mockm".

# Test: Search for the term "Mockm" in the documentation. Expect: Correct documentation and integration.
rg --type md -A 5 $'Mockm'

Length of output: 2848

internal/vite-config/src/plugins/mockm-mock.ts (8)

44-51: Ensure the command-line arguments are correctly constructed.

Verify that the command-line arguments are correctly constructed and used.

Verification successful

The command-line arguments are correctly constructed and used.

The cliArg array is correctly formed using the line array, which includes the necessary key-value pairs for the command-line arguments. These arguments are then passed to the ProcessManager object as expected.

  • internal/vite-config/src/plugins/mockm-mock.ts: Lines 44-51
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the correct construction and usage of the command-line arguments.

# Test: Search for the usage of the command-line arguments. Expect: Correct construction and handling of the arguments.
rg --type typescript -A 5 $'cliArg'

Length of output: 69


Script:

#!/bin/bash
# Description: Verify the correct construction and usage of the command-line arguments.

# Test: Search for the usage of the command-line arguments. Expect: Correct construction and handling of the arguments.
rg -t ts -A 5 'cliArg'

Length of output: 924


26-30: Ensure the package is correctly retrieved.

Verify that the package specified by mockServerPackage is correctly retrieved.

Verification successful

Package retrieval is correctly handled.

The package specified by mockServerPackage is correctly retrieved using the getPackage function. If the package is not found, an error is logged and the function returns early.

  • internal/vite-config/src/plugins/mockm-mock.ts (lines 26-30)
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the correct retrieval of the package specified by `mockServerPackage`.

# Test: Search for the usage of the `getPackage` function. Expect: Correct retrieval and handling of the package.
rg --type typescript -A 5 $'getPackage'

Length of output: 73


Script:

#!/bin/bash
# Description: Verify the correct retrieval of the package specified by `mockServerPackage`.

# Test: Search for the usage of the `getPackage` function. Expect: Correct retrieval and handling of the package.
rg --type ts -A 5 $'getPackage'

Length of output: 8721


10-14: Ensure the default plugin options are correctly set.

Verify that the default plugin options (mockServerPackage, port, verbose) are correctly set and used.

Verification successful

Ensure the default plugin options are correctly set.

The default plugin options (mockServerPackage, port, verbose) are correctly set in the viteMockmPlugin function.

  • mockServerPackage is set to @vben/backend-mock.
  • port is set to 5320.
  • verbose is set to true.

These options are used within the function to configure the mock server package, port, and verbosity.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the correct usage of the default plugin options.

# Test: Search for the usage of the default plugin options. Expect: Correct usage and integration.
rg --type typescript -A 5 $'mockServerPackage|port|verbose'

Length of output: 95


Script:

#!/bin/bash
# Description: Verify the correct usage of the default plugin options.

# Test: Search for the usage of the default plugin options. Expect: Correct usage and integration.
rg --type ts -A 5 'mockServerPackage|port|verbose'

Length of output: 364471


78-86: Ensure the handleSpace function is correctly implemented.

Verify that the handleSpace function is correctly implemented and used.

Verification successful

The handleSpace function is correctly implemented and used.

The function is used to handle paths that may contain spaces, wrapping them in double quotes if the operating system is Windows. This is consistent with the intended behavior described in the comments.

  • internal/vite-config/src/plugins/mockm-mock.ts:
    • Line 78: --config': handleSpace(${pkg.dir}/mm.config.cjs`),
    • Line 86: handleSpace(${pkg.dir}/node_modules/mockm/run.js`),
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the correct implementation and usage of the `handleSpace` function.

# Test: Search for the usage of the `handleSpace` function. Expect: Correct implementation and handling of the function.
rg --type typescript -A 5 $'handleSpace'

Length of output: 74


Script:

#!/bin/bash
# Find all TypeScript files and search for the usage of the `handleSpace` function within those files.
fd -e ts -e tsx | xargs rg 'handleSpace'

Length of output: 336


35-39: Ensure the ports are correctly retrieved.

Verify that the ports (availablePort, testPort, replayPort) are correctly retrieved and used.

Verification successful

Ports are correctly retrieved and used.

The ports (availablePort, testPort, replayPort) are correctly retrieved using Promise.all and the getPort function. They are subsequently used in the code to check port availability and form command-line arguments.

  • internal/vite-config/src/plugins/mockm-mock.ts: Lines 35-39, 41-45, 47-52
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the correct retrieval and usage of the ports.

# Test: Search for the usage of the ports. Expect: Correct retrieval and handling of the ports.
rg --type typescript -A 5 $'availablePort|testPort|replayPort'

Length of output: 98


Script:

#!/bin/bash
# Description: Verify the correct retrieval and usage of the ports.

# Test: Search for the usage of the ports. Expect: Correct retrieval and handling of the ports.
rg -t ts -A 5 'availablePort|testPort|replayPort'

Length of output: 1358


16-23: Ensure the Transform stream is correctly implemented.

Verify that the Transform stream is correctly implemented and used for logging.

Verification successful

The Transform stream is correctly implemented and integrated.

  • The verbose flag is properly defined and used to conditionally log data.
  • The transformStream is correctly integrated as the stdout stream for the ProcessManager instance.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the correct implementation of the `Transform` stream.

# Test: Search for the usage of the `Transform` stream. Expect: Correct implementation and integration.
rg --type typescript -A 5 $'Transform'

Length of output: 72


Script:

#!/bin/bash
# Description: Verify the correct implementation of the `Transform` stream.

# Test: Search for the usage of the `Transform` stream in TypeScript files. Expect: Correct implementation and integration.
rg 'Transform' --glob '*.ts' -A 5

Length of output: 1898


Script:

#!/bin/bash
# Description: Verify the definition of `verbose` and the integration of `transformStream`.

# Test: Search for the definition of `verbose` in the relevant TypeScript file.
rg 'verbose' internal/vite-config/src/plugins/mockm-mock.ts -A 5 -B 5

# Test: Search for the usage of `transformStream` in the relevant TypeScript file.
rg 'transformStream' internal/vite-config/src/plugins/mockm-mock.ts -A 5 -B 5

Length of output: 1755


33-33: Ensure the ProcessManager is correctly imported.

Verify that the ProcessManager is correctly imported and used.

Verification successful

The ProcessManager is correctly imported and used.

  • The ProcessManager is dynamically imported using await import('@wll8/process-manager').
  • It is used within the same file internal/vite-config/src/plugins/mockm-mock.ts.
Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the correct import and usage of the `ProcessManager`.

# Test: Search for the usage of the `ProcessManager`. Expect: Correct import and integration.
rg --type typescript -A 5 $'ProcessManager'

Length of output: 77


Script:

#!/bin/bash
# Description: Verify the correct import of the `ProcessManager`.

# Test: Search for the import statement of `ProcessManager`. Expect: Correct import statement.
rg "import.*ProcessManager" -t ts

Length of output: 35


Script:

#!/bin/bash
# Description: Verify the usage of the `ProcessManager`.

# Test: Search for the usage of `ProcessManager`. Expect: Correct usage in the codebase.
rg "ProcessManager" -t ts

Length of output: 229


57-61: Ensure the ProcessManager is correctly instantiated.

Verify that the ProcessManager is correctly instantiated and used.

internal/vite-config/src/typing.ts (3)

Line range hint 19-33: Renamed NitroMockPluginOptions to MockmMockPluginOptions.

The renaming is consistent and the properties within the interface are clear and well-documented.


98-100: Updated ApplicationPluginOptions to use mockmMock and mockmMockOptions.

The renaming is consistent with the new MockmMockPluginOptions interface. Ensure that all references to nitroMock and nitroMockOptions in the codebase are updated accordingly.


145-145: Updated export statement to use MockmMockPluginOptions.

The export statement is updated correctly to reflect the new interface name. This ensures that any consumers of this module will use the updated interface.

internal/vite-config/typing.ts (1)

1-147: New file with interface declarations and type exports.

The new file introduces interface declarations for various plugin options and exports them. The structure and documentation are clear and consistent with the existing codebase. Ensure that this file is correctly integrated and referenced where needed.

apps/backend-mock/util.cjs (7)

1-14: New function wrapApiData.

The function encapsulates API response wrapping, improving code modularity and reusability. The logic for determining success or error responses is clear and well-documented.


16-23: New function useResponseSuccess.

The function standardizes the structure of successful API responses. The structure is clear and consistent with common API response formats.


25-32: New function useResponseError.

The function standardizes the structure of error API responses. The structure is clear and consistent with common API response formats.


34-34: Updated MOCK_USERS to a local constant.

The change to a local constant is consistent with the new export structure. Ensure that MOCK_USERS is correctly referenced where needed.


58-58: Updated MOCK_CODES to a local constant.

The change to a local constant is consistent with the new export structure. Ensure that MOCK_CODES is correctly referenced where needed.


108-108: Updated MOCK_MENUS to a local constant.

The change to a local constant is consistent with the new export structure. Ensure that MOCK_MENUS is correctly referenced where needed.


213-220: Updated export structure to use module.exports.

The new export structure is clear and consistent, improving the module's usability. Ensure that all exported entities are correctly referenced where needed.

internal/vite-config/src/plugins/index.ts (3)

26-26: Import statement for viteMockmPlugin looks good.

The import statement correctly imports the viteMockmPlugin from the mockm-mock module.


104-105: Function signature change for loadApplicationPlugins looks good.

The function signature correctly replaces nitroMock and nitroMockOptions with mockmMock and mockmMockOptions.


136-138: Conditional plugin loading for viteMockmPlugin looks good.

The conditional logic correctly checks for mockmMock and loads the viteMockmPlugin with mockmMockOptions.

docs/src/guide/essentials/server.md (3)

7-7: Introduction update to reference Mockm looks good.

The introduction correctly references Mockm and provides a link to its documentation.


49-49: Proxy target URL update looks good.

The update to use 127.0.0.1 instead of localhost can help avoid potential DNS resolution issues.


257-271: Mockm usage and configuration update looks good.

The documentation correctly describes how to use and configure Mockm and provides relevant links to its documentation.

internal/vite-config/index.ts (3)

1-27: Import statements look good.

The import statements correctly import the necessary Vite plugins, including the new viteMockmPlugin.


29-42: Function loadConditionPlugins looks good.

The function is well-structured and correctly loads the plugins based on the provided conditions.


87-200: Function loadApplicationPlugins looks good.

The function is well-structured and correctly loads the application-specific plugins based on the provided conditions, including the new viteMockmPlugin.

Comment on lines 12 to 31
/** @type {import('mockm/@types/config').Config} */
module.exports = util => {
const {
libObj: { mockjs },
} = util
return {
api: {
'/api/menu/all'(req, res){
const token = req.get(`Authorization`)
if (!token) {
return res.status(401).json(useResponseError('UnauthorizedException', 'Unauthorized Exception'))
}
const username = Buffer.from(token, 'base64').toString('utf8');

const menus = MOCK_MENUS.find((item) => item.username === username)?.menus ?? [];
res.json(useResponseSuccess(menus))

},
},
}
Copy link
Contributor

Choose a reason for hiding this comment

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

LGTM! Well-structured function definition.

The function defines the configuration for the mockm library, including an API endpoint for retrieving all menu items. It properly handles authorization and returns appropriate responses.

Reminder: Add tests for the new API endpoint.

The new API endpoint should have corresponding tests to ensure its functionality.

Do you want me to generate the unit testing code or open a GitHub issue to track this task?

Comment on lines 10 to 31
/** @type {import('mockm/@types/config').Config} */
module.exports = util => {
const {
libObj: { mockjs },
} = util
return {
api: {
'/api/user/info'(req, res) {
const token = req.get(`Authorization`)
if (!token) {
return res.status(401).json(useResponseError('UnauthorizedException', 'Unauthorized Exception'))
}
const username = Buffer.from(token, 'base64').toString('utf8');

const user = MOCK_USERS.find((item) => item.username === username);

const { password: _pwd, ...userInfo } = user;
res.json(useResponseSuccess(user))
},
},
}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

LGTM! Well-structured function definition.

The function defines the configuration for the mockm library, including an API endpoint for retrieving user information. It properly handles authorization and returns appropriate responses.

Reminder: Add tests for the new API endpoint.

The new API endpoint should have corresponding tests to ensure its functionality.

Do you want me to generate the unit testing code or open a GitHub issue to track this task?

Comment on lines +29 to +45
'post /api/auth/login'(req, res) {
const { password, username } = req.body;

const findUser = MOCK_USERS.find(
(item) => item.username === username && item.password === password,
);

if (!findUser) {
return res.status(403).json(useResponseError('UnauthorizedException', '用户名或密码错误'))
}

const accessToken = Buffer.from(username).toString('base64');
res.json(useResponseSuccess({
accessToken,
// TODO: refresh token
refreshToken: accessToken,
}));
Copy link
Contributor

Choose a reason for hiding this comment

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

Reminder: Generate refresh token.

There is a TODO comment for generating a refresh token.

Do you want me to generate the code for generating a refresh token or open a GitHub issue to track this task?

Comment on lines 21 to 22
$ pnpm i mockm
$ npx mm
Copy link
Contributor

Choose a reason for hiding this comment

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

Fix Markdownlint issues by removing dollar signs.

The dollar signs before the commands should be removed to comply with Markdownlint rules.

- $ pnpm i mockm
- $ npx mm
+ pnpm i mockm
+ npx mm
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
$ pnpm i mockm
$ npx mm
pnpm i mockm
npx mm
Tools
Markdownlint

21-21: null
Dollar signs used before commands without showing output

(MD014, commands-show-output)


22-22: null
Dollar signs used before commands without showing output

(MD014, commands-show-output)

Comment on lines 19 to 28
'/api/auth/codes'(req, res) {
const token = req.get(`Authorization`)
if (!token) {
return res.status(401).json(useResponseError('UnauthorizedException', 'Unauthorized Exception'))
}
const username = Buffer.from(token, 'base64').toString('utf8');

const codes = MOCK_CODES.find((item) => item.username === username)?.codes ?? [];
res.json(useResponseSuccess(codes))
},
Copy link
Contributor

Choose a reason for hiding this comment

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

Improve token validation and error handling.

The function should validate the token format and improve error handling for potential issues during token decoding.

+        if (!token || !Buffer.from(token, 'base64').toString('utf8')) {
+          return res.status(400).json(useResponseError('InvalidTokenException', 'Invalid token format'))
+        }
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
'/api/auth/codes'(req, res) {
const token = req.get(`Authorization`)
if (!token) {
return res.status(401).json(useResponseError('UnauthorizedException', 'Unauthorized Exception'))
}
const username = Buffer.from(token, 'base64').toString('utf8');
const codes = MOCK_CODES.find((item) => item.username === username)?.codes ?? [];
res.json(useResponseSuccess(codes))
},
'/api/auth/codes'(req, res) {
const token = req.get(`Authorization`)
if (!token) {
return res.status(401).json(useResponseError('UnauthorizedException', 'Unauthorized Exception'))
}
if (!token || !Buffer.from(token, 'base64').toString('utf8')) {
return res.status(400).json(useResponseError('InvalidTokenException', 'Invalid token format'))
}
const username = Buffer.from(token, 'base64').toString('utf8');
const codes = MOCK_CODES.find((item) => item.username === username)?.codes ?? [];
res.json(useResponseSuccess(codes))
},

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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between f59b222 and 28dcb81.

Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
Files selected for processing (5)
  • apps/backend-mock/api/auth.cjs (1 hunks)
  • apps/backend-mock/api/menu.cjs (1 hunks)
  • apps/backend-mock/api/user.cjs (1 hunks)
  • apps/backend-mock/get-user.cjs (1 hunks)
  • apps/backend-mock/mm.config.cjs (1 hunks)
Files skipped from review as they are similar to previous changes (3)
  • apps/backend-mock/api/auth.cjs
  • apps/backend-mock/api/menu.cjs
  • apps/backend-mock/api/user.cjs
Additional comments not posted (3)
apps/backend-mock/mm.config.cjs (3)

16-16: LGTM!

The inclusion of the getUser plugin is appropriate.


17-19: LGTM!

The proxy configuration appears correct.


58-60: LGTM!

The response handlers are well-defined and follow best practices.

Comment on lines 7 to 13
try {
const token = req.get(`Authorization`);
const username = Buffer.from(token, 'base64').toString('utf8');
req.username = username;
} catch {
// ...
}
Copy link
Contributor

Choose a reason for hiding this comment

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

Add logging for errors and improve error handling.

The current error handling is minimal and lacks logging. This can make debugging difficult.

-          } catch {
-            // ...
+          } catch (error) {
+            console.error('Error decoding Authorization header:', error);
+            res.status(400).send('Invalid Authorization header');
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
try {
const token = req.get(`Authorization`);
const username = Buffer.from(token, 'base64').toString('utf8');
req.username = username;
} catch {
// ...
}
try {
const token = req.get(`Authorization`);
const username = Buffer.from(token, 'base64').toString('utf8');
req.username = username;
} catch (error) {
console.error('Error decoding Authorization header:', error);
res.status(400).send('Invalid Authorization header');

apps/backend-mock/mm.config.cjs Outdated Show resolved Hide resolved
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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 28dcb81 and 0528a0d.

Files selected for processing (1)
  • internal/vite-config/src/config/application.ts (1 hunks)
Files skipped from review as they are similar to previous changes (1)
  • internal/vite-config/src/config/application.ts

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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 0528a0d and e911c89.

Files selected for processing (2)
  • apps/backend-mock/README.md (1 hunks)
  • apps/backend-mock/mm.config.cjs (1 hunks)
Files skipped from review as they are similar to previous changes (1)
  • apps/backend-mock/mm.config.cjs
Additional context used
Markdownlint
apps/backend-mock/README.md

9-9: null
Fenced code blocks should have a language specified

(MD040, fenced-code-language)

Additional comments not posted (4)
apps/backend-mock/README.md (4)

5-6: Description Update Approved.

The updated description accurately reflects the use of mockm and JSON-based storage, providing clear information about the new approach and its benefits.


7-16: File Structure Section Approved.

The new section detailing the project file structure is clear and provides useful information about the organization of directories and files.

Tools
Markdownlint

9-9: null
Fenced code blocks should have a language specified

(MD040, fenced-code-language)


21-22: Running Instructions Update Approved.

The updated instructions for running the application with mockm are clear and provide necessary information.


25-29: Reference Section Update Approved.

The new references to mockm documentation and code repository are useful and provide additional information for users.

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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between e911c89 and 708fb5e.

Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
Files selected for processing (5)
  • docs/src/index.md (1 hunks)
  • internal/lint-configs/eslint-config/src/configs/ignores.ts (1 hunks)
  • internal/vite-config/src/config/application.ts (1 hunks)
  • package.json (1 hunks)
  • turbo.json (1 hunks)
Files skipped from review due to trivial changes (1)
  • package.json
Files skipped from review as they are similar to previous changes (4)
  • docs/src/index.md
  • internal/lint-configs/eslint-config/src/configs/ignores.ts
  • internal/vite-config/src/config/application.ts
  • turbo.json

@wll8 wll8 closed this Aug 3, 2024
@github-actions github-actions bot locked and limited conversation to collaborators Sep 5, 2024
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant