node-api-postgres

0

This is a modern RESTful API built with Node.js and Express, designed to interact with a PostgreSQL database.

Productivity

Express - Node.js API with PostgreSQL

nodepost

This is a modern RESTful API built with Node.js and Express, designed to interact with a PostgreSQL database. The API provides various endpoints for managing user data, with additional features like authentication, JWT protection, soft deletion, and automated testing. We've also integrated Swagger for auto-generated API documentation.

Express.js NodeJS Postgres NPM

Features ๐Ÿš€

  • User Management:

    • Get All Users: Retrieve a list of all users.
    • Get User by ID: Retrieve a specific user by their ID.
    • Create User: Add a new user to the database.
    • Update User: Update details of an existing user.
    • Delete User: Remove a user from the database (soft delete functionality).
  • Authentication & Authorization:

    • User Authentication: Secure API access using JSON Web Tokens (JWT).
    • Role-based Access Control (RBAC): Control access to resources based on user roles (e.g., admin, user).
  • Swagger API Documentation:

    • Swagger integrated for real-time API documentation and testing directly in the browser. Access the documentation at: http://localhost:3000/api-docs.
  • Database:

    • Integration with PostgreSQL for storing user data securely.
    • Soft delete functionality: Mark users as deleted without removing their data.
  • Unit Testing:

    • Comprehensive unit tests using Mocha and Chai to ensure the reliability of the application.
    • Test Cases: Includes tests for user creation, update, deletion, and authentication.

Technologies Used โš™๏ธ

  • Node.js (JavaScript runtime)
  • Express (Web framework)
  • PostgreSQL (Database)
  • JSON Web Token (JWT) (Authentication)
  • Body-Parser (Parsing JSON request bodies)
  • Swagger (API documentation)
  • Mocha (Testing framework)
  • Chai (Assertion library)

Installation ๐Ÿ› ๏ธ

Step 1: Clone the Repository

git clone https://github.com/JawherKl/node-api-postgres.git
cd node-api-postgres

Step 2: Install Dependencies

npm install

Step 3: Set up PostgreSQL

Ensure you have PostgreSQL installed and running. Create a new database and configure the connection.

Step 4: Configure Database Connection

Update the db.js file to set up your PostgreSQL connection credentials.

Step 5: Generate JWT Secret (Optional)

Generate a random JWT secret key (recommended for production environments):

node -e "console.log(require('crypto').randomBytes(32).toString('hex'))"

Inject Table into PostgreSQL

CREATE TABLE users (
  id SERIAL PRIMARY KEY,
  name VARCHAR(100) NOT NULL,
  email VARCHAR(255) UNIQUE NOT NULL,
  password VARCHAR(255) NOT NULL,
  picture VARCHAR(255) NULL,
  role VARCHAR(20) DEFAULT 'user',  -- Role-based access control
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  deleted_at TIMESTAMP NULL  -- For soft delete functionality
);
CREATE TABLE metrics (
    id SERIAL PRIMARY KEY,
    user_id INT NOT NULL,
    metric_name VARCHAR(255) NOT NULL,
    metric_value FLOAT NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE
);

Column Explanation

  • id: Unique identifier for each user (auto-increment).
  • name: User's name (max 100 characters).
  • email: Unique email address (max 255 characters).
  • password: Hashed password for security.
  • role: User's role (e.g., admin, user).
  • created_at: Timestamp for record creation.
  • updated_at: Timestamp for last update (auto-updates on modification).
  • deleted_at: Nullable timestamp for soft deletion.

Usage ๐Ÿƒโ€โ™‚๏ธ

Start the Server

node index.js

The server will run on [http://localhost:3000].

Access Swagger API Docs

Once the server is running, you can access the auto-generated API documentation powered by Swagger at: http://localhost:3000/api-docs.

API Endpoints ๐Ÿ“ก

  • GET / - Returns a simple welcome message.
  • GET /users - Get all users.
  • GET /users/:id - Get a user by ID.
  • POST /users - Create a new user (requires JSON body).
  • PUT /users/:id - Update an existing user by ID (requires JSON body).
  • DELETE /users/:id - Delete a user by ID.
  • POST /login - Authenticate a user and return a JWT (requires JSON body with email and password).

Run In Postman

Example Requests ๐Ÿ“

Get All Users

curl -X GET http://localhost:3000/users

Create User

curl -X POST http://localhost:3000/users -H "Content-Type: application/json" -d '{"name": "John Doe", "email": "john@example.com", "password": "password"}'

Update User

curl -X PUT http://localhost:3000/users/1 -H "Content-Type: application/json" -d '{"name": "Jane Doe"}'

Delete User

curl -X DELETE http://localhost:3000/users/1

Authenticate User

curl -X POST http://localhost:3000/login -H "Content-Type: application/json" -d '{"email": "john@example.com", "password": "password"}'

Access Protected Route

curl -X GET http://localhost:3000/users -H "Authorization: Bearer your_jwt_token"

Unit Testing ๐Ÿงช

Unit tests are implemented using Mocha and Chai. To run tests:

  1. Install test dependencies (if not installed):

    npm install --save-dev mocha chai
    
  2. Run the tests:

    npm test
    

This will run all tests and output the results to the console. You can find the test cases for different routes and operations in the test folder.

Contributing ๐Ÿค

Contributions are welcome! If you have suggestions, improvements, or bug fixes, please open an issue or submit a pull request.

License ๐Ÿ“

This project is licensed under the MIT License. See the LICENSE file for details.

Acknowledgments ๐Ÿ™

  • Special thanks to all contributors and the open-source community.
  • Gratitude to the maintainers of the libraries used in this project.

Stargazers over time

Stargazers over time

Give me stars! Thank you!!!