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
Please following below code :
db.data is your model define
To create the
Model
based on the data provided by you, I would be breaking down them down into three sub-models, one forconfig
, another one forpoint
and the last one fortooltip
since those are the three feature of interest which we’re looking at. So in youmodels
directoryOnce the three models have been created; then I would define a
/saveData
route inside myapp.js
orserver.js
file(this is opinionated and for simplicity I used, you can follow the routes folder approach as well) where thePOST
request happens.This code will start the server on port
3000
. You can then send aPOST
request from you app or via some client tohttp://localhost:3000/saveData
with your data object in the body to save the data to the database. Hope this helps.