CodeNewbie Community

Cover image for How I stored data in two different databases simultaneously using Axios and APIs
Sankalp Swami
Sankalp Swami

Posted on

How I stored data in two different databases simultaneously using Axios and APIs

Node.js is an open-source, cross-platform, back-end JavaScript runtime environment that runs on the V8 engine and executes JavaScript code outside the web. When it comes to scalability, Node JS is the best in the business. Working on Node JS for me is as beautiful as watching this man
Dhoni

WHAT IS AXIOS ?

Axios is an javascript library which is used to make http requests from browser and nodejs. Axios requests and provides response in json data. It intercepts requests and responses.
How to install axios

$ npm install axios
Enter fullscreen mode Exit fullscreen mode

THE SCENE

When I was working for an startup as a Node JS Dev, there was an requirement of an software which will save data to two different databases simultaneously. Actually, it was an Internet Service Providing Company and they were using some CRM application for which they were paying. They wanted to develop same application with advanced features but they didnt want to stop using the other application for their own reasons. Now, I had a task to develop an api endpoint, which was for new customer creation and that data should be stored in two different databases ie, in the new our own built application and in the one for which they were paying.

HOW I DID IT

Ofcourse, axios came for the rescue. After googling things, I settled with axios because it was the one with most the convenient way to do.
This was my POST request controller

add: (req, res) => {
        mongoose.connect(
            connUri,
            {
                useNewUrlParser: true,
                useUnifiedTopology: true,
                useFindAndModify: false,
                useCreateIndex: true,
            },
            (err) => {
                let result = {};
                let status = 201;
                if (!err) {
                        const firstName = req.body.firstName;
                        const lastName = req.body.lastName;
                        const email = req.body.email;
                        const lco = new LCO({
                            firstName,
                            lastName,
                            email
                        });
                        lco.save((err, lco) => {
                            if (!err) {
                                result.status = status;
                                result.result = lco;
                            } else {
                                status = 500;
                                result.status = status;
                                result.error = err;
                            }
                            res.status(status).send(result);
                            // Close the connection after saving
                            mongoose.connection.close();
                        });
                } else {
                    status = 500;
                    result.status = status;
                    result.error = err;
                    res.status(status).send(result);

                    mongoose.connection.close();
                }
            }
        );
    }
Enter fullscreen mode Exit fullscreen mode

So now my challenge was to store the same data to different database simultaneously with the same POST request.
Lets see how an axios POST request looks like

axios.post('{url}', {data}, {options});
Enter fullscreen mode Exit fullscreen mode

You can add headers options to the axios request. I added my headers options in config object.

 const config = {
    headers: {
         'Content-Type': 'application/x-www-form-urlencoded'
    }
 }
Enter fullscreen mode Exit fullscreen mode

After the config object, I went for another object named data, for passing it to the axios POST request.

const data = {
      firstName: firstName,
      lastName: lastName,
      email: email
}
Enter fullscreen mode Exit fullscreen mode

Now, its time for the axios part. I added the axios code snippet.

axios.post('/http://127.0.0.1:8000/api/v1/users', qs.stringify(data), config)
            .then((result) => {
                 console.log(result);
            }).catch((err) => {
                 console.log(err);
            });
Enter fullscreen mode Exit fullscreen mode

qs.stringify converts json objects into query strings.
Now My code looks like this -

add: (req, res) => {
        mongoose.connect(
            connUri,
            {
                useNewUrlParser: true,
                useUnifiedTopology: true,
                useFindAndModify: false,
                useCreateIndex: true,
            },
            (err) => {
                let result = {};
                let status = 201;
                if (!err) {
                        const config = {
                            headers: {
                                'Content-Type': 'application/x-www-form-urlencoded'
                            }
                        }
                        const firstName = req.body.firstName;
                        const lastName = req.body.lastName;
                        const email = req.body.email;
                        const lco = new LCO({
                            firstName,
                            lastName,
                            email
                        });
                        const data = {
                           firstName: firstName,
                           lastName: lastName,
                           email: email
                        }
                        lco.save((err, lco) => {
                            if (!err) {
                                result.status = status;
                                result.result = lco;
                                axios.post('/http://127.0.0.1:8000/api/v1/users', qs.stringify(data), config)
                                    .then((result) => {
                                        console.log(result);
                                    }).catch((err) => {
                                        console.log(err);
                                    });
                            } else {
                                status = 500;
                                result.status = status;
                                result.error = err;
                            }
                            res.status(status).send(result);
                            // Close the connection after saving
                            mongoose.connection.close();
                        });
                } else {
                    status = 500;
                    result.status = status;
                    result.error = err;
                    res.status(status).send(result);

                    mongoose.connection.close();
                }
            }
        );
    }
Enter fullscreen mode Exit fullscreen mode

Yep, this works very efficiently. I had a great experience learning axios when working on this project.

🙌SUPPORT

Buy Me A Coffee

Thanks for reading, keep learning, Peace and Bubbyeye..!
Dhoni

Discussion (0)