Skip to content

Instantly share code, notes, and snippets.

@CastonPursuit
Last active August 17, 2023 17:09
Show Gist options
  • Save CastonPursuit/11fff3b97fbe57eba38f8500f4675204 to your computer and use it in GitHub Desktop.
Save CastonPursuit/11fff3b97fbe57eba38f8500f4675204 to your computer and use it in GitHub Desktop.

Backend Setup:

  1. Import Necessary Modules: Start by importing the required libraries at the top of your server.js or your main application file.

    const express = require('express');
    const bodyParser = require('body-parser');
    const { Pool } = require('pg');
  2. Initialize Express and PostgreSQL:

    Configure PostgreSQL by establishing a connection using pg.

    const app = express();
    
    const pool = new Pool({
       user: 'your_username',
       host: 'localhost',
       database: 'schoolDB',
       password: 'your_password',
       port: 5432,
    });
    
    // Middlewares
    app.use(bodyParser.json());
  3. Define CRUD Routes:

    a. GET all students:

    app.get('/students', async (req, res) => {
       try {
           const result = await pool.query('SELECT * FROM students');
           res.json(result.rows);
       } catch (error) {
           res.status(500).json({ message: 'Internal server error' });
       }
    });

    b. POST a new student:

    app.post('/students', async (req, res) => {
       try {
           const { name, grade } = req.body;
           const result = await pool.query('INSERT INTO students (name, grade) VALUES ($1, $2) RETURNING *', [name, grade]);
           res.status(201).json(result.rows[0]);
       } catch (error) {
           res.status(500).json({ message: 'Internal server error' });
       }
    });

    c. PUT (update) an existing student:

    app.put('/students/:id', async (req, res) => {
       try {
           const { name, grade } = req.body;
           const result = await pool.query('UPDATE students SET name = $1, grade = $2 WHERE id = $3 RETURNING *', [name, grade, req.params.id]);
           if (result.rows.length) {
               res.json(result.rows[0]);
           } else {
               res.status(404).json({ message: 'Student not found' });
           }
       } catch (error) {
           res.status(500).json({ message: 'Internal server error' });
       }
    });

    d. DELETE a student:

    app.delete('/students/:id', async (req, res) => {
       try {
           const result = await pool.query('DELETE FROM students WHERE id = $1 RETURNING *', [req.params.id]);
           if (result.rows.length) {
               res.json({ message: 'Student deleted successfully' });
           } else {
               res.status(404).json({ message: 'Student not found' });
           }
       } catch (error) {
           res.status(500).json({ message: 'Internal server error' });
       }
    });
  4. Start the server:

    const PORT = 3000;
    app.listen(PORT, () => {
        console.log(`Server is running on port ${PORT}`);
    });

    Use the command below to start the server:

    nodemon server.js

Testing with Postman:

  1. Launch Postman.

  2. GET all students: Set the HTTP method to GET and use the URL http://localhost:3000/students. Hit Send.

  3. Add a student: Switch to POST, set the URL to http://localhost:3000/students, and use the 'Body' tab to input student details in JSON format. Click Send.

  4. Update a student: Use PUT, adjust the URL to http://localhost:3000/students/[STUDENT_ID] replacing [STUDENT_ID] with a valid ID, and change the student's details in the 'Body' tab. Hit Send.

  5. Delete a student: Change the HTTP method to DELETE, modify the URL to http://localhost:3000/students/[STUDENT_ID] where [STUDENT_ID] is the ID of the student you want to remove, and press Send.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment