Blood Bank Management System Project with Source Code | Sequelize Setup: Database Connection, Model Creation, and GET API | Service Module API | React & Node JS Project Tutorial | Part 4

Learn how to create a fully functional Blood Bank Management System using modern technologies. This step-by-step guide is perfect for both beginners and experienced developers, offering source code and practical insights. With a focus on React JS, Node JS, and Bootstrap, you'll develop an efficient system for managing blood donations, inventory, and donors. Start building your blood bank management system today!

Technologies Used

  • React JS
  • Node JS
  • Bootstrap
  • HTML & CSS

Basic Requirement

  1. Node JS
  2. Editor
  3. Web browser

How to Set Up Sequelize for Database Connection and Create a GET API in Node.js

Sequelize is a popular ORM (Object-Relational Mapping) tool for Node.js that allows you to interact with SQL databases easily. In this guide, we will walk through how to set up Sequelize, create a service model, and build a GET API to fetch data from a database.

Step 1: Install Sequelize and Database Driver

To get started, you need to install Sequelize and the appropriate database driver (we’ll use MySQL in this case):

npm install sequelize mysql2
        

Step 2: Set Up Sequelize

In your project, create a new folder named config/ and a file config/database.js to configure the database connection.

const { Sequelize } = require('sequelize');

const sequelize = new Sequelize('database_name', 'username', 'password', {
    host: 'localhost',
    dialect: 'mysql'
});

sequelize.authenticate()
    .then(() => {
        console.log('Connection has been established successfully.');
    })
    .catch(err => {
        console.error('Unable to connect to the database:', err);
    });

module.exports = sequelize;
        

Replace database_name, username, and password with your actual database credentials.

Step 3: Create the Service Model

In the models/ folder, create a file called service.js. This will define the service model with columns id, name, img, and status.

const { DataTypes } = require('sequelize');
const sequelize = require('../config/database');

const Service = sequelize.define('Service', {
    id: {
        type: DataTypes.INTEGER,
        autoIncrement: true,
        primaryKey: true,
    },
    name: {
        type: DataTypes.STRING,
        allowNull: false,
    },
    img: {
        type: DataTypes.STRING,
        allowNull: true,
    },
    status: {
        type: DataTypes.BOOLEAN,
        defaultValue: true,
    },
}, {
    tableName: 'services',
    timestamps: false,
});

module.exports = Service;
        

Step 4: Sync the Model with the Database

In your app.js or server entry file, ensure that Sequelize synchronizes the model with the database. This creates the table if it doesn’t exist.

const express = require('express');
const sequelize = require('./config/database');
const Service = require('./models/service');

const app = express();

sequelize.sync()
    .then(() => {
        console.log('Database & tables synced!');
    })
    .catch(err => {
        console.error('Error syncing database:', err);
    });

app.listen(4000, () => {
    console.log('Server is running on http://localhost:4000');
});
        

Step 5: Create a GET API to Fetch Services

Now let’s create a simple GET API to fetch the list of services. In the routes/ folder, create a file called serviceRoutes.js:

const express = require('express');
const router = express.Router();
const Service = require('../models/service');

router.get('/services', async (req, res) => {
    try {
        const services = await Service.findAll();
        res.json(services);
    } catch (err) {
        res.status(500).json({ error: 'Failed to fetch services' });
    }
});

module.exports = router;
        

Include this route in your main app.js file:

const express = require('express');
const sequelize = require('./config/database');
const serviceRoutes = require('./routes/serviceRoutes');

const app = express();

sequelize.sync();

app.use(express.json());

app.use('/api', serviceRoutes);

app.listen(4000, () => {
    console.log('Server is running on http://localhost:4000');
});
        

Step 6: Test the GET API

Run your Node.js server:

npm start
        

Visit http://localhost:4000/api/services in your browser or use Postman to make a GET request and see all the available services from the database.