skip to Main Content

I am creating a REST API using nodejs , express , MySql server , sequelize

I want to save the following object to my database.

let dataToSave = {

    "config": {
        "id": "1697141843496"
        "user_id": 27856,
        "imageurl": "my url",
        "name": "Ikea",
        "server": "Google",
        "size": "300x600",
        "imageWidth": "300",
        "imageHeight": "600",
        "hide_logo": 0,
        "point_color": "#1c846a",
        "pulse": true,
    },
    "points": [
        {
            "pointId": "292155",
            "x": 60.06711409395973,
            "y": 22.909698996655518,
            "tooltip": {
                "toltipId": "292155",
                "title": "Window",
                "price": "400",
                "link": "https://interactive-img.com/editimage?image_id=52711",
                "tooltipThumbnailUrl": "blob:http://localhost:4200/c5a7369a-94bc-423d-b3f3-474a30aad69f",
                "right": "",
                "left": "40%",
                "top": "18%"
            }
        },
        {
            "pointId": "216572",
            "x": 63.758389261744966,
            "y": 70.40133779264214,
            "tooltip": {
                "toltipId": "216572",
                "title": "Jiko",
                "price": "9000",
                "link": "https://interactive-img.com/editimage?image_id=52711",
                "tooltipThumbnailUrl": "blob:http://localhost:4200/6b26099d-75c2-4f1c-ba06-dd9e0cca14d4",
                "right": "",
                "left": "43.6667%",
                "top": "65.3333%"
            }
        }
    ],
}

How can I create model based on the above object ?

This is what I have tried so far.

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

module.exports = model;
function model(sequelize) {
    const attributes = {
        config: {
            type: DataTypes.JSON, 
        },
        points: {
            type: DataTypes.JSON, 
        },
    };

    const options = {
        defaultScope: {
            attributes: { exclude: ['hash'] }
        },
        scopes: {
            withHash: { attributes: {} }
        }
    };

    return sequelize.define('data', attributes, options);
}

2

Answers


  1. Please following below code :
    db.data is your model define

    var dataToSave = {
      config : your_json,
      points : your_json
    }
    await db.data.create(dataToSave)
     .then(async (data) => { return true; })
     .catch(async (err) => { console.log(err.message.toString())});
    
    Login or Signup to reply.
  2. To create the Model based on the data provided by you, I would be breaking down them down into three sub-models, one for config, another one for point and the last one for tooltip since those are the three feature of interest which we’re looking at. So in you models directory

    // ./models/configModel.js
    const { DataTypes } = require('sequelize');
    
    module.exports = (sequelize) => {
        const Config = sequelize.define('Config', {
            id: {
                type: DataTypes.STRING,
                primaryKey: true
            },
            user_id: {
                type: DataTypes.INTEGER
            },
            imageurl: {
                type: DataTypes.STRING
            },
            name: {
                type: DataTypes.STRING
            },
            server: {
                type: DataTypes.STRING
            },
            size: {
                type: DataTypes.STRING
            },
            imageWidth: {
                type: DataTypes.STRING
            },
            imageHeight: {
                type: DataTypes.STRING
            },
            hide_logo: {
                type: DataTypes.INTEGER
            },
            point_color: {
                type: DataTypes.STRING
            },
            pulse: {
                type: DataTypes.BOOLEAN
            }
        });
    
        return Config;
    };
    
    // ./models/pointModel.js
    module.exports = (sequelize) => {
        const Point = sequelize.define('Point', {
            pointId: {
                type: DataTypes.STRING,
                primaryKey: true
            },
            x: {
                type: DataTypes.FLOAT
            },
            y: {
                type: DataTypes.FLOAT
            }
        });
    
        return Point;
    };
    
    // ./models/tooltipModel.js
    module.exports = (sequelize) => {
        const Tooltip = sequelize.define('Tooltip', {
            tooltipId: {
                type: DataTypes.STRING,
                primaryKey: true
            },
            title: {
                type: DataTypes.STRING
            },
            price: {
                type: DataTypes.STRING
            },
            link: {
                type: DataTypes.STRING
            },
            tooltipThumbnailUrl: {
                type: DataTypes.STRING
            },
            right: {
                type: DataTypes.STRING
            },
            left: {
                type: DataTypes.STRING
            },
            top: {
                type: DataTypes.STRING
            }
        });
    
        return Tooltip;
    };
    

    Once the three models have been created; then I would define a /saveData route inside my app.js or server.js file(this is opinionated and for simplicity I used, you can follow the routes folder approach as well) where the POST request happens.

    const express = require('express');
    const bodyParser = require('body-parser');
    const db = require('./config'); // Your database config
    const Config = require('./models/configModel');
    const Point = require('./models/pointModel');
    const Tooltip = require('./models/tooltipModel');
    
    const app = express();
    
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({ extended: true }));
    
    // Rest of your code including your db sync code...
    
    app.post('/saveData', async (req, res) => {
        const dataToSave = req.body;
    
        // Save config data
        const config = await Config.create(dataToSave.config);
    
        // Save points data
        for(let point of dataToSave.points) {
            const tooltip = await Tooltip.create(point.tooltip);
            point.tooltip = tooltip.id;
            const savedPoint = await Point.create(point);
        }
    
        res.send({ message: 'Data fetch Success' });
    });
    
    // Some other code
    
    app.listen(3000, () => {
        console.log('Server is running on port 3000');
    });
    
    

    This code will start the server on port 3000. You can then send a POST request from you app or via some client to http://localhost:3000/saveData with your data object in the body to save the data to the database. Hope this helps.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search