Code Issues Solver | Python

Complete getCandy Function and Correct Database Configuration

The task involves correcting the `getCandy` function to fetch candy types from a PostgreSQL database, handle errors, and send proper JSON responses. The database configuration is adjusted to resolve an error in the `host` format. The


Empty image or helper icon

Prompt

fix the code to return json with the resulting query rows

// index.js
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const port = 3000;
app.use(bodyParser.json());

const { Pool } = require('pg');
const newDBPool = new Pool({
    user: 'admin',
    host: 'localhost:3000',
    database: 'willywonkadb',
    password: 'goldenticket'
});

//Finish the getCandy function below:
const getCandy = (request, response) => {
   newDBPool.query('SELECT type FROM candy ORDER BY type DESC', (error, result) => {
        if (error) {
            throw error;
        }
        response.status(200).json(result.rows);
    });
};

app.get('/candy', getCandy);

module.exports = {
  app
};



We are working on an Express.js application for a candy factory. Our application connects to a database that stores all the types of candy in the factory. Currently, the application has one route (/candy) that uses a function named getCandy() to display all the types of candy from our database.

Complete the getCandy() function so that it:

Uses the newDBPool variable (our database connection) to query the database to retrieve the type field from all the candies in the candy table. The query result should be ordered by the type field in descending order.
If the database query produces an error, our function should throw the error. Otherwise, the response should have a status of 200 and return a JSON object of the database query results.

Answer

Problem Analysis

The task is to complete the getCandy function to retrieve and return candy types from the database ordered by type in descending order. The database connection details and the getCandy function skeleton are provided. It's expected to handle any potential errors and return a proper JSON response.

Code Review

The code contains:

  1. Initial setup for Express application and PostgreSQL connection.
  2. Middleware to parse JSON bodies.
  3. Placeholder for getCandy function.

Issues Identified

  1. Incorrect host format in the newDBPool object. The host should be just the hostname, not including port.
  2. The database query execution is already correct, but the error should not cause the server to crash. Instead, it should send an error response.
  3. The result.rows should be sent as JSON in the response.

Solution

Below is the corrected and completed code.

// index.js
const express = require('express');
const bodyParser = require('body-parser');
const { Pool } = require('pg');

// Express app setup
const app = express();
const port = 3000;

// JSON body parser middleware
app.use(bodyParser.json());

// Database connection configuration
const newDBPool = new Pool({
    user: 'admin',
    host: 'localhost', // Correct host format
    database: 'willywonkadb',
    password: 'goldenticket',
    port: 5432 // Default PostgreSQL port
});

/**
 * getCandy function to fetch candy types from the database
 * and return them as a JSON response.
 * 
 * @param {Request} request - Express request object
 * @param {Response} response - Express response object
 */
const getCandy = (request, response) => {
    // Query to fetch candy types ordered by type descending
    newDBPool.query('SELECT type FROM candy ORDER BY type DESC', (error, result) => {
        if (error) {
            // Error handling: send error response
            response.status(500).json({ error: error.message });
            return;
        }
        // Send 200 status and query result as JSON
        response.status(200).json(result.rows);
    });
};

// Define GET /candy route
app.get('/candy', getCandy);

// Server listening on configured port
app.listen(port, () => {
    console.log(`Server running on port ${port}`);
});

module.exports = {
    app
};

Explanation

  1. Database Configuration: Corrected the host entry to just 'localhost' and added a missing port.
  2. Error Handling: If there’s an error with the query, the function sends a response with status 500 and error message in JSON.
  3. Success Response: On successful query, returns status 200 and JSON of the result rows.

Example Usage

  1. Start server: Run node index.js in your terminal.
  2. Access route: Visit http://localhost:3000/candy in your browser or use a tool like Postman.

Unit Tests

Using a testing framework like Jest to validate the getCandy function's behavior.

// index.test.js
const request = require('supertest');
const { app } = require('./index');
const { Pool } = require('pg');

// Mock the Pool instance
jest.mock('pg', () => {
    const mPool = {
        query: jest.fn()
    };
    return { Pool: jest.fn(() => mPool) };
});

describe('GET /candy', () => {
    it('should return 200 and JSON result on success', async () => {
        const mockRows = [{ type: 'Lollipop' }, { type: 'Chocolate' }];
        Pool().query.mockImplementation((text, callback) => {
            callback(null, { rows: mockRows });
        });

        const response = await request(app).get('/candy');
        
        expect(response.status).toBe(200);
        expect(response.body).toEqual(mockRows);
    });

    it('should return 500 and an error message on query error', async () => {
        const mockError = new Error('Database error');
        Pool().query.mockImplementation((text, callback) => {
            callback(mockError);
        });

        const response = await request(app).get('/candy');
        
        expect(response.status).toBe(500);
        expect(response.body).toEqual({ error: mockError.message });
    });
});

This setup mocks the PostgreSQL pool and simulates both successful and erroneous database query cases, ensuring our application handles both scenarios correctly.

Create your Thread using our flexible tools, share it with friends and colleagues.

Your current query will become the main foundation for the thread, which you can expand with other tools presented on our platform. We will help you choose tools so that your thread is structured and logically built.

Description

The task involves correcting the getCandy function to fetch candy types from a PostgreSQL database, handle errors, and send proper JSON responses. The database configuration is adjusted to resolve an error in the host format. The corrected code includes Express setup, middleware for parsing JSON bodies, error handling, and sending JSON responses. An example of usage and unit tests with Jest are provided for validation.