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

Aggiunto endpoint API per generare il curriculum #150

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

Conversation

Merluzzo93
Copy link

@Merluzzo93 Merluzzo93 commented Oct 7, 2024

Summary by CodeRabbit

  • New Features

    • Introduced a new API endpoint for generating resumes via POST requests.
    • Added functionality to render resumes based on user-provided data and themes.
  • Bug Fixes

    • Improved error handling for missing resume data and invalid request methods.

Copy link

changeset-bot bot commented Oct 7, 2024

⚠️ No Changeset found

Latest commit: c364bc2

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 Oct 7, 2024

@Merluzzo93 is attempting to deploy a commit to the JSON Resume Team on Vercel.

A member of the Team first needs to authorize it.

Copy link
Contributor

coderabbitai bot commented Oct 7, 2024

Walkthrough

The changes introduce a new function renderResume in apps/registry/lib/renderResume.js for rendering resumes using Handlebars templates. Additionally, a new API endpoint is created in apps/registry/pages/api/generate-resume.js to handle POST requests for generating resumes. This endpoint validates the request, extracts necessary data, and utilizes renderResume to produce a base64-encoded data URL of the rendered resume, responding with appropriate status codes based on the request's validity and processing outcomes.

Changes

File Path Change Summary
apps/registry/lib/renderResume.js Added: async function renderResume(resumeData, theme) to render a resume using Handlebars templates.
apps/registry/pages/api/generate-resume.js Added: async function handler(req, res) to handle POST requests for generating resumes and return a data URL.

Poem

🐰 In the meadow where resumes bloom,
A function was crafted to chase away gloom.
With themes and data, it weaves a fine tale,
Generating dreams where careers set sail.
So hop along, let the new endpoint play,
For every rabbit's resume, a bright new day! 🌼


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

🧹 Outside diff range and nitpick comments (2)
apps/registry/lib/renderResume.js (1)

5-5: Add JSDoc for better documentation and type hinting

To improve code readability and maintainability, consider adding JSDoc comments to describe the function, its parameters, and return value. This will provide better documentation and enable IDE type hinting.

Here's a suggested addition:

/**
 * Renders a resume using the specified theme.
 * @param {Object} resumeData - The data to be rendered in the resume.
 * @param {string} theme - The name of the theme to be used.
 * @returns {Promise<string>} The rendered resume HTML.
 */
export async function renderResume(resumeData, theme) {
apps/registry/pages/api/generate-resume.js (1)

4-6: LGTM: HTTP method check is correct.

The check for POST method is appropriate. Consider using a constant for the status code to improve maintainability.

You could refactor the status code as follows:

+ const METHOD_NOT_ALLOWED = 405;
- return res.status(405).json({ error: 'Metodo non consentito' });
+ return res.status(METHOD_NOT_ALLOWED).json({ error: 'Metodo non consentito' });
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 40b46fe and c364bc2.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (2)
  • apps/registry/lib/renderResume.js (1 hunks)
  • apps/registry/pages/api/generate-resume.js (1 hunks)
🧰 Additional context used
🔇 Additional comments (2)
apps/registry/pages/api/generate-resume.js (2)

1-3: LGTM: Import and function declaration are correct.

The import statement and the async function declaration follow best practices for a Next.js API route.


17-21: 🛠️ Refactor suggestion

Consider enhancing the response and verify data URL usage.

The current implementation works, but consider the following suggestions:

  1. Include additional metadata in the response, such as the theme used and a timestamp.
  2. Consider offering multiple format options (e.g., HTML, PDF) based on client requirements.

Also, please verify that the client-side code correctly handles and displays the data URL. Run the following script to check for proper data URL handling in the frontend code:

import Handlebars from 'handlebars';

export async function renderResume(resumeData, theme) {
const themePath = join(process.cwd(), '..', '..', 'themes', theme);
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Use a more robust method for theme path construction

The current path construction method uses multiple .. to navigate the directory structure. This approach can be fragile if the directory structure changes. Consider using a configuration file or environment variable to store the base path to the themes directory.

Here's a suggested approach:

import { config } from '../config'; // Assume we have a config file

// In the function
const themePath = join(config.themesBasePath, theme);

Comment on lines +7 to +10
const templateContent = readFileSync(join(themePath, 'resume.hbs'), 'utf8');
const template = Handlebars.compile(templateContent);

return template(resumeData);
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add error handling and input validation

The current implementation lacks error handling for file reading and template compilation. It also doesn't validate the inputs. This could lead to unhandled exceptions and potential security issues.

Consider adding the following improvements:

  1. Validate inputs:

    if (typeof theme !== 'string' || !theme.trim()) {
      throw new Error('Invalid theme specified');
    }
    if (typeof resumeData !== 'object' || resumeData === null) {
      throw new Error('Invalid resume data');
    }
  2. Add error handling:

    try {
      const templateContent = await readFile(join(themePath, 'resume.hbs'), 'utf8');
      const template = Handlebars.compile(templateContent);
      return template(resumeData);
    } catch (error) {
      if (error.code === 'ENOENT') {
        throw new Error(`Theme '${theme}' not found`);
      }
      throw new Error(`Error rendering resume: ${error.message}`);
    }

These changes will make the function more robust and easier to debug.

Comment on lines +1 to +3
import { readFileSync } from 'fs';
import { join } from 'path';
import Handlebars from 'handlebars';
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Consider using asynchronous file reading

The function is declared as asynchronous, but it uses readFileSync which is a blocking operation. Consider using the asynchronous version readFile from the fs/promises module to maintain consistency and prevent potential performance issues.

Here's a suggested change:

-import { readFileSync } from 'fs';
+import { readFile } from 'fs/promises';
import { join } from 'path';
import Handlebars from 'handlebars';
📝 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
import { readFileSync } from 'fs';
import { join } from 'path';
import Handlebars from 'handlebars';
import { readFile } from 'fs/promises';
import { join } from 'path';
import Handlebars from 'handlebars';

Comment on lines +9 to +15
const { resumeData, theme = 'elegant' } = req.body;

if (!resumeData) {
return res
.status(400)
.json({ error: 'I dati del curriculum sono obbligatori' });
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Enhance request body validation.

While the current validation checks for the presence of resumeData, it could be more robust. Consider the following improvements:

  1. Validate the structure of resumeData to ensure it contains all necessary fields.
  2. Validate the theme value against a list of allowed themes.
  3. Use a validation library like Joi or Yup for more comprehensive input validation.

Example implementation:

const allowedThemes = ['elegant', 'modern', 'classic'];
const { resumeData, theme = 'elegant' } = req.body;

if (!resumeData || typeof resumeData !== 'object') {
  return res.status(400).json({ error: 'I dati del curriculum sono obbligatori e devono essere un oggetto' });
}

if (!allowedThemes.includes(theme)) {
  return res.status(400).json({ error: 'Tema non valido' });
}

// Additional validation for resumeData structure could be added here

Comment on lines +22 to +25
} catch (error) {
console.error(error);
res.status(500).json({ error: 'Errore interno del server' });
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Improve error handling and logging.

While the current error handling catches errors, it could be improved:

  1. Use a logging library (e.g., Winston, Pino) for structured logging and log rotation.
  2. Consider adding more context to the logged error, such as request details (excluding sensitive information).
  3. In non-production environments, consider returning more detailed error information to aid in debugging.

Example implementation:

import logger from '../../lib/logger';  // Assume this is your logging setup

// In the catch block:
logger.error('Error generating resume', {
  error: error.message,
  stack: process.env.NODE_ENV !== 'production' ? error.stack : undefined,
  requestId: req.headers['x-request-id'],  // Assuming you're using request IDs
});

const errorResponse = process.env.NODE_ENV === 'production'
  ? { error: 'Errore interno del server' }
  : { error: error.message, stack: error.stack };

res.status(500).json(errorResponse);

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