• AI Fire
  • Posts
  • ⚔ Advanced ChatGPT Prompts For Devs: Optimize Coding

⚔ Advanced ChatGPT Prompts For Devs: Optimize Coding

Boost productivity with 16 Advanced ChatGPT Prompts - enhance code quality, debugging, and integrate AI to streamline your dev process with ease now.

What’s your biggest coding challenge?

Login or Subscribe to participate in polls.

1. Introduction To Advanced ChatGPT Prompts For Devs

advanced-chatgpt-prompts-for-devs

As a developer, you’ve probably used ChatGPT for simple tasks like writing a function or explaining an error. But with the right approach, ChatGPT can become a powerful assistant, helping you automate workflows, create professional documentation, or prepare for interviews at top tech companies like Atlassian or Stripe. Advanced ChatGPT Prompts for Developers are carefully crafted questions that provide enough context to get high-quality, actionable results, from CI/CD pipelines to custom study plans.

These prompts save time, improve code quality, and help you solve complex problems. For instance, you can ask ChatGPT to build a complete CI/CD pipeline or analyze system architecture. In this article, I’ll share 16 powerful prompts, starting with one to automate the CI/CD for your project.

Key Benefits:

  • Save time on repetitive tasks like writing tests or docs.

  • Get optimized code and solutions for performance and security.

  • Support for everything from coding to interviewing at companies like Shopify.

2. Advanced ChatGPT Prompts For Devs: Automate CI/CD Pipelines

Setting up a CI/CD pipeline is key to automating your project’s build, test, and deployment process. But configuring one from scratch, especially with platforms like CircleCI or Render, can be time-consuming. With Advanced ChatGPT Prompts for Developers, you can ask ChatGPT to create a full pipeline, complete with configuration and setup guides, in minutes.

Purpose:
Build an automated CI/CD pipeline for a project, such as a Python app, with steps for building, testing, security checks, and deployment.

General Prompt Template:

I need to build a CI/CD pipeline for my project. Please create a complete pipeline with the following details:

Project Info: 
Tech stack: [Language, framework, database, testing tool].
Repository: [Code hosting platform, e.g., Bitbucket].
Deployment platform: [Service, e.g., Render].
Security requirements: [Security tool, e.g., safety].

Pipeline Requirements:
Build: Set up the environment and install dependencies.
Test: Run unit tests to verify code.
Security check: Run security tool, stop pipeline if critical issues are found.
Deploy: Deploy to the service if all steps pass.
Documentation: Provide setup instructions for the repository.

Expected Output:
Configuration file (YAML/JSON) for build, test, security, and deploy steps.
Brief explanation of each step.
Setup guide: How to add the config file to the repository and set up the deployment service.
Maintenance notes (e.g., updating versions, handling deploy errors).
Please format the config file in a code block and provide documentation in markdown.

Specific Example Prompt:

I’m building a CI/CD pipeline for a Python project using CircleCI. Please design a complete pipeline with the following details:

Project Info: 
Project: Python web app using Django and PostgreSQL.
Tech stack: Python 3.10, Django, PostgreSQL, Pytest (for unit tests).
Repository: Bitbucket.
Deployment platform: Render.
Security requirements: Run safety to check for vulnerabilities in Python libraries.

Pipeline Requirements:
Build: Set up Python 3.10 environment and install dependencies.
Test: Run unit tests with Pytest to ensure code works.
Security check: Perform safety check and stop pipeline if critical vulnerabilities are found.
Deploy: Deploy to Render if all steps pass.
Documentation: Provide instructions for adding the config file to Bitbucket.

Expected Output:
CircleCI config file (YAML) with build, test, security, and deploy steps.
Brief explanation of each step in the pipeline.
Setup guide: How to add the YAML file to Bitbucket and configure Render.
Maintenance notes (e.g., updating Python version, handling deploy errors).
Please format the YAML file in a code block and provide documentation in markdown.

Expected Output:

version: 2.1
jobs:
  build-and-test:
    docker:
      - image: cimg/python:3.10
    steps:
      - checkout
      - run:
          name: Install dependencies
          command: pip install -r requirements.txt
      - run:
          name: Run tests
          command: pytest
      - run:
          name: Security check
          command: pip install safety && safety check --full-report
  deploy:
    docker:
      - image: cimg/python:3.10
    steps:
      - checkout
      - run:
          name: Deploy to Render
          command: curl -X POST https://api.render.com/v1/services/$RENDER_SERVICE_ID/deploy -H "Authorization: Bearer $RENDER_API_KEY"
workflows:
  ci-cd:
    jobs:
      - build-and-test
      - deploy:
          requires:
            - build-and-test
          filters:
            branches:
              only: main

Brief Explanation:

  • Checkout: Fetches code from Bitbucket.

  • Install dependencies: Installs Python libraries from requirements.txt.

  • Run tests: Executes unit tests with Pytest.

  • Security check: Checks for library vulnerabilities with safety.

  • Deploy: Deploys to Render if all steps pass.

Benefits:

  • Saves hours setting up pipelines.

  • Ensures code is thoroughly tested before deployment.

  • Easy to maintain with clear documentation.

3. Advanced ChatGPT Prompts For Devs: System Architecture Analysis

system-architecture-analysis

Selecting the right architecture for a large system is critical to a project’s success. A poor choice can lead to performance bottlenecks, scaling challenges, or budget overruns. With Advanced ChatGPT Prompts for Developers, you can ask ChatGPT to analyze architecture options, compare trade-offs, and provide a clear recommendation, enabling informed decisions.

Purpose:
Analyze and select a system architecture based on performance, scalability, security, and cost, such as for an e-commerce web app deployed on Vercel.

General Prompt Template:

I need to evaluate architecture options for a system. Please analyze with the following details:

Project Info: 
System type: [Describe system, e.g., web app].
Tech stack: [Language, framework, database].
Requirements: [Expected load, security needs, budget].

Analysis Requirements:
Suggest at least three different architectures.
Compare performance, scalability, security, and cost.
Provide a recommendation with specific reasoning.

Output:
Brief description of each architecture.
Comparison table in markdown.
Final recommendation with detailed explanation.
Please format the comparison table in markdown and the recommendation as clear text.

Specific Example Prompt:

I need to evaluate architecture options for an e-commerce web app. Please analyze with the following details:

Project Info:
System type: E-commerce web app with 10,000 daily active users.
Tech stack: Node.js, React, Supabase (PostgreSQL).
Requirements: Handle 1,000 transactions/minute, high security (GDPR compliance), budget under $500/month.

Analysis Requirements:
Suggest three architectures: Monolithic, Microservices, Serverless.
Compare performance, scalability, cost, and security.
Provide a recommendation with specific reasoning.

Output:
Brief description of each architecture.
Comparison table in markdown.
Final recommendation with detailed explanation.
Please format the comparison table in markdown and the recommendation as clear text.

Output:
Architecture Descriptions:

  • Monolithic: The entire application is built as a single codebase. Easy to develop and deploy initially, but hard to scale with high traffic. Works well with Supabase for database management.

  • Microservices: The system is composed of independent services (e.g., product, payment services). Highly scalable and maintainable, but requires complex management. Integrates well with Node.js/React and Supabase.

  • Serverless: Uses serverless functions (e.g., Vercel Functions) to process requests. Automatically scales with no server management, but costs can rise with high traffic.

Comparison Table:

Criterion

Monolithic

Microservices

Serverless

Performance

Moderate (depends on optimization)

High (optimized per service)

High (auto-optimized)

Scalability

Low (hard to distribute load)

High (independent services)

Very high (auto-scaling)

Security

Moderate (single point of failure)

High (isolated services, GDPR-compliant)

High (Vercel-managed, GDPR-compliant)

Cost

~$300/month (Vercel + Supabase)

~$450/month (multiple services)

~$550/month (traffic-dependent)

Recommendation:
Microservices are the optimal choice for this e-commerce web app. With 10,000 daily active users and 1,000 transactions per minute, Microservices allow independent scaling of critical services (e.g., payment or product catalog), ensuring high performance. Supabase’s PostgreSQL support efficiently manages transactional data, and Node.js/React aligns well with this architecture. Security-wise, Microservices enable isolating sensitive services, meeting GDPR requirements. The estimated cost of ~$450/month fits within the $500 budget. However, invest in monitoring tools (e.g., Datadog) to manage services effectively. Monolithic is viable for early stages but struggles with scalability, while Serverless, though flexible, risks exceeding the budget with high traffic.

Benefits:

  • Enables decisions based on detailed, project-specific analysis.

  • Saves time comparing architecture options.

  • Supports large-scale app development on Vercel with Supabase.

4. Create Technical Documentation

create-technical-documentation

Clear and professional technical documentation enables development teams to work efficiently, but writing it is often time-consuming and overlooked. With Advanced ChatGPT Prompts for Developers, you can ask ChatGPT to generate detailed documentation for APIs, libraries, or modules, including technical specs, usage examples, and error handling, saving time and improving documentation quality.

Purpose:
Create comprehensive technical documentation for a software component, such as an API for an e-commerce web app deployed on Vercel.

General Prompt Template:

I need technical documentation for a software component. Please create documentation with the following details:

Component Info:
Name: [Component name, e.g., API].
Tech stack: [Language, framework, database].
Purpose: [Main functionality].

Documentation Requirements:
Overview: Describe functionality and purpose.
Technical specs: Define API (endpoints, parameters, return values).
Usage examples: Provide basic and advanced examples.
Troubleshooting: List common errors and solutions.

Output:
Documentation in markdown with code blocks.
Table for API specs (if applicable).
Please ensure the documentation is clear and developer-friendly.

Specific Example Prompt:

I need technical documentation for an API of an e-commerce web app. Please create documentation with the following details:

Component Info:
Name: Product API.
Tech stack: Node.js, Express, Supabase (PostgreSQL).
Purpose: Manage product listings (create, read, update, delete).

Documentation Requirements:
Overview: Describe functionality and purpose.
Technical specs: Define API (endpoints, methods, parameters, return values).
Usage examples: Provide basic (fetch product list) and advanced (create product) examples.
Troubleshooting: List at least two common errors and solutions.

Output:
Documentation in markdown with code blocks.
Table for API specs.
Please ensure the documentation is clear and developer-friendly.

Output:

Product API Documentation

Overview

The Product API enables management of product listings in an e-commerce web app, supporting create, read, update, and delete (CRUD) operations. Built with Node.js using the Express framework and Supabase (PostgreSQL) for data storage, this API is designed for deployment on Vercel, ensuring high performance and reliability.

Technical Specs

Endpoint

Method

Parameters

Returns

/products

GET

limit (query, number, default 10), offset (query, number, default 0)

List of products (JSON)

/products/:id

GET

id (path, number)

Product details (JSON)

/products

POST

name (body, string, required), price (body, number, required)

New product (JSON)

/products/:id

PUT

id (path, number), name (body, string), price (body, number)

Updated product (JSON)

/products/:id

DELETE

id (path, number)

Deletion confirmation (JSON)

Usage Examples

Basic: Fetch product list

curl "http://api.example.com/products?limit=5&offset=0"

Response:

[
  { "id": 1, "name": "Dell XPS Laptop", "price": 1200 },
  { "id": 2, "name": "Sony Headphones", "price": 150 }
]

Advanced: Create a new product

curl -X POST http://api.example.com/products \
  -H "Content-Type: application/json" \
  -d '{"name":"iPhone 14","price":999}'

Response:

{ "id": 3, "name": "iPhone 14", "price": 999 }

Troubleshooting

  • 400 Bad Request: Missing or invalid name or price in POST/PUT requests.
    Solution: Verify request body includes name as a non-empty string and price as a positive number, e.g., {"name":"Product","price":100}.

  • 500 Internal Server Error: Failed connection to Supabase.
    Solution: Check SUPABASE_URL and SUPABASE_KEY environment variables in Vercel. Test connectivity by running a query in the Supabase dashboard.

Benefits:

  • Generates professional documentation quickly.

  • Provides clear, developer-friendly information for teams and API users.

  • Reduces manual documentation effort, ideal for projects on Vercel.

5. Advanced ChatGPT Prompts For Devs: Effective Debugging

effective-debugging

Debugging is a critical part of software development, but pinpointing the root cause of an issue can be time-consuming. With Advanced ChatGPT Prompts for Developers, you can ask ChatGPT to analyze errors, suggest potential causes, and provide detailed fixes, enabling you to resolve issues quickly and accurately.

Purpose:
Diagnose and fix errors in code or systems, such as API issues in a Node.js app deployed on Vercel.

General Prompt Template:

I’m facing an error in my project. Please help me debug with the following details:

Error Info:
Symptoms: [Describe the issue].
Environment: [Language, framework, deployment platform].
Error logs: [Error messages or logs].

Requirements:
Suggest at least three possible causes for the error.
Provide steps to verify each cause.
Offer detailed fixes for each cause.

Output:
List of causes and verification steps (markdown).
Detailed fixes with code blocks if needed.
Please ensure explanations are clear and developer-friendly.

Specific Example Prompt:

I’m facing an error in a Node.js application. Please help me debug with the following details:

Error Info:
Symptoms: The /users API returns a 500 error when fetching user lists.
Environment: Node.js 18, Express, Supabase (PostgreSQL), deployed on Vercel.
Error logs: Error: Connection timeout at Supabase client.

Requirements:
Suggest at least three possible causes for the error.
Provide steps to verify each cause.
Offer detailed fixes for each cause.

Output:
List of causes and verification steps (markdown).
Detailed fixes with code blocks if needed.
Please ensure explanations are clear and developer-friendly.

Output:

Debugging /users API 500 Error

Possible Causes

  1. Incorrect Supabase configuration: Missing or incorrect SUPABASE_URL or SUPABASE_KEY environment variables.

  2. Overloaded database query: SQL query returns too much data, causing a timeout.

  3. Vercel limits: Execution time exceeds serverless function limit (10 seconds for free plan).

Verification Steps

  • Supabase configuration:

    • Check environment variables in Vercel dashboard (SUPABASE_URL, SUPABASE_KEY).

    • Log the URL to confirm: console.log(process.env.SUPABASE_URL).

  • Database query:

    • Copy the query from code and run it in Supabase dashboard.

    • Check the number of returned records (keep below 100 to avoid timeout).

  • Vercel limits:

    • Review Vercel dashboard logs for timeout errors.

    • Measure API execution time using tools like Postman.

Fixes

  1. Supabase configuration:

    • Update environment variables in Vercel.

    • Test Supabase connection:

      const { createClient } = require('@supabase/supabase-js');
      const supabase = createClient(process.env.SUPABASE_URL, process.env.SUPABASE_KEY);
      async function testConnection() {
        const { data, error } = await supabase.from('users').select('id').limit(1);
        if (error) console.error('Connection error:', error);
        else console.log('Connection OK');
        return { data, error };
      }
      testConnection();
      
  2. Database query:

    • Optimize query by limiting columns and records:

      const { data, error } = await supabase.from('users').select('id, name').limit(50);
      if (error) throw error;
      
    • Add an index on the users table (e.g., on id or name) in Supabase to speed up queries.

  3. Vercel limits:

    • Split queries using pagination:

      const { data, error } = await supabase.from('users').select('id, name').range(0, 49);
      if (error) throw error;
      
    • If issues persist, upgrade to Vercel’s Pro plan for a 30-second execution limit.

Benefits:

  • Identifies error causes quickly with clear verification steps.

  • Provides detailed fixes, reducing debugging time.

  • Applicable to various API or database errors in projects on Vercel.

Learn How to Make AI Work For You!

Transform your AI skills with the AI Fire Academy Premium Plan - FREE for 14 days! Gain instant access to 500+ AI workflows, advanced tutorials, exclusive case studies and unbeatable discounts. No risks, cancel anytime.

Start Your Free Trial Today >>

6. Optimize Git Workflow

Efficient Git workflow management is key to seamless collaboration in software projects, but issues like branch conflicts or messy commit histories can slow progress. With Advanced ChatGPT Prompts for Developers, you can ask ChatGPT to analyze your Git repository state, suggest resolution steps, and provide precise Git commands to streamline your workflow.

Purpose:
Handle complex Git scenarios, such as resolving branch conflicts or cleaning up commit history in a repository hosted on GitLab.

General Prompt Template:

I need to optimize my Git workflow for a project. Please assist with the following details:

Git Repository Info:
Current state: [Describe branches, commits, conflicts].
Platform: [GitLab, Bitbucket, etc.].
Goal: [Merge branches, clean history, etc.].

Requirements:
Analyze the repository state and identify issues.
Suggest resolution steps with Git commands.
Briefly explain each command.

Output:
Repository state analysis (markdown).
Resolution steps with Git commands in code blocks and explanations.
Please ensure Git commands are accurate and explanations are clear.

Specific Example Prompt:

I need to optimize my Git workflow for a project. Please assist with the following details:

Git Repository Info:
Current state: The feature/payment branch conflicts with main after a merge attempt. The feature/payment branch has a messy commit history with multiple small commits.
Platform: GitLab.
Goal: Resolve conflicts, squash small commits into one, and merge into main.

Requirements:
Analyze the repository state and identify issues.
Suggest resolution steps with Git commands.
Briefly explain each command.

Output:
Repository state analysis (markdown).
Resolution steps with Git commands in code blocks and explanations.
Please ensure Git commands are accurate and explanations are clear.

Output:

Optimizing Git Workflow for feature/payment Branch

Repository State Analysis

  • Merge conflicts: The feature/payment branch conflicts with main due to overlapping changes (e.g., in payment.js).

  • Messy commit history: The feature/payment branch has multiple small commits (e.g., "fix typo", "update function"), making the history hard to read.

  • Goal on GitLab: Resolve conflicts, squash commits into one, and merge into main for a clean history.

Resolution Steps

  1. Switch to feature/payment and fetch main:

    git checkout feature/payment
    git fetch origin
    git merge origin/main

Explanation: Switches to feature/payment, fetches updates from main on GitLab, and attempts a merge. This will trigger conflict notifications.

  1. Resolve conflicts:

    # Check conflicted files (e.g., payment.js)
    git status
    # Edit payment.js to resolve conflicts, keeping desired changes
    git add payment.js
    git commit
    

    Explanation: Uses git status to identify conflicted files, manually resolves conflicts in an editor (e.g., VS Code), then adds and commits to complete the merge.

  2. Squash small commits into one:

    git reset --soft $(git merge-base feature/payment origin/main)
    git commit -m "Implement payment feature with validation and error handling"
    

    Explanation: git reset --soft preserves changes but removes commit history back to the merge base with main. A new commit consolidates all changes with a clear message.

  3. Push to GitLab and merge into main:

    git push origin feature/payment --force
    git checkout main
    git pull origin main
    git merge feature/payment
    git push origin main
    

    Explanation: Pushes the rewritten branch to GitLab (--force due to history change). Switches to main, pulls updates, merges feature/payment, and pushes to GitLab.


**Benefits**:  
- Resolves conflicts and cleans commit history efficiently.  
- Provides accurate Git commands for easy execution.  
- Enhances repository management on GitLab.

7. Advanced ChatGPT Prompts For Devs: Optimize Code Performance

Code performance is critical for ensuring applications run quickly and efficiently, especially in large systems. However, identifying and fixing inefficient code can be time-consuming. With Advanced ChatGPT Prompts for Developers, you can ask ChatGPT to analyze code, pinpoint performance issues, and suggest optimizations, improving speed and reliability.

Purpose:
Optimize code performance, such as improving database queries in a Node.js app deployed on Vercel.

General Prompt Template:

I need to optimize code performance in my project. Please assist with the following details:

Code Info:
Language: [Programming language].
Code snippet: [Code to optimize].
Environment: [Framework, deployment platform].
Issue: [Performance symptom, e.g., slow response time].

Requirements:
Analyze the code and identify performance issues.
Suggest at least three optimizations with modified code.
Explain the benefits of each optimization.

Output:
Performance issue analysis (markdown).
Optimizations with code blocks and explanations.
Please ensure modified code is accurate and explanations are clear.

Specific Example Prompt:

I need to optimize code performance in a Node.js application. Please assist with the following details:
Code Info:

  • Language: JavaScript (Node.js 18).

  • Code snippet:

    const { createClient } = require('@supabase/supabase-js');
    const supabase = createClient(process.env.SUPABASE_URL, process.env.SUPABASE_KEY);
    async function getUsers() {
      const { data, error } = await supabase.from('users').select('*');
      if (error) throw error;
      return data;
    }
    
  • Environment: Express, Supabase (PostgreSQL), deployed on Vercel.

  • Issue: The /users API responds slowly (over 5 seconds) when the users table has over 10,000 records.
    Requirements:

  1. Analyze the code and identify performance issues.

  2. Suggest at least three optimizations with modified code.

  3. Explain the benefits of each optimization.
    Output:

  • Performance issue analysis (markdown).

  • Optimizations with code blocks and explanations.

  • Please ensure modified code is accurate and explanations are clear.

Output:

Optimizing /users API Performance

Performance Issue Analysis

The current code queries the entire users table with select('*'), causing several issues:

  • Large data retrieval: Fetching all columns and records (10,000+) increases processing time and memory usage.

  • No pagination: Returning all records at once leads to slow responses (over 5 seconds).

  • Missing indexes: Queries may be slow if the users table lacks indexes on frequently used columns (e.g., id or name).

Optimizations

  1. Limit columns and records:

    const { createClient } = require('@supabase/supabase-js');
    const supabase = createClient(process.env.SUPABASE_URL, process.env.SUPABASE_KEY);
    async function getUsers(page = 1, limit = 50) {
      const offset = (page - 1) * limit;
      const { data, error } = await supabase
        .from('users')
        .select('id, name, email')
        .range(offset, offset + limit - 1);
      if (error) throw error;
      return data;
    }

Benefits: Selects only necessary columns (id, name, email) and limits to 50 records per page, reducing data transfer and cutting response time to under 1 second. Pagination efficiently handles large datasets.

  1. Add index to users table:

    -- Run in Supabase SQL Editor
    CREATE INDEX idx_users_name ON users (name);
    
    // Code unchanged, but queries are faster with index
    const { data, error } = await supabase
      .from('users')
      .select('id, name, email')
      .like('name', '%search%')
      .limit(50);
    if (error) throw error;
    return data;
    

    Benefits: Indexing the name column speeds up search or filter queries (e.g., like), reducing query time from seconds to milliseconds, especially for large tables.

  2. Implement caching with Redis:

    const { createClient } = require('@supabase/supabase-js');
    const redis = require('redis');
    const client = redis.createClient({ url: process.env.REDIS_URL });
    await client.connect();
    const supabase = createClient(process.env.SUPABASE_URL, process.env.SUPABASE_KEY);
    async function getUsers(page = 1, limit = 50) {
      const cacheKey = `users:${page}:${limit}`;
      const cached = await client.get(cacheKey);
      if (cached) return JSON.parse(cached);
      const offset = (page - 1) * limit;
      const { data, error } = await supabase
        .from('users')
        .select('id, name, email')
        .range(offset, offset + limit - 1);
      if (error) throw error;
      await client.setEx(cacheKey, 3600, JSON.stringify(data));
      return data;
    }
    

    Benefits: Caches query results in Redis for 1 hour, reducing Supabase queries. Response time drops to under 100ms for repeated requests, saving server resources.

Maintenance Notes:

  • Monitor users table size and update indexes as needed.

  • Track API response times on Vercel to detect issues early.

  • Ensure Redis is configured correctly to avoid high costs.

Benefits:

  • Significantly improves API response times.

  • Provides accurate, ready-to-use optimization code.

  • Ideal for large-scale apps on Vercel with Supabase.

8. Write Unit Tests

Unit tests ensure code behaves as expected and reduce bugs during development. However, writing comprehensive unit tests, especially for complex functions, can be time-consuming. With Advanced ChatGPT Prompts for Developers, you can ask ChatGPT to generate detailed test cases, covering edge cases, to enhance code reliability.

Purpose:
Write unit tests for a function or module, such as a data processing function in a Node.js application.

General Prompt Template:

I need to write unit tests for a function or module in my project. Please assist with the following details:

Code Info:
Language: [Programming language].
Function/module: [Code or functionality description].
Testing library: [Jest, Mocha, etc.].

Requirements:
Create at least three test cases, including normal and edge cases.
Provide complete test code with setup if needed.
Explain each test case.

Output:
Unit test code in code blocks (markdown).
Explanation of each test case.
Please ensure test code is accurate and explanations are clear.

Specific Example Prompt:

I need to write unit tests for a function in a Node.js application. Please assist with the following details:
Code Info:

  • Language: JavaScript (Node.js 18).

  • Function:

    function calculateDiscount(price, discountPercentage) {
      if (typeof price !== 'number' || typeof discountPercentage !== 'number') {
        throw new Error('Invalid input');
      }
      if (price < 0 || discountPercentage < 0 || discountPercentage > 100) {
        throw new Error('Invalid range');
      }
      const discount = price * (discountPercentage / 100);
      return price - discount;
    }
    
  • Testing library: Jest.
    Requirements:

  1. Create at least three test cases, including normal and edge cases.

  2. Provide complete test code with setup if needed.

  3. Explain each test case.
    Output:

  • Unit test code in code blocks (markdown).

  • Explanation of each test case.

  • Please ensure test code is accurate and explanations are clear.

Output:

Unit Tests for calculateDiscount Function

Unit Test Code

const { calculateDiscount } = require('./discount');

describe('calculateDiscount', () => {
  // Test case 1: Normal case
  test('should calculate discount for valid price and percentage', () => {
    const result = calculateDiscount(100, 20);
    expect(result).toBe(80);
  });

  // Test case 2: Edge case - 0% discount
  test('should return original price when discount is 0%', () => {
    const result = calculateDiscount(50, 0);
    expect(result).toBe(50);
  });

  // Test case 3: Edge case - invalid inputs
  test('should throw error for non-numeric inputs', () => {
    expect(() => calculateDiscount('100', 20)).toThrow('Invalid input');
    expect(() => calculateDiscount(100, '20')).toThrow('Invalid input');
  });
});

Test Case Explanations

  1. Normal case:

    • Test: Calls calculateDiscount(100, 20) (price 100, 20% discount).

    • Expectation: Returns 80 (100 - 20% = 80).

    • Purpose: Verifies the function correctly calculates the discounted price for valid inputs.

  2. Edge case - 0% discount:

    • Test: Calls calculateDiscount(50, 0) (price 50, 0% discount).

    • Expectation: Returns 50 (original price, no discount).

    • Purpose: Ensures the function handles the edge case of a 0% discount correctly.

  3. Edge case - invalid inputs:

    • Test: Calls calculateDiscount('100', 20) and calculateDiscount(100, '20') (non-numeric inputs).

    • Expectation: Throws Invalid input error.

    • Purpose: Confirms the function detects and handles invalid input types, ensuring robustness.

Maintenance Notes:

  • Add test cases for other edge cases (e.g., negative price, discount > 100%) if the function is extended.

  • Run tests with jest --coverage to ensure full coverage.

  • Integrate tests into a CI/CD pipeline on GitLab.

Benefits:

  • Generates unit tests quickly, covering key scenarios.

  • Provides accurate, Jest-compatible test code.

  • Enhances code reliability in Node.js projects.

9. Advanced ChatGPT Prompts For Developers: Create Architecture Design Templates

A well-designed software architecture ensures a robust, scalable system. However, crafting detailed design templates requires significant effort and expertise. With Advanced ChatGPT Prompts for Developers, you can request ChatGPT to generate architecture designs, including diagrams, descriptions, and suitable technologies, streamlining the planning process.

Purpose:
Create an architecture design template for a system, such as an online learning web app deployed on Vercel.

General Prompt Template:

I need an architecture design template for a software system. Please assist with the following details:

System Info:
System type: [Description, e.g., web app].
Requirements: [Main features, expected load, security].
Tech stack: [Language, framework, database].

Design Requirements:
Propose an architecture (e.g., microservices, serverless).
Describe key components and interactions.
Provide an architecture diagram (text description or PlantUML syntax).

Output:
Architecture and component description (markdown).
Architecture diagram (PlantUML or text).
Please ensure the design is specific, concise, and practical.

Specific Example Prompt:

I need an architecture design template for an online learning web app. Please assist with the following details:

System Info:
System type: Web app for online learning with videos and quizzes.
Requirements: Support 5,000 concurrent users, secure video storage, payment integration.
Tech stack: Node.js, React, Supabase (PostgreSQL).

Design Requirements:
Propose an architecture (microservices or serverless).
Describe key components and interactions.
Provide an architecture diagram (PlantUML syntax).

Output:
Architecture and component description (markdown).
Architecture diagram (PlantUML).
Please ensure the design is specific, concise, and practical.

Output:

Architecture Design for Online Learning Web App

Architecture Description

Proposed Architecture: Microservices
Rationale: Microservices enable independent scaling of components (video streaming, payments, quizzes), ideal for 5,000 concurrent users. Supabase supports data storage and integrates well with Node.js/React on Vercel.

Key Components and Interactions:

  • API Gateway: Handles client requests (React) and routes to services (Vercel API Routes).

  • User Service: Manages accounts and authentication (Supabase Auth).

  • Video Service: Stores and streams videos (Supabase Storage, CDN integration).

  • Quiz Service: Creates and grades quizzes (Node.js, Supabase PostgreSQL).

  • Payment Service: Processes payments (Stripe via Vercel Functions).
    Interactions: Clients send requests via API Gateway, which routes to services that process data with Supabase or Stripe and return responses.

Architecture Diagram (PlantUML)

@startuml
actor User
participant "React Client" as Client
participant "API Gateway (Vercel)" as Gateway
participant "User Service" as UserService
participant "Video Service" as VideoService
participant "Quiz Service" as QuizService
participant "Payment Service" as PaymentService
database "Supabase PostgreSQL" as DB
participant "Supabase Storage" as Storage
participant "Stripe" as Stripe

User -> Client: Access app
Client -> Gateway: HTTP Request
Gateway -> UserService: Authenticate
UserService -> DB: Query user data
Gateway -> VideoService: Stream video
VideoService -> Storage: Fetch video
Gateway -> QuizService: Submit quiz
QuizService -> DB: Store results
Gateway -> PaymentService: Process payment
PaymentService -> Stripe: Charge
Stripe --> PaymentService: Confirm
PaymentService --> Gateway: Response
Gateway --> Client: JSON Response
Client --> User: Display

@enduml

Benefits:

  • Generates clear, rapid architecture designs.

  • PlantUML diagrams are editable and integratable into documentation.

  • Suits online learning apps on Vercel with Supabase.

10. Integrate Third-Party APIs

Integrating third-party APIs is a quick way to add features, but handling authentication, errors, and performance can be complex. With Advanced ChatGPT Prompts for Developers, you can request ChatGPT to generate API integration code, handle errors, and optimize performance, saving time and ensuring reliability.

Purpose:
Integrate a third-party API into an application, such as Stripe for payments in a Node.js app on Vercel.

General Prompt Template:

I need to integrate a third-party API into my project. Please assist with the following details:

Project Info:
API: [API name, e.g., Stripe].
Functionality: [Integration purpose].
Tech stack: [Language, framework].

Requirements:
Provide API integration code (including authentication).
Handle at least two common error cases.
Optimize performance (e.g., caching, rate limiting).

Output:
Integration code with error handling (code block, markdown).
Brief explanation of each part.
Please ensure code is accurate, concise, and practical.

Specific Example Prompt:

I need to integrate the Stripe API into a Node.js application. Please assist with the following details:

Project Info:
API: Stripe (payments).
Functionality: Process order payments.
Tech stack: Node.js, Express, Supabase (PostgreSQL).

Requirements:
Provide API integration code (including authentication).
Handle two error cases: card declined, invalid API key.
Optimize performance (rate limiting or caching).

Output:
Integration code with error handling (code block, markdown).
Brief explanation of each part.
Please ensure code is accurate, concise, and practical.

Output:

Integrating Stripe API For Payments

Integration Code

const express = require('express');
const Stripe = require('stripe');
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);
const router = express.Router();

// API endpoint to process payments
router.post('/create-payment', async (req, res) => {
  const { amount, currency = 'usd', paymentMethodId, orderId } = req.body;

  try {
    // Validate input
    if (!amount || !paymentMethodId || !orderId) {
      return res.status(400).json({ error: 'Missing required fields' });
    }

    // Create payment intent
    const paymentIntent = await stripe.paymentIntents.create({
      amount: Math.round(amount * 100), // Convert to cents
      currency,
      payment_method: paymentMethodId,
      confirmation_method: 'manual',
      confirm: true,
      return_url: 'http://localhost:3000/success',
    });

    // Update order status in Supabase
    const { createClient } = require('@supabase/supabase-js');
    const supabase = createClient(process.env.SUPABASE_URL, process.env.SUPABASE_KEY);
    await supabase.from('orders').update({ payment_status: 'success' }).eq('id', orderId);

    res.json({ clientSecret: paymentIntent.client_secret });
  } catch (error) {
    // Handle errors
    if (error.type === 'StripeCardError') {
      return res.status(400).json({ error: 'Card declined', details: error.message });
    }
    if (error.type === 'StripeInvalidRequestError' && error.message.includes('Invalid API Key')) {
      return res.status(401).json({ error: 'Invalid API key', details: error.message });
    }
    res.status(500).json({ error: 'Payment failed', details: error.message });
  }
});

// Rate limiting for optimization
const rateLimit = require('express-rate-limit');
router.use('/create-payment', rateLimit({
  windowMs: 15 * 60 * 1000, // 15 minutes
  max: 100, // 100 requests per IP
}));

module.exports = router;

Explanation

  • Authentication: Uses STRIPE_SECRET_KEY from environment variables for security.

  • Payment Intent: Calls stripe.paymentIntents.create with amount (in cents), payment_method, and confirm: true for immediate processing.

  • Status Update: Saves payment status to Supabase after successful payment.

  • Error Handling:

    • Card Declined: Returns 400 with details (StripeCardError).

    • Invalid API Key: Returns 401 (StripeInvalidRequestError).

  • Optimization: Implements express-rate-limit to cap requests at 100 per 15 minutes, preventing API abuse.

Benefits:

  • Enables rapid, secure Stripe integration.

  • Handles errors clearly and optimizes performance.

  • Ideal for Node.js apps on Vercel.

11. Create Automation Scripts

Automating repetitive tasks like deployment, backups, or monitoring saves time and reduces errors. With Advanced ChatGPT Prompts for Developers, you can request ChatGPT to generate automation scripts with error handling and optimization, boosting system management efficiency.

Purpose:
Create an automation script, such as backing up a Supabase database to AWS S3.

General Prompt Template:

I need an automation script for my project. Please assist with the following details:

Project Info:
Task: [Task description, e.g., backup].
Platform: [OS, tools, services].
Language: [Programming language, e.g., Bash, Python].

Requirements:
Provide a script with error handling.
Optimize performance or security.
Briefly explain key parts.

Output:
Script in a code block (markdown).
Explanation of each part.
Please ensure the script is accurate, concise, and practical.

Specific Example Prompt:

I need an automation script to back up a Supabase database. Please assist with the following details:

Project Info:
Task: Back up a Supabase database (PostgreSQL) to AWS S3.
Platform: Linux, AWS CLI, Supabase CLI.
Language: Bash.

Requirements:
Provide a script with error handling.
Optimize security (e.g., encrypt backup files).
Briefly explain key parts.

Output:
Script in a code block (markdown).
Explanation of each part.
Please ensure the script is accurate, concise, and practical.

Output:

Script to Back Up Supabase to AWS S3

Script

#!/bin/bash

# Environment variables
SUPABASE_URL=${SUPABASE_URL:-"your-supabase-url"}
SUPABASE_KEY=${SUPABASE_KEY:-"your-supabase-key"}
S3_BUCKET="your-s3-bucket"
BACKUP_DIR="/tmp/supabase_backup"
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
BACKUP_FILE="supabase_backup_${TIMESTAMP}.sql.gz"
ENCRYPTED_FILE="${BACKUP_FILE}.gpg"

# Create temporary directory
mkdir -p "$BACKUP_DIR" || { echo "Error: Cannot create $BACKUP_DIR"; exit 1; }

# Back up database
pg_dump --host=$(echo $SUPABASE_URL | cut -d'/' -f3 | cut -d':' -f1) \
  --port=5432 \
  --username=postgres \
  --dbname=postgres \
  --password="$SUPABASE_KEY" \
  | gzip > "$BACKUP_DIR/$BACKUP_FILE" 2> /tmp/backup_error.log
if [ $? -ne 0 ]; then
  echo "Backup error: $(cat /tmp/backup_error.log)"
  exit 1
fi

# Encrypt backup file
echo "your-gpg-passphrase" | gpg --batch --yes --passphrase-fd 0 \
  --symmetric --cipher-algo AES256 \
  -o "$BACKUP_DIR/$ENCRYPTED_FILE" "$BACKUP_DIR/$BACKUP_FILE" 2> /tmp/encrypt_error.log
if [ $? -ne 0 ]; then
  echo "Encryption error: $(cat /tmp/encrypt_error.log)"
  rm -rf "$BACKUP_DIR"
  exit 1
fi

# Upload to S3
aws s3 cp "$BACKUP_DIR/$ENCRYPTED_FILE" "s3://$S3_BUCKET/backups/$ENCRYPTED_FILE" 2> /tmp/s3_error.log
if [ $? -ne 0 ]; then
  echo "S3 upload error: $(cat /tmp/s3_error.log)"
  rm -rf "$BACKUP_DIR"
  exit 1
fi

# Clean up
rm -rf "$BACKUP_DIR"
echo "Backup successful: $ENCRYPTED_FILE"

Benefits:

  • Automates secure, efficient backups.

  • Concise script with clear error handling.

  • Ideal for Supabase and AWS S3.

12. Advanced ChatGPT Prompts For Developers: Analyze User Requirements

Analyzing user requirements is crucial to ensure a product meets expectations, but translating vague requests into clear specifications can be challenging. With Advanced ChatGPT Prompts for Developers, you can request ChatGPT to analyze requirements, identify key features, and create specifications, saving time and improving accuracy.

Purpose:
Analyze user requirements for an application, such as a task management app on Vercel.

General Prompt Template:

I need to analyze user requirements for a project. Please assist with the following details:

Requirement Info:
Description: [User requirements].
Audience: [Target users].
Tech stack: [Language, framework].

Analysis Requirements:
Identify primary and secondary features.
Create specifications (features, constraints).
Suggest clarifying questions (if needed).

Output:
Feature analysis and specifications (markdown, table).
List of clarifying questions.
Please ensure the analysis is concise, specific, and practical.

Specific Example Prompt:

I need to analyze user requirements for a task management app. Please assist with the following details:

Requirement Info:
Description: Users want a web app to create, track, and complete daily tasks, with reminder notifications.
Audience: Office workers, remote employees.
Tech stack: Node.js, React, Supabase (PostgreSQL).

Analysis Requirements:
Identify primary and secondary features.
Create specifications (features, constraints).
Suggest three clarifying questions.

Output:
Feature analysis and specifications (markdown, table).
List of clarifying questions.
Please ensure the analysis is concise, specific, and practical.

Output:

Analysis of Task Management App Requirements

Feature Analysis

  • Primary Features:

    • Create tasks: Users add tasks with title, description, due date.

    • Track tasks: View task lists (completed/incomplete).

    • Reminder notifications: Send email reminders before due dates.

  • Secondary Features:

    • Edit/delete tasks: Update or remove tasks.

    • Filter tasks: Filter by status or date.

Specifications

Feature

Description

Constraints

Create tasks

Add tasks with title (required), description, due date

Store in Supabase, limit 1,000 tasks/user

Track tasks

Display task lists with pagination

Load up to 50 tasks at a time, React UI

Reminder notifications

Send email 24 hours before due date via Vercel Functions

Integrate SendGrid, limit 100 emails/day

Edit/delete tasks

Update or delete tasks via API

Only task owners can modify

Filter tasks

Filter by status (complete/incomplete) or date

Optimize Supabase queries with indexes

Clarifying Questions

  1. Do users need to log in to manage tasks, and if so, which authentication methods (email, Google)?

  2. Should reminders allow customizable timing (e.g., 1 hour, 1 day before)?

  3. Is there a need to store task edit history (audit log)?

Benefits:

  • Converts vague requirements into clear specifications.

  • Saves time in analysis, aiding development on Vercel.

  • Clarifying questions refine requirements.

13. Advanced ChatGPT Prompts For Developers: Create User Documentation

Clear user documentation helps end-users navigate a product effectively, but writing accessible guides requires time and skill. With Advanced ChatGPT Prompts for Developers, you can request ChatGPT to generate user documentation, including guides, FAQs, and tips, enhancing the user experience.

Purpose:
Create user documentation for an application, such as a task management app on Vercel.

General Prompt Template:

I need user documentation for an application. Please assist with the following details:

App Info:
Name: [App name].
Features: [Main functionality].
Audience: [Target users].

Documentation Requirements:
Usage guides for at least two key features.
FAQ with three common questions.
Tips for effective use.

Output:
Documentation in markdown, easy to read.
Clearly divided sections.
Please ensure the documentation is concise, friendly, and practical.

Specific Example Prompt:

I need user documentation for a task management app. Please assist with the following details:

App Info:
Name: TaskEasy.
Features: Create, track tasks, receive reminder notifications.
Audience: Office workers, remote employees.

Documentation Requirements:
Usage guides for creating tasks and receiving reminders.
FAQ with three common questions.
Two tips for effective use.

Output:
Documentation in markdown, easy to read.
Clearly divided sections.
Please ensure the documentation is concise, friendly, and practical.

Output:

# TaskEasy User Documentation

## Usage Guides

### 1. Creating Tasks
- **Step 1**: Log in to TaskEasy using email or Google.  
- **Step 2**: Click the "Add Task" button in the top-right corner.  
- **Step 3**: Enter a title (required), description (optional), and due date.  
- **Step 4**: Click "Save". The task appears in the "Incomplete" list.  
**Note**: You can edit or delete tasks anytime.

### 2. Receiving Reminder Notifications
- **How it works**: TaskEasy automatically sends email reminders 24 hours before a task’s due date.  
- **Check**: Ensure your email is verified in "Account Settings".  
- **Customization**: Reminders are currently email-based. Contact support for additional options (SMS, push notifications).

## FAQ
1. **How do I filter completed tasks?**  
   Use the filter at the top of the task list, selecting "Completed" or "Incomplete".  
2. **Can I create tasks without a due date?**  
   Yes, due dates are optional. Tasks will be saved without reminders.  
3. **What if I don’t receive reminder emails?**  
   Check your spam folder or contact support at [email protected].

## Tips for Effective Use
- **Prioritize tasks**: Set earlier due dates for urgent tasks to get timely reminders.  
- **Use filters**: Filter tasks by date to focus on upcoming deadlines.

**Benefits**:  
- User-friendly documentation for new users.  
- FAQs and tips enhance user experience.  
- Suits TaskEasy on Vercel.

14. Optimize Application Security

Security is critical to protect applications from attacks and data breaches, but implementing robust measures requires deep expertise. With Advanced ChatGPT Prompts for Developers, you can request ChatGPT to analyze an application, suggest security enhancements, and provide executable code, strengthening security efficiently.

Purpose:
Enhance security for a web application, such as a Node.js app deployed on Vercel.

General Prompt Template:

I need to optimize security for an application. Please assist with the following details:

App Info:
Type: [Web app, API, etc.].
Tech stack: [Language, framework, database].
Security concerns: [Specific issues, if any].

Requirements:
Identify three potential security vulnerabilities.
Suggest fixes with code or configuration.
Explain the benefits of each fix.

Output:
Vulnerability analysis and fixes (markdown).
Code or configuration in code blocks.
Please ensure solutions are concise, accurate, and practical.

Specific Example Prompt:

I need to optimize security for a Node.js web application. Please assist with the following details:

App Info:
Type: REST API for a task management app.
Tech stack: Node.js, Express, Supabase (PostgreSQL), deployed on Vercel.
Security concerns: No user authentication or API protection.

Requirements:
Identify three potential security vulnerabilities.
Suggest fixes with code or configuration.
Explain the benefits of each fix.

Output:
Vulnerability analysis and fixes (markdown).
Code or configuration in code blocks.
Please ensure solutions are concise, accurate, and practical.

Output:

Optimizing Security for Task Management API

Vulnerability Analysis

  1. Lack of User Authentication: API lacks token-based access control, allowing unauthorized access.

  2. SQL Injection Risk: Supabase queries may be vulnerable if inputs are not sanitized.

  3. Missing HTTP Security Headers: No headers like Content Security Policy, increasing XSS risks.

Fixes

  1. Implement JWT Authentication:

    const jwt = require('jsonwebtoken');
    const express = require('express');
    const router = express.Router();
    
    // Authentication middleware
    const authenticate = (req, res, next) => {
      const token = req.header('Authorization')?.replace('Bearer ', '');
      if (!token) return res.status(401).json({ error: 'No token provided' });
      try {
        const decoded = jwt.verify(token, process.env.JWT_SECRET);
        req.user = decoded;
        next();
      } catch (error) {
        res.status(401).json({ error: 'Invalid token' });
      }
    };
    
    // Protect route
    router.get('/tasks', authenticate, async (req, res) => {
      const { createClient } = require('@supabase/supabase-js');
      const supabase = createClient(process.env.SUPABASE_URL, process.env.SUPABASE_KEY);
      const { data, error } = await supabase.from('tasks').select('*').eq('user_id', req.user.id);
      if (error) return res.status(500).json({ error: error.message });
      res.json(data);
    });
    
    module.exports = router;

Benefits: Restricts API access to authenticated users via JWT, preventing unauthorized access. Tokens are securely stored in environment variables.

  1. Use Safe Supabase Queries:

    const { createClient } = require('@supabase/supabase-js');
    const supabase = createClient(process.env.SUPABASE_URL, process.env.SUPABASE_KEY);
    
    async function getTasks(userId, status) {
      // Safe parameterized query
      const { data, error } = await supabase
        .from('tasks')
        .select('id, title, status')
        .eq('user_id', userId)
        .eq('status', status)
        .limit(50);
      if (error) throw new Error(error.message);
      return data;
    }
    

    Benefits: Supabase automatically parameterizes queries, preventing SQL Injection. Limiting to 50 records reduces large data risks.

  2. Add Security Headers with Helmet:

    const express = require('express');
    const helmet = require('helmet');
    const app = express();
    
    // Add security headers
    app.use(helmet({
      contentSecurityPolicy: {
        directives: {
          defaultSrc: ["'self'"],
          scriptSrc: ["'self'", "https://vercel.com"],
        },
      },
    }));
    
    app.use(express.json());
    app.use('/api', require('./routes'));
    
    module.exports = app;
    

    Benefits: Helmet adds headers like Content Security Policy, mitigating XSS and other attacks. CSP restricts scripts to trusted sources.

Maintenance Notes:

  • Update jsonwebtoken, helmet, @supabase/supabase-js to patch security flaws.

  • Monitor Vercel logs for unauthorized access attempts.

  • Enable Row Level Security (RLS) on Supabase for enhanced data protection.

Benefits:

  • Rapidly strengthens API security.

  • Provides accurate, integrable code.

  • Ideal for Node.js apps on Vercel.

15. Generate Performance Reports

Performance reports help developers monitor and improve application efficiency, but collecting and presenting complex data can be time-consuming. With Advanced ChatGPT Prompts for Developers, you can request ChatGPT to create performance queries and report templates, simplifying the tracking of key metrics.

Purpose:
Generate a performance report for a web application, such as a Node.js app on Vercel with Prometheus.

General Prompt Template:

I need a performance report for an application. Please assist with the following details:

App Info:
Type: [Web app, API, etc.].
Monitoring tool: [Prometheus, New Relic, etc.].
Metrics: [Response time, errors, etc.].

Requirements:
Suggest three performance metrics to track.
Provide queries or configurations to collect data.
Create a report template (table or text).

Output:
Metrics, queries, and report template (markdown).
Brief explanation of each part.
Please ensure queries are accurate, reports are concise, and practical.

Specific Example Prompt:

I need a performance report for a Node.js web application. Please assist with the following details:

App Info:
Type: REST API for a task management app.
Monitoring tool: Prometheus.
Metrics: API response time, error rate, and request throughput.

Requirements:
Suggest three performance metrics to track.
Provide Prometheus queries to collect data.
Create a report template (markdown table).

Output:
Metrics, queries, and report template (markdown).
Brief explanation of each part.
Please ensure queries are accurate, reports are concise, and practical.

Output:

Performance Report for Task Management API

Performance Metrics

  1. API Response Time: Measures average latency of endpoints (milliseconds).

  2. Error Rate: Percentage of requests returning errors (4xx, 5xx).

  3. Request Throughput: Number of requests per second to the API.

Prometheus Queries

  1. API Response Time (P95):

    histogram_quantile(0.95, sum(rate(http_request_duration_seconds_bucket[5m])) by (le, endpoint))

Explanation: Calculates 95th percentile (P95) latency for each endpoint over 5 minutes.

  1. Error Rate:

    100 * sum(rate(http_requests_total{status=~"4..|5.."}[5m])) / sum(rate(http_requests_total[5m]))
    

    Explanation: Computes percentage of error requests (4xx, 5xx) relative to total requests over 5 minutes.

  2. Request Throughput:

    sum(rate(http_requests_total[5m])) by (endpoint)
    

    Explanation: Measures requests per second for each endpoint over 5 minutes.

Report Template

Endpoint

Response Time (P95, ms)

Error Rate (%)

Throughput (req/s)

/tasks

120

0.5

10

/tasks/create

150

1.0

5

/tasks/update

130

0.8

3

Report Explanation:

  • Response Time: /tasks/create is slowest (150ms), consider optimization (e.g., Supabase indexing).

  • Error Rate: /tasks/create has highest errors (1.0%), check error logs.

  • Throughput: /tasks handles most traffic (10 req/s), ensure scalability on Vercel.

Maintenance Notes:

  • Configure Prometheus exporter for Node.js (e.g., prom-client).

  • Review reports daily on Vercel to detect anomalies.

  • Optimize slow endpoints with caching or efficient queries.

Benefits:

  • Generates concise, readable performance reports.

  • Accurate Prometheus queries, ready to use.

  • Supports optimization for apps on Vercel.

16. Advanced ChatGPT Prompts For Developers: Create Software Test Plans

A software test plan ensures an application meets requirements and is free of critical bugs, but creating a detailed plan can be time-consuming. With Advanced ChatGPT Prompts for Developers, you can request ChatGPT to generate a test plan, including test scenarios, scope, and criteria, streamlining the testing process.

Purpose:
Create a test plan for a web application, such as a task management app on Vercel.

General Prompt Template:

I need a software test plan for an application. Please assist with the following details:

App Info:
Type: [Web app, API, etc.].
Main features: [Feature description].
Tech stack: [Language, framework].

Plan Requirements:
Define the testing scope (features, test types).
Suggest at least three test scenarios (including edge cases).
Create a test plan table with success criteria.

Output:
Test plan (markdown, table).
Brief explanation of scenarios.
Please ensure the plan is concise, specific, and practical.

Specific Example Prompt:

I need a software test plan for a task management application. Please assist with the following details:

App Info:
Type: Web app with REST API.
Main features: Create, edit, delete tasks; send reminder notifications.
Tech stack: Node.js, React, Supabase (PostgreSQL), deployed on Vercel.

Plan Requirements:
Define the testing scope (features, test types).
Suggest three test scenarios (including edge cases).
Create a test plan table with success criteria.

Output:
Test plan (markdown, table).
Brief explanation of scenarios.
Please ensure the plan is concise, specific, and practical.

Output:

# Test Plan for Task Management Application

## Testing Scope
- **Features**: Create, edit, delete tasks; send reminder notifications.  
- **Test Types**: Functional, integration, performance, security.  
- **Exclusions**: Detailed UI testing, mobile device testing.

## Test Scenarios
1. **Create tasks with valid and invalid inputs**:  
   - **Description**: Test task creation with title, description, and due date; try invalid inputs (empty title).  
   - **Edge Cases**: Maximum title length (255 characters), past due date.  
   - **Expectation**: Valid inputs create tasks successfully; invalid inputs return errors.

2. **Send reminder notifications at correct times**:  
   - **Description**: Verify email reminders are sent 24 hours before task due dates.  
   - **Edge Cases**: Tasks without due dates, reminders near due time.  
   - **Expectation**: Emails sent on time; no emails for tasks without due dates.

3. **Delete tasks with user permissions**:  
   - **Description**: Ensure users can only delete their own tasks, not others’.  
   - **Edge Cases**: Unauthenticated users, non-existent tasks.  
   - **Expectation**: Successful deletion with valid permissions; errors (401/404) for unauthorized or missing tasks.

## Test Plan Table
| ID  | Feature                  | Test Scenario                         | Test Type     | Success Criteria                                |
|-----|--------------------------|---------------------------------------|---------------|------------------------------------------------|
| T1  | Create task              | Create with valid title, due date     | Functional    | Task saved in Supabase, returns 201 status      |
| T2  | Create task              | Create with empty title               | Functional    | Returns 400 error with "Title required" message |
| T3  | Send notification        | Task with valid due date              | Integration   | Email sent via SendGrid 24 hours prior          |
| T4  | Send notification        | Task without due date                 | Functional    | No email sent, no errors                        |
| T5  | Delete task              | Delete user’s own task                | Security      | Task removed from Supabase, returns 200 status  |
| T6  | Delete task              | Delete another user’s task            | Security      | Returns 401 "Unauthorized" error                |

## Scenario Explanations
- **Scenario 1**: Verifies task creation handles valid and invalid inputs, including edge cases (long titles, invalid dates).  
- **Scenario 2**: Confirms reminders are sent correctly and skipped for tasks without due dates, testing SendGrid integration.  
- **Scenario 3**: Ensures security by restricting task deletion to authorized users, handling error cases (401, 404).

**Benefits**:  
- Clear, actionable test plan.  
- Covers functional, security, and integration tests.  
- Suits apps on Vercel with Supabase.

17. Conclusion

This article’s 16 Advanced ChatGPT Prompts for Devs have guided you through key stages: from automating CI/CD pipelines and designing APIs to debugging, testing, and managing projects. Each prompt is crafted to deliver practical, actionable solutions, whether you’re building web apps on Vercel, managing databases with Supabase, or preparing for technical interviews. Don’t wait, copy a prompt, paste it into ChatGPT, and transform your workflow now!

If you are interested in other topics and how AI is transforming different aspects of our lives or even in making money using AI with more detailed, step-by-step guidance, you can find our other articles here:

*indicates a premium content, if any

How would you rate the quality of this AI Workflows article? šŸ“

Login or Subscribe to participate in polls.

Reply

or to participate.