I’m developing a web app which watches about crypto-coins currency. So now, i’m developing a server and DB, so:
I’ve got 2 main models:
Current Coins – the list of current currency of crypto coins
and CoinInfo – the table which has detailed coin currency for all period
So I use One to Many connection for models, but i want to have the next:
I refresh my Current currency every 5 minutes, so data in this Table always refresh, so i want that on each refresh, the data which will be updated store in other table (for each coin) But i don’t how to do it:
const sequelize = require("../DB/db");
const DataTypes = require("sequelize");
const CoinDetalInfo = require("./CoinDetalnfo");
const CurrencyList = sequelize.define(
"Coin",
{
id: {
type: DataTypes.STRING,
primaryKey: true,
unique: true,
},
name: {
type: DataTypes.STRING,
},
symbol: {
type: DataTypes.STRING,
},
image: {
type: DataTypes.STRING,
},
current_price: {
type: DataTypes.FLOAT,
},
price_change_percentage_24h: {
type: DataTypes.FLOAT,
},
mkt_cap: {
type: DataTypes.FLOAT,
},
total_volume: {
type: DataTypes.FLOAT,
},
},
{ timestamps: true }
);
CurrencyList.hasMany(CoinDetalInfo, {
onDelete: "cascade",
});
module.exports = CurrencyList;
const sequelize = require("../DB/db");
const DataTypes = require("sequelize");
const CoinDetalInfo = sequelize.define("CoinInfo", {
price: {
type: DataTypes.FLOAT,
},
mkt_cap: {
type: DataTypes.FLOAT,
},
total_volume: {
type: DataTypes.FLOAT,
},
});
module.exports = CoinDetalInfo
And code which fill my First table
const axios = require("axios");
const CurrencyList = require("../Models/CurrencyList");
const URLs = require("../Configs/URLs");
module.exports = {
FillDataBaseWithCurrencyListInfo: async (req, res) => {
const collectionCurrencies = await axios.get(
URLs.CoinGeckoURL,
(response) => {
return response;
}
);
const mappedCollectionCurrencies = collectionCurrencies.data.map(
({
id,
symbol,
name,
image,
market_cap,
current_price,
price_change_percentage_24h,
total_volume,
}) => ({
id,
symbol,
name,
image,
market_cap,
current_price,
price_change_percentage_24h,
total_volume,
})
);
mappedCollectionCurrencies.map(async (item, index) => {
const found = await CurrencyList.findOne({
where: { id: item.id },
});
if (!found) {
await CurrencyList.create({
id: item.id,
name: item.name,
symbol: item.symbol,
image: item.image,
mkt_cap: item.market_cap,
current_price: item.current_price,
price_change_percentage_24h: item.price_change_percentage_24h,
total_volume: item.total_volume,
});
} else {
await CurrencyList.update(
{
name: item.name,
symbol: item.symbol,
image: item.image,
mkt_cap: item.market_cap,
current_price: item.current_price,
price_change_percentage_24h: item.price_change_percentage_24h,
total_volume: item.total_volume,
},
{
where: {
id: item.id,
},
}
);
}
});
res.send(mappedCollectionCurrencies);
},
GetCurrencyListInfoFromDataBase: async (req, res) => {
const CurrencyListCollection = await CurrencyList.findAll();
res.json(CurrencyListCollection);
},
};