# Sequelize Image Upload

1. **<mark>Introduction</mark>**  
    To implement image upload with **Node.js**, **Sequelize**, and a **REST API**, you can follow these steps. We'll use a combination of libraries to handle the image upload, store metadata in the database, and manage the backend.  
    Requirements -
    
    **Node.js**: The runtime environment for executing JavaScript on the server.
    
    **Express.js**: A Node.js framework for building REST APIs.
    
    **Sequelize**: An ORM for interacting with databases.
    
    **multer**: Middleware for handling file uploads.
    
    **MySQL/PostgreSQL/SQLite**: A database for storing image metadata (e.g., name, path, etc.).
    
2. **<mark>Set up a Node.js project</mark>**  
    Create a directory for your project and initialize it.
    
    ```bash
    npm init -y
    ```
    
    Install the required dependencies,
    
    ```bash
    npm install express multer sequelize mysql2
    ```
    
    `express`: For building the API.
    
    `multer`: For handling file uploads.
    
    `sequelize`: For interacting with the database.
    
    `mysql2`: The driver for MySQL (use `pg` for PostgreSQL or `sqlite3` for SQLite).
    
3. #### <mark>Set up Sequelize</mark>
    
    Run the Sequelize CLI to set up your project.
    
    ```bash
    npx sequelize-cli init
    ```
    
    This will create the `config`, `models`, and `migrations` directories.
    
    Update the `config/config.json` file with your database credentials.
    
    ```json
    {
      "development": {
        "username": "root",
        "password": "password",
        "database": "image_upload_db",
        "host": "127.0.0.1",
        "dialect": "mysql"
      }
    }
    ```
    
4. #### **<mark>Create an image model</mark>**
    
    Create a model to store the image metadata (e.g., filename and path).
    
    ```bash
    npx sequelize-cli model:generate --name Image --attributes name:string,path:string
    ```
    
    Run the migration,
    
    ```bash
    npx sequelize-cli db:migrate
    ```
    
5. #### **<mark>Create the Express app and routes</mark>**
    
    Now, set up your Express app and API routes to handle file uploads and saving data in the database.
    
    `app.js`
    
    ```javascript
    const express = require('express');
    const multer = require('multer');
    const path = require('path');
    const { Image } = require('./models'); // Sequelize model
    
    const app = express();
    
    // Set up multer for image storage
    const storage = multer.diskStorage({
      destination: function (req, file, cb) {
        cb(null, 'uploads/'); // Directory to store the images
      },
      filename: function (req, file, cb) {
        const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
        cb(null, file.fieldname + '-' + uniqueSuffix + path.extname(file.originalname));
      }
    });
    
    const upload = multer({ storage: storage });
    
    // Route to upload an image
    app.post('/upload', upload.single('image'), async (req, res) => {
      try {
        // Save the file metadata in the database
        const image = await Image.create({
          name: req.file.originalname,
          path: req.file.path
        });
    
        res.status(201).json({
          message: 'Image uploaded successfully',
          data: image
        });
      } catch (error) {
        res.status(500).json({ error: 'Failed to upload image' });
      }
    });
    
    // Route to fetch images
    app.get('/images', async (req, res) => {
      try {
        const images = await Image.findAll();
        res.json(images);
      } catch (error) {
        res.status(500).json({ error: 'Failed to retrieve images' });
      }
    });
    
    const PORT = process.env.PORT || 3000;
    app.listen(PORT, () => {
      console.log(`Server is running on port ${PORT}`);
    });
    ```
    
6. **<mark>Directory Structure</mark>**
    
    ```bash
    image-upload-app
    ├── uploads/               # Directory where images are stored
    ├── models/
    │   ├── image.js           # Sequelize model for Image
    │   └── index.js           # Sequelize model index file
    ├── migrations/            # Sequelize migrations
    ├── config/                # Sequelize configuration
    ├── app.js                 # Main app file
    └── package.json
    ```
    
    Ensure that you create an **uploads/** directory to store the images:
    
    ```bash
    mkdir uploads
    ```
    
7. #### **<mark>Test the API</mark>**
    
    Use a tool like **Postman** or **cURL** to test the image upload.
    
    **Upload an image**,
    
    ```bash
    POST /upload
    Content-Type: multipart/form-data
    Body: 
      Key: "image" (file)
    ```
    
    **Fetch all images**,
    
    ```json
    GET /images
    ```
    
    This will return a list of images along with their file paths stored in the database.
