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

chore: improve local dx #19

Merged
merged 3 commits into from
Mar 21, 2025
Merged

chore: improve local dx #19

merged 3 commits into from
Mar 21, 2025

Conversation

luxass
Copy link
Member

@luxass luxass commented Mar 21, 2025

This pull request includes several changes to improve the setup and development process for the api.mojis.dev project. The most important changes include updates to the README.md file, modifications to the package.json scripts, and enhancements to the emoji data handling scripts.

Documentation updates:

  • README.md: Added sections for installation, usage, API documentation, development, and license.

Script and configuration updates:

  • package.json: Updated the predev script to include a new setup:emoji-data script and restructured the emoji data handling scripts.

Emoji data handling improvements:

  • scripts/copy-emoji-data.ts: Added checks for the existence of the emoji data directory, created the directory if it does not exist, and updated the script to parse and copy emoji data files directly. [1] [2]
  • scripts/setup-dev/setup-worker.ts: Renamed from emoji-data-setup-app.ts and added error handling for the file upload process.
  • scripts/setup-dev/setup.ts: Added a new script to handle the setup of emoji data for development, including starting a worker and uploading the emoji data.

Summary by CodeRabbit

  • Documentation
    • Added a comprehensive project guide outlining installation, usage, and API documentation.
  • New Features
    • Introduced streamlined commands to facilitate setup and updates for emoji data.
  • Chores
    • Enhanced workflows with improved error handling and setup procedures for a smoother development experience.

Copy link

coderabbitai bot commented Mar 21, 2025

Walkthrough

This pull request adds comprehensive documentation to the project and enhances the setup and data processing scripts. It updates the README and package scripts to clearly define installation, usage, and emoji data management. The changes refactor the emoji data extraction process by directly handling file extraction and applying improved error handling in the worker functions. Additionally, new fields for metadata are introduced in the worker configuration to capture query details.

Changes

File(s) Change Summary
README.md Added detailed documentation including installation instructions, usage commands, API documentation link, development tools, and licensing information.
package.json Updated the predev script to run emoji data copy and setup sequentially. Added new scripts: setup:emoji-data and copy:emoji-data.
scripts/…/copy-emoji-data.ts & setup-dev/setup.ts Replaced worker-based upload with direct file extraction. Introduced a new setup script that reads a tar.gz emoji file, builds a request, and posts it to the API.
scripts/…/setup-worker.ts Modified error handling by replacing c.executionCtx.waitUntil with a try-catch block to await and manage multiple promises for better error reporting.
worker-configuration.d.ts Added optional properties (served_by_region, served_by_primary, and timings) to the D1Meta interface for enhanced query execution metadata.

Sequence Diagram(s)

sequenceDiagram
    participant Setup as Setup Script
    participant FS as File System
    participant API as "api.mojis.dev/upload"
    Setup->>FS: Read compressed emoji data file
    FS-->>Setup: Return file data (tar.gz)
    Setup->>Setup: Parse file and create Blob/FormData
    Setup->>API: Send POST request with emoji data
    API-->>Setup: Return JSON response
    Setup->>Setup: Log response and dispose worker
Loading

Possibly related PRs

Poem

I'm a rabbit on a coding spree,
Hopping through scripts so merrily.
Docs and data now hop in line,
Error handling so neat and fine.
With every byte, I wiggle with glee! 🐇💻

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

  • 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 generate docstrings to generate docstrings for 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.

@luxass luxass merged commit d2f33b0 into main Mar 21, 2025
3 of 4 checks passed
@luxass luxass deleted the improve-local-dx branch March 21, 2025 04:52
Copy link

@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

🧹 Nitpick comments (12)
scripts/setup-dev/setup.ts (2)

14-15: Add error handling for file reading operation

The file reading operation doesn't have specific error handling. If the emoji-data.tar.gz file doesn't exist, it will throw a generic error.

-  const file = await readFile(path.join(root.toString(), "./node_modules/.emoji-data/emoji-data.tar.gz"));
-  const blob = new Blob([file]);
+  try {
+    const filePath = path.join(root.toString(), "./node_modules/.emoji-data/emoji-data.tar.gz");
+    const file = await readFile(filePath);
+    const blob = new Blob([file]);
+  } catch (err) {
+    console.error(`Failed to read emoji data file: ${err.message}`);
+    throw new Error("Emoji data file not found. Run 'pnpm run copy:emoji-data' first.");
+  }

4-4:

❓ Verification inconclusive

Consider using the stable API if available

The script uses unstable_startWorker which suggests it's using an experimental API that might change in future versions of wrangler.


🏁 Script executed:

#!/bin/bash
# Check if there's a stable API alternative to unstable_startWorker
grep -r "startWorker" --include="*.d.ts" node_modules/wrangler/

Length of output: 119


Review Verification: Verify Experimental API Usage

After checking the repository, our initial search for a stable alternative to unstable_startWorker in the wrangler package was inconclusive (the expected files from the wrangler dependency weren’t available). Since we couldn’t confirm a stable API option via the code search, please verify with the official wrangler documentation or your local setup to determine if a stable API has been introduced.

  • File: scripts/setup-dev/setup.ts
  • Line: 4 (usage of unstable_startWorker)

If a stable API becomes available, update the import accordingly. Otherwise, ensure that using the experimental API is safe for your workflow.

scripts/copy-emoji-data.ts (3)

22-35: Add error handling for tar parsing operation

The tar parsing operation could fail if the blob contains invalid data, but there's no specific error handling for this operation.

 const filePrefix = "emoji-data-main/data/";

-const tar = await parseTarGzip(await blob.arrayBuffer(), {
-  filter(file) {
-    if (!file.name.startsWith(filePrefix) || !file.name.endsWith(".json")) {
-      return false;
-    }
-
-    // remove the file prefix
-    file.name = file.name.slice(filePrefix.length);
-
-    return true;
-  },
-});
+try {
+  const tar = await parseTarGzip(await blob.arrayBuffer(), {
+    filter(file) {
+      if (!file.name.startsWith(filePrefix) || !file.name.endsWith(".json")) {
+        return false;
+      }
+
+      // remove the file prefix
+      file.name = file.name.slice(filePrefix.length);
+
+      return true;
+    },
+  });
+} catch (err) {
+  console.error(`Failed to parse emoji data: ${err.message}`);
+  throw new Error("Invalid emoji data format");
+}

37-41: Add more granular error handling for file writing operations

The file writing operations could fail individually, but there's no specific error handling for these operations.

 for await (const file of tar) {
-  const filePath = path.join(root.toString(), "./node_modules/.emoji-data", file.name);
-  await mkdir(path.dirname(filePath), { recursive: true });
-  await writeFile(filePath, file.text);
+  try {
+    const filePath = path.join(root.toString(), "./node_modules/.emoji-data", file.name);
+    await mkdir(path.dirname(filePath), { recursive: true });
+    await writeFile(filePath, file.text);
+  } catch (err) {
+    console.error(`Failed to write file ${file.name}: ${err.message}`);
+    // Continue with other files instead of failing the entire process
+  }
 }

43-43: Add progress indication for better user experience

Consider adding progress indication to inform the user about the copying process, especially useful for large data sets.

+let fileCount = 0;
 for await (const file of tar) {
   const filePath = path.join(root.toString(), "./node_modules/.emoji-data", file.name);
   await mkdir(path.dirname(filePath), { recursive: true });
   await writeFile(filePath, file.text);
+  fileCount++;
 }

-console.log("emoji data copied");
+console.log(`emoji data copied: ${fileCount} files processed`);
scripts/setup-dev/setup-worker.ts (1)

68-68: Update console log message to match the new file name

The console log message still references "emoji data setup app" despite the file being renamed to "setup-worker.ts".

-console.log("started the emoji data setup app");
+console.log("started the emoji data setup worker");
README.md (6)

1-4: Project Title and Description Clarity
The title (“# api.mojis.dev”) and the one-line description (“A RESTful API for accessing emoji data.”) clearly introduce the project. Consider adding a brief summary of key features or benefits below this description to provide new users with a quick overview of what the API offers.


5-12: Installation Instructions Completeness
The installation section is clear and provides concise commands to clone the repository and install dependencies using pnpm. It may be worthwhile to note explicitly that pnpm is required, or include a link to the pnpm installation guide for those less familiar with it.


13-17: Usage Command Simplicity
The usage section, with the command pnpm run dev, is straightforward and gives a clear starting point for running the development server. If there are any required environment variables or additional setup steps, consider mentioning them here to further improve local DX.


19-22: Emoji Data Handling Note Enhancement
The note explains that emoji data will be copied from mojis/emoji-data into the node_modules/.emoji-data directory and provides an update command using pnpm run copy:emoji-data. Since the PR objectives mention improvements in emoji data handling—including a new setup:emoji-data script—it might be helpful to clarify when to use each script or add a brief reference to the new setup process.


23-26: API Documentation Section
The API Documentation section is succinct and includes a direct link to api.mojis.dev using Scalar. For extra clarity, consider adding a brief outline of what users can expect to find in the documentation (e.g., list of endpoints, usage examples).


27-35: Development Tools Overview
The development section effectively lists the frameworks and tools used in the project (Hono, Cloudflare Workers, Vitest, and Scalar). Given the enhancements mentioned in the PR objectives—such as changes to setup scripts like setup:emoji-data—you might include a brief note or link to further documentation on these new scripts to enhance the local developer experience.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d2b1082 and 7a0fcde.

📒 Files selected for processing (6)
  • README.md (1 hunks)
  • package.json (1 hunks)
  • scripts/copy-emoji-data.ts (2 hunks)
  • scripts/setup-dev/setup-worker.ts (1 hunks)
  • scripts/setup-dev/setup.ts (1 hunks)
  • worker-configuration.d.ts (2 hunks)
🔇 Additional comments (9)
worker-configuration.d.ts (1)

4619-4629: Enhanced D1 metadata provides valuable query insights

These additions to the D1Meta interface provide useful information about database queries:

  • served_by_region indicates which geographical region handled the query
  • served_by_primary shows whether the primary database instance processed the query
  • timings.sql_duration_ms captures the execution time, excluding network latency

These properties will help with monitoring database performance, troubleshooting regional issues, and understanding query execution patterns in distributed environments.

scripts/setup-dev/setup.ts (3)

9-12: LGTM! Well-structured worker initialization

The worker configuration is properly set up with the correct paths to the config file and entrypoint.


35-38: LGTM! Proper error handling in main function

The error handling for the main function is well-implemented, properly catching errors and exiting the process with a non-zero status code.


20-25:

❓ Verification inconclusive

Improve request error handling and remove ts-expect-error

The request doesn't check if the response was successful, and there's a TypeScript error suppression without explanation.

 console.log("sending request to worker");
 const res = await worker.fetch("https://api.mojis.dev/upload", {
   method: "POST",
-  // @ts-expect-error hmmm
   body: formData,
 });

+ if (!res.ok) {
+   const text = await res.text();
+   throw new Error(`Failed to upload emoji data: ${res.status} ${text}`);
+ }

To resolve the ts-expect-error, consider using proper type annotations or creating a typed wrapper for the fetch API.


🏁 Script executed:

#!/bin/bash
# Check the wrangler worker fetch method type definition
grep -A 10 "fetch" --include="*.d.ts" node_modules/wrangler/

Length of output: 116


Improve fetch error handling and ensure proper type annotations in setup.ts

The updated diff should:

  • Remove the @ts-expect-error comment and replace it with proper type handling.
  • Add error checking to throw a descriptive error when the response isn’t successful.
  • Note: The verification of the worker’s fetch type definition was inconclusive (the grep command failed to locate the expected files). Please manually verify or update the import of the correct type definitions (e.g., from an alternative package like @cloudflare/workers-types if applicable) to safely remove error suppressions.
 console.log("sending request to worker");
 const res = await worker.fetch("https://api.mojis.dev/upload", {
   method: "POST",
-  // @ts-expect-error hmmm
   body: formData,
 });

+ if (!res.ok) {
+   const text = await res.text();
+   throw new Error(`Failed to upload emoji data: ${res.status} ${text}`);
+ }
scripts/copy-emoji-data.ts (2)

1-5: LGTM! Good imports for file operations

Appropriate imports for file system operations and the parseTarGzip library.


10-12: LGTM! Directory existence check and creation

Good practice to check if the directory exists before attempting to create it.

scripts/setup-dev/setup-worker.ts (1)

54-64: LGTM! Improved error handling with try-catch block

The addition of a try-catch block greatly improves error handling during the file upload process. The response now properly indicates success or failure with an appropriate HTTP status code.

One small suggestion to make the error message more helpful:

 try {
   await Promise.all(promises);
   return c.json({
     message: "Files uploaded",
   });
 } catch (err) {
   console.error(err);
   return c.json({
-    message: "Failed to upload files",
+    message: `Failed to upload files: ${err.message}`,
   }, 500);
 }
package.json (1)

10-12: LGTM! Well-structured scripts for emoji data handling

The updated script organization provides a clearer separation of concerns between copying and setting up emoji data. The predev script now properly runs both steps sequentially.

README.md (1)

36-38: License Information Accuracy
The license section clearly states that the project is published under the MIT License. This information is accurate and requires no further changes.

@coderabbitai coderabbitai bot mentioned this pull request Mar 22, 2025
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