Create a docker image of Node-Express API – Part II


In this post which is the continuation of Node-API Docker Image ( the Links are at the end of the post), create and run container using the image we build.

Lets check the existence of the image in docker using

docker image

Create the container

To build a container to run the API we need only the Image , all the depending Image will be automatically download by Docker.

docker run --name customer -d -p 3000:3000 user-api:latest

The above command will run, customer API in detached mode on port 3000.

Stop and Resume the container

We can stop running a container at any time using docker stop <id/name> and resume with docker start <id/name>

Following Docker Post may deserve a good read

How to clear all element in mongoose object array in Nodejs


Mongoose array can set of objects basically a reference to other mongoose document placed in other document. Our task is to clear all element stored in MongoDB array of objects.

To clear we can use pull or simply an assign a blank array ([]). In our Post example we had tags array.

post.tags=[]

[] will clear all of the tag id in the tags object array

Use dotenv to store configurations in Reactjs


A modern Reactjs app can be consisting of multiple components, connection to different databases, APIs etc. In other Nodejs projects we can use the dotenv package to store configuration details and can access with process.env.

Is dotenv useful for Reactjs ? Yeh.

Suppose you have using an API in many of the components and wanna some correction in API path, may be a change in basic URL. What we do ? Go through all of the component and change the base URL. Tiresome job !

For such case place the URL in .env (/src) file and use the process.env.REACT_APP_API_SERVER in all of the component. Yo need to change only the .env file for updating base URL.

First up all install the package using

npm i dotenv

and in the App.js , require the package as follows and use it in the component

....
require("dotenv").config();
 .get(`${process.env.REACT_APP_API_SERVER}/post/find`)
      .then((response) => {

        if (response.data.length > 0) {
          this.setState({
            posts: response.data,
          });
        }
      })
      .catch((error) => {
        console.log(error);
      });

How to export multiple components in Reactjs


Usually we organize components React components in separate files. But for smaller components associated with component we are using need not be placed in operate file. In short it is possible to place multiple components in a single js file and export them.

 .....
  our component codes goes her

module.exports= {Post,Tags,Comments}

In the above fashion we can export the components and can import the components as follows

 const {Post,Tags,Comments} =from './components'

How to create ant row design for Reactjs


We are already learn how can utilize the antd for a Reactjs projects. Let’ quickly design a rows with columns ( a grid design) using the easy to use customize UI provided by Ant Design .

Go to Ant Row documentation , adjust the gutters and column count and click the copy code icon and past it where ever you need them.

Following ant design posts deserve good read

Ant layout for Reactjs apps


Ant Design is a UI Kit for developing beautiful web app and it is the second most popular one, it is just like Bootstrap we are familiar. In fact many apps have using multiple UI kits, there are plenty of UI kit available.

Install antd

Using Layouts we can create a skeleton structure of the app, which includes header, footer and content section. For using them in our React app, install the package using

npm i antd

Import Ant Design components

In our app.js we need to import the package extract the header,content,footer objects and also the css for beautify the objects as follows.

import { Layout} from "antd";
import "antd/dist/antd.css";
const { Header, Content, Footer } = Layout;

Create app layout

We have everything we needed, the Header,content,Footer components , Lets organize our app layout in app.js file of React app,

<Router>
<Layout className="layout" style={{ background: "##f759ab" }}>
      <Header>
        Your custom header components here
      </Header>
      <Content style={{ padding: "0 15px" }}>
      <Route path="/about" exact component={AboutUs} />
        You can place more routes/content here 

      </Content>
      <Footer style={{ textAlign: "center" }}>
        space for custom footer component
      </Footer>
    </Layout>
</Router>

That is the basics of the antd, explore more on he Ant for Reactjs

Following ant design posts deserve good read

How to render child components in Reactjs


Suppose we have components that called inside another in Reactjs , things can be messy. The parent component not render the child by default. Here is our code with two components.

export default class BackgroundDesign extends Component {
    render() {
        return (
            <div
            className="site-layout-content text-al"
            style={{ background: "#a8071a" }}
             
          />       
        )
    }
}

export default class SiteHeading extends Component {
  render() {
    return (
      <div className="site-layout" style={{ background: "#820014" }}>
        <span
          className="p-2"
          style={{ color: "whitesmoke", "font-size": "28px" }}
        >
          I am a Heading
        </span>
        
      </div>
    );
  }
}
 <BackgroundDesign>
            <SiteHeading/>
                It is a about  page.
            </BackgroundDesign>

In the above BackgroundDesign component we used Site Heading component which is not rendered successfully.

How to add element to mongoose object array in Nodejs


Mongoose array can set of objects basically a reference to other mongoose document placed in other document. Our task is to place a new element to MongoDB array of objects.

To add a new element we can use the $push command. In our Post example we had tags which need to added while updating the post.

Post.updateOne({_id:pst},
{
  $push:{'tags':ctag._id}
},
{  safe: true, upsert: true}
) 

$push will add the tag id to the tags object array

Alternatively we can afford the following method too. The difference is that the first one used inside a update command.

post.tags.push(stag)

How to auto create tables based on sequelize models


We had discussed how to auto create API using sequelize, on thing I missed is auto creation of tables.

Sequelize

Sequelize is a promise-based Node.js ORM for Postgres, MySQL, MariaDB, SQLite and Microsoft SQL Server. It features solid transaction support, relations, eager and lazy loading, read replication and more.

Auto create tables

Sequelize module has provided a function called sync in order to create tables based on the Sequelize models we created.

Place the call in the authenticate method of the Sequelize configuration as follows

const Sequelize=require('sequelize')
module.exports=new Sequelize('todo_collections','root','123',{
    host:'127.0.0.1',
    port:3306,
    dialect:'mysql',
    pool:{
        max:5,
        min:0,
        acquire:30000,
        idle:10000
    }
})

.......
.......

const db = require("./config/database");
db.authenticate()
  .then(() => {
      console.log("Database connected")
    db.sync()
    })
  .catch((e) => console.log("Error:" + e));
app.get("/", (req, res) => {
  res.send("Hello world");
});

We can use sync({force:true}) for drop the tables already created

You may like to read these sequelize posts too

How to resolve sequelize-JSON.parse error in Node


When I start with Sequelize ORM end up with the body-parser error. Usually we define body parser using app.use(bodyparser.json()), which globally declare parser functionality for all routes.

SyntaxError: Unexpected token in JSON at position 0
at JSON.parse ()
at createStrictSyntaxError (E:\NodeProjects\sequelize-api -mysql\node_modules\body-parser\lib\types\json.js:158:10)
at parse (E:\NodeProjects\sequelize-api -mysql\node_modules\body-parser\lib\types\json.js:83:15)
at E:\NodeProjects\sequelize-api -mysql\node_modules\body-parser\lib\read.js:121:18
at invokeCallback (E:\NodeProjects\sequelize-api -mysql\node_modules\raw-body\index.js:224:16)
at done (E:\NodeProjects\sequelize-api -mysql\node_modules\raw-body\index.js:213:7)
at IncomingMessage.onEnd (E:\NodeProjects\sequelize-api -mysql\node_modules\raw-body\index.js:273:7)
at IncomingMessage.emit (node:events:388:22)
at endReadableNT (node:internal/streams/readable:1305:12)
at processTicksAndRejections (node:internal/process/task_queues:80:21)

Here is where sequelize findAll() like functionality collides and the above error log will be populated

Solution

We can apply route specific parser to fix this mess. Let’s see how

Before the fix

For simplicity I have omitted some of the lines in index.js (Node project file). Before the fix our routes look like this

...
app.use(bodyParser.urlencoded({extended:false})) 
app.use(bodyParser.json())

app.post("/todo",  (req, res, next) => {
    const {item,description}=req.body
    Todo.create({item:item,description:description})
    .then((model) => {
      res.status(200).send(model);
      })
      .catch((e) => {
        res.status(400).send("Error:" + e);
      });
  });

app.get("/todo", (req, res, next) => {
  Todo.findAll()
    .then((model) => {
        res.json({
            error: false,
            data: model
        })
    })
    .catch(error => res.json({
        error: true,
        data: [],
        error: error
    }))
});


After the fix

After the removal of the global json parser it will look like this

...
app.use(bodyParser.urlencoded({extended:false})) 
 

app.post("/todo", bodyParser.json(), (req, res, next) => {
    const {item,description}=req.body
    Todo.create({item:item,description:description})
    .then((model) => {
      res.status(200).send(model);
      })
      .catch((e) => {
        res.status(400).send("Error:" + e);
      });
  });

app.get("/todo", (req, res, next) => {
  Todo.findAll()
    .then((model) => {
        res.json({
            error: false,
            data: model
        })
    })
    .catch(error => res.json({
        error: true,
        data: [],
        error: error
    }))
});


we have added the parser function of the bodyParser to Post routes only and the problem solved