spot_img
HomeEducationUse OceanBase in Node.js - DZone Get hold of US

Use OceanBase in Node.js – DZone Get hold of US

Welcome to the most recent episode in our sequence of articles designed that can assist you get began with OceanBase, a next-generation distributed relational database. Constructing on our earlier guides, the place we related OceanBase to a Sveltekit app and built an e-commerce app with Flask and OceanBase, we now flip our consideration to integrating OceanBase right into a Node.js undertaking utilizing the favored Sequelize ORM and the Specific server.

Sequelize is a promise-based Node ORM that helps the dialects for PostgreSQL, MySQL, MariaDB, SQLite, and naturally, OceanBase. It gives a strong set of options for mannequin querying and manipulation. Specific, alternatively, is a minimal and versatile Node net software framework that gives a strong set of options for net and cell purposes.

However why use Sequelize and Specific with OceanBase, it’s possible you’ll ask? Sequelize will assist us work together with OceanBase, which is suitable with MySQL, in a extra JavaScript-friendly manner, abstracting away a lot of the SQL syntax. Specific, being a quick, unopinionated, and minimalist net framework for Node, will permit us to construct our software’s backend with ease and effectivity.

What We Are Going to Build: A Mini-CRM System

In this article, I’m going to build a mini Customer Relationship Management (CRM) system. CRM systems are integral to managing customer data, interactions, and business information. They are crucial for businesses of all sizes to maintain effective customer relationships and to ensure smooth operations.

The mini CRM system will leverage the power of OceanBase, a next-generation distributed relational database that excels in handling massive amounts of data with high availability and strong consistency. OceanBase’s scalability and distributed nature make it a perfect fit for businesses of all sizes. As businesses grow and the volume of their data increases, they can effortlessly scale their database with OceanBase, making it an ideal choice for a CRM system and other enterprise resource planning applications.

The mini CRM system will be a simple yet powerful application that will allow us to perform Create, Read, Update, and Delete (CRUD) operations on contacts in our database. These operations form the backbone of any data-driven application and are essential for managing records in a database.

The CRM system will have the following features:

  1. Create Contacts: We will be able to add new contacts to our database. Each contact will have basic information such as name, email, company, and owner.
  2. Read Contacts: We will be able to view all the contacts stored in our database. This feature will display a list of all the contacts with their respective information. We will also be able to read the record of one specific contact.
  3. Update Contacts: This feature will allow us to modify the details of a specific contact. We can update any information related to a contact, such as changing their email or company.
  4. Delete Contacts: If we no longer need to keep contact in our database, we can delete it. This feature will remove the contact and all its related information from our database.

By building this mini CRM system, we will learn how to effectively use OceanBase in a Node.js project with Sequelize as the ORM and Express as the server. We will understand how to perform CRUD operations using Sequelize and how to structure our Express application to handle these operations. Most importantly, we will see how OceanBase can effortlessly manage our data, providing us with a reliable and scalable solution for our application’s database needs.

Setting up the Database

To set up the project, you first need a running OceanBase cluster. You have several options for doing so. You can install OceanBase in your local environment, spin up a virtual machine in the cloud to run it or use OceanBase Cloud in the AWS marketplace to arrange your cluster in just some clicks.

On this tutorial, I’ll merely arrange a demo OceanBase cluster on an AWS EC2 occasion. You possibly can learn my earlier article on learn how to install OceanBase in AWS.

After putting in OceanBase and spinning up the demo cluster, I’m going to arrange a demo consumer for the event fairly than utilizing the basis consumer, which is taken into account not safe.

We will create a brand new consumer referred to as demo that solely has entry to the database we’re utilizing. Earlier than this, I additionally created a database in OceanBase referred to as app, which would be the most important database we’ll work together with inside this text.

To create a brand new consumer, we’ll use the next command:

CREATE USER 'demo'@'localhost' IDENTIFIED BY 'password';

Subsequent, we’ll grant the consumer permission to entry the app database.

GRANT ALL PRIVILEGES ON app.* TO 'demo'@'localhost';

Now we will hook up with the OceanBase occasion from our undertaking utilizing the demo consumer credentials.

Host: YOUR_EC2_PUBLIC_IP_ADDRESS
Port: 2881
Person: demo
Password: password

Establishing the Challenge

Now, we have to arrange our Node.js undertaking. I’ll assume you have got Node.js and npm put in. If not, you’ll be able to obtain and set up them from the official Node.js website. When you’re prepared, create a brand new listing in your undertaking and initialize it with npm:

mkdir oceanbase-sequelize && cd oceanbase-sequelize
npm init -y

Subsequent, set up Specific, Sequelize, and the mysql2 driver. (Since there isn’t any direct Sequelize help of OceanBase, and OceanBase is suitable with MySQL, I’ll use the MySQL driver to hook up with OceanBase in Sequelize, which works completely effective in all my checks.)

npm set up categorical sequelize mysql2

Configuring Sequelize

Sequelize is a strong ORM device that gives a high-level abstraction for managing database operations. It helps a variety of databases, together with OceanBase (by way of MySQL). Configuring Sequelize includes organising the connection to the database and defining fashions that symbolize the tables within the database.

You should use a Command Line Interface (CLI) that simplifies the method of organising and managing your undertaking. One of many instructions supplied by the Sequelize CLI is sequelize init, which units up a primary undertaking construction for you.

Earlier than you should utilize the Sequelize CLI, you could set up it. You are able to do this by working:

npm set up --save-dev sequelize-cli

As soon as the Sequelize CLI is put in, you’ll be able to initialize your undertaking by working the next:

This command will create the next directories and information:

  • config/: This listing comprises a config.json file the place you’ll be able to specify your database configuration for various environments (improvement, take a look at, and manufacturing).
  • fashions/: This listing is in your Sequelize fashions. By default, it consists of an index.js file that units up Sequelize and imports all fashions.
  • migrations/: This listing is in your migration scripts.
  • seeders/: This listing is in your seeder information.

Configuring the Database Connection

To connect to your OceanBase database, you need to update the config/config.json file with your database credentials. Here’s my configuration for the credentials I created in the last section:


  "development": 
    "username": "demo",
    "password": "password",
    "database": "app",
    "host": "YOUR_EC2_PUBLIC_IP_ADDRESS",
        "port": 2881,
    "dialect": "mysql"
  ,
  "test": 
    "username": "your_username",
    "password": "your_password",
    "database": "your_database",
    "host": "localhost",
    "dialect": "mysql"
  ,
  "production": 
    "username": "your_username",
    "password": "your_password",
    "database": "your_database",
    "host": "localhost",
    "dialect": "mysql"
  

Now, Sequelize is configured and ready to use in your project. You can start defining your models in the models/ directory and use Sequelize’s features to interact with your OceanBase database.

Defining Data Models

Data models in Sequelize represent tables in your database. They are defined using the define method on your Sequelize instance. This method takes two arguments: the name of the model (which will be used as the table name) and an object that defines the model’s attributes.

Let’s define a Contact model for the CRM system. This model will have the following attributes: firstName, lastName, email, age, company, and owner.

Here’s how we can define this model in the models/Contact.js file:

module.exports = (sequelize, DataTypes) => 
    const Contact = sequelize.define('Contact', 
        firstName: 
            type: DataTypes.STRING,
            allowNull: false,
            validate: 
                notEmpty: true,
            ,
        ,
        lastName: 
            type: DataTypes.STRING,
            allowNull: false,
            validate: 
                notEmpty: true,
            ,
        ,
        email: 
            type: DataTypes.STRING,
            allowNull: false,
            validate: 
                notEmpty: true,
            ,
        ,
        age: 
            type: DataTypes.INTEGER,
            allowNull: true,
            validate: 
                notEmpty: true,
            ,
        ,
        company: 
            type: DataTypes.STRING,
            allowNull: true,
            validate: 
                notEmpty: true,
            ,
        ,
        owner: 
            type: DataTypes.STRING,
            allowNull: true,
            validate: 
                notEmpty: true,
            ,
        ,
    );
    return Contact;
;

In this code, we’re defining a Contact model with six attributes. Each attribute is an object that specifies the data type and validation rules.

For example, the firstName, lastName, and email attributes are of type STRING and cannot be null or empty. The age, company, and owner attributes are also of type STRING but can be null, however, they cannot be empty if provided.

The validate property is used to specify validation rules. In this case, we’re using the notEmpty rule, which ensures that the value is not an empty string.

The define method returns the model, which we then export so it can be used in other parts of our application. This Contact model now represents a Contact table in our OceanBase database. You can use this model to perform CRUD operations on the Contact table.

Building the Express Application

The Express application is the core of our project. It’s where we define our routes and handle requests. In our case, we’ll be creating routes to perform CRUD (Create, Read, Update, Delete) operations on our Contact model.

Setting Up Express

First, we import Express and create an instance of it. We also import our Contact model and the Sequelize instance from the models directory.

const express = require('express');
const app = express();

// Connect to the database
const db = require('./models');
const  Contact  = require('./models');

We also add a middleware to parse JSON bodies. This is necessary because we’ll be receiving JSON data in our POST and PATCH requests.

Creating Routes

Get All Contacts

Our first route is a GET route to /contacts. This route retrieves all contacts from the database using the findAll method on the Contact model.

app.get('/contacts', async (req, res) => 
    const contacts = await Contact.findAll();
    res.json(contacts);
);

Get a Contact by ID

Next, we have a GET route to /contact/:id. This route retrieves a single contact by its ID using the findByPk method.

app.get('/contact/:id', async (req, res) => 
    const contact = await Contact.findByPk(req.params.id);
    if (contact) 
        res.json(contact);
     else 
        res.status(404).send(
            status: 'failed',
            message: 'Contact not found',
        );
    
);

Create a New Contact

We also have a POST route to /contact. This route creates a new contact using the create method.

app.post('/contact', async (req, res) => 
    const newContact = await Contact.create(req.body);
    res.json(newContact);
);

When making a POST request to this route, the request body should be a JSON object that represents a new contact. The structure of this object should match the structure of our Contact model.

Here’s an example of how you can structure the request body:


    "firstName": "John",
    "lastName": "Doe",
    "email": "[email protected]",
    "age": 30,
    "company": "Tech Corp",
    "owner": "Jane Doe"

Delete a Contact

Our DELETE route to /contact/:id deletes a contact by its ID using the destroy method.

app.delete('/contact/:id', async (req, res) => 
    const result = await Contact.destroy(
        where: 
            id: req.params.id,
        ,
    );
    if (result) 
        res.status(200).send(
            status: 'succeed',
            message: 'Contact deleted',
        );
     else 
        res.status(404).send(
            status: 'failed',
            message: 'Contact not found',
        );
    
);

In this route, :id is a route parameter that represents the ID of the contact you want to delete. When you make a DELETE request, you replace :id with the actual ID of the contact.

For example, if you want to delete the contact with an ID of 5, you would send a DELETE request to /contact/5.

The ID of a contact is typically assigned by OceanBase when the contact is created. You can find the ID of a contact by making a GET request to the /contacts route, which returns a list of all contacts. Each contact in the list includes an id property that you can use in the DELETE route.

Update a Contact

Finally, we have a PATCH route to /contact/:id that updates a contact by its ID using the update method.

app.patch('/contact/:id', async (req, res) => 
    const updatedContact = await Contact.update(req.body, 
        where: 
            id: req.params.id,
        ,
    );
    if (updatedContact[0]) 
        res.status(200).send(
            status: 'Contact updated',
            data: await Contact.findByPk(req.params.id),
        );
     else 
        res.status(404).send(
            status: 'failed',
            message: 'Contact not found',
        );
    
);

When making a PATCH request to this route, the request body should be a JSON object that includes the properties you want to update. The structure of this object should match the structure of our Contact model, but you only need to include the properties you want to change.

Starting the Server

Finally, we synchronize our Sequelize models with our OceanBase database using db.sequelize.sync() and start our server.

db.sequelize.sync().then((req) => 
    app.listen(3000, () => 
        console.log('Server running at port 3000...');
    );
);

The sync method creates the necessary tables in the database if they don’t exist. After the synchronization is complete, we start our server on port 3000.

And that’s it! We now have a fully functional Express application that can perform CRUD operations on our Contact model using Sequelize and OceanBase.

Running the App

To run the application, simply navigate to the root directory of your project in your terminal and run the command:

You should see the message “Server running at port 3000…” in your terminal, indicating that your application is running and ready to accept requests.

To interact with your application, you can use a tool like Postman, which lets you ship HTTP requests to your server and examine the responses. On this article, I’ll simply use the Thunder Client plugin in VS Code to check the requests.

Listed below are some examples of how you should utilize Thunder Consumer to work together along with your software:

Creating a New Contact

To create a new contact, you can send a POST request to http://127.0.0.1:3000/contact. In the body of the request, you would include a JSON object that represents the new contact.

In this example, we’re creating a new contact with the name “John Smith,” email “[email protected],” age 33, firm “EXAMPLE INC,” and proprietor “Wayne.” After sending the request, we obtain a response that features the brand new contact with an ID assigned by OceanBase.

Getting All Contacts

To get all contacts, you would send a GET request to http://127.0.0.1:3000/contacts.

Getting All Contacts

In this example, we’re retrieving all contacts from the OceanBase database. The response is an array of contacts.

Getting a Contact by ID

To get a contact by ID, you would send a GET request to http://127.0.0.1:3000/contact/:id, replacing :id with the ID of the contact.

Getting a Contact by ID

In this example, we’re retrieving the contact with an ID of 7. The response is the contact with that ID.

Updating a Contact

To update a contact, you would send a PATCH request to http://127.0.0.1:3000/contact/:id, replacing :id with the ID of the contact. In the body of the request, you would include a JSON object that includes the properties you want to update.

Updating a Contact

On this instance, we’re updating the primary title of the contact with an ID of 6. The response is the up to date contact.

Deleting a Contact

To delete a contact, you would send a DELETE request to http://127.0.0.1:3000/contact/:id, replacing :id with the ID of the contact.

Deleting a Contact

In this example, we’re deleting the contact with an ID of 5. The response is a message indicating that the contact was successfully deleted.

Conclusion

In this article, we’ve walked through the process of integrating OceanBase into a Node project using Sequelize and Express. We’ve built a mini-CRM system that performs CRUD operations on a Contact model.

We’ve seen how Sequelize abstracts away much of the SQL syntax, allowing us to interact with our OceanBase database in a JavaScript-friendly way. We’ve also seen how Express allows us to build our application’s backend with ease and efficiency. The mini-CRM system we’ve built is a simple yet powerful application that leverages the scalability and distributed nature of OceanBase, making it a perfect fit for businesses of all sizes.

If you want to explore the project further, you can clone the project from my GitLab repository and run it in your native machine. 

Be at liberty to switch the undertaking and experiment with completely different options of OceanBase. The chances are infinite, and there is at all times one thing new to study.

In the event you want any assist putting in or utilizing OceanBase, you’ll be able to attain out to the OceanBase workforce on Twitter (@OceanBaseDB) or ask a query on StackOverflow with the “OceanBase” tag.


#OceanBase #Node.js #DZone

RELATED ARTICLES
Continue to the category

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -spot_img

Most Popular

Recent Comments