Skip to content

Commit

Permalink
refactor : remove sequelize, change database mongodb
Browse files Browse the repository at this point in the history
  • Loading branch information
papicc45 committed Nov 20, 2023
1 parent ee6932c commit 3998d4c
Show file tree
Hide file tree
Showing 12 changed files with 392 additions and 140 deletions.
16 changes: 11 additions & 5 deletions app.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,9 @@ var logger = require('morgan');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var app = express();

// require('dotenv').config();
require('dotenv').config({ path: '/app/env' });
const db = require('./models');

app.use(logger('dev'));
app.use(express.json());
Expand Down Expand Up @@ -53,9 +54,14 @@ app.get('/nodetest', (req, res)=> {
res.json({ check : 'check' });
})

db.sequelize.sync({ force: false }).then(() => {
app.listen(process.env.PORT, () => {
console.log(`http://localhost:${process.env.PORT}`);
});
const {connectDB} = require('./schemas/index')
connectDB();
const {initKafka} = require('./controller/CategoryController.js');

app.listen(process.env.PORT, () => {
initKafka().catch(console.error);
console.log(`http://localhost:${process.env.PORT}`);
});


module.exports = app;
14 changes: 0 additions & 14 deletions config/config.js

This file was deleted.

118 changes: 101 additions & 17 deletions controller/CategoryController.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,39 @@
const models = require('../models/index');
const {QueryTypes} = require("sequelize");
const { sequelize } = require('../models/index')
require('dotenv').config({ path: '/app/env' });
// require('dotenv').config();

const kafkaBrokers = process.env.KAFKA_BROKERS;
const { Kafka } = require('kafkajs');
const Category = require('../schemas/Category');
const Hashtag = require('../schemas/Hashtag');

const update = { $setOnInsert : { count : 0 } };
const options = { upsert : true };
exports.test = async (req, res) => {
const { categoryName, temperature } = req.body;
const query = { categoryName : categoryName, temperature : temperature };

const insertOrUpdate = await Category.updateOne(query, update, options);
const updateCount = { $inc : { count : 1 } };
const again = await Category.updateOne(query, updateCount);
res.send({ createtest, again });
}

exports.getHashtagsInfo = async (req, res) => {
try {
const result = await Hashtag.find().sort('-count');

res.json({ result });
} catch (err) {
const message = `${err.name} : ${err.parent}`;
res.status(500).json({ message })
}
}

exports.getHashtagInfo = async (req, res) => {
const tagName = req.query.tagName;
try {
const result = await models.Hashtag.findAll();
console.log(result);
const result = await Hashtag.findOne({ tagName : tagName });

res.json({ result });
} catch (err) {
const message = `${err.name} : ${err.parent}`;
Expand All @@ -19,22 +47,78 @@ exports.getTop5 = async (req, res)=> {
const temp = Math.round((temp_min + temp_max) / 2);
const minus = temp - 1;
const plus = temp + 1;
const query = `SELECT categoryName, sum(count) as count FROM category WHERE temperature >= ? AND temperature <= ? GROUP BY categoryName ORDER BY count DESC LIMIT 5`;

try {
const result = await sequelize.query(query, {
type : QueryTypes.SELECT,
replacements : [minus, plus],
});
const result = await Category.aggregate([
{
$match: {
temperature: { $gte: minus, $lte: plus }
}
},
{
$group: {
_id: "$categoryName",
count: { $sum: "$count" }
}
},
{
$sort: { count: -1 }
},
{
$limit: 5
}
]);
res.json({ result });
} catch(err) {
const message = `${err.name} : ${err.parent}`;
res.status(500).json({ message })
}
}

let categorys = new Array();
result.forEach((val)=> {
categorys.push(val.categoryName);
});
exports.searchByTyping = async (req, res) => {
const text = req.query.text;

res.json({ categorys });
} catch(err) {
try {
const result = await Hashtag.find({
tagName: { $regex: text, $options: 'i' }
}).sort({ count: -1 })

console.log(result);
res.json({ result });
} catch (err) {
const message = `${err.name} : ${err.parent}`;
res.status(500).json({ message })
}
}
}

const kafka = new Kafka({
clientId : 'category_service',
brokers : [kafkaBrokers]
})

const consumer = kafka.consumer({ groupId : 'cate'});

exports.initKafka = async () => {
await consumer.connect();
await consumer.subscribe({ topic : 'category', fromBeginning : true })
await consumer.subscribe({ topic : 'hashtag', fromBeginning : true })
await consumer.run({
eachMessage : async ({ topic, partition, message }) => {
const replace = message.value.toString().replaceAll('"', '');
//카테고리
if(topic === "category") {
const categories = replace.split('/');
categories.forEach((val) =>{
console.log(val);
})
} else { //해시태그
const hashtags = replace.split('/');
hashtags.forEach((val) => {
console.log(val);
})
}

}
})
}

30 changes: 0 additions & 30 deletions models/Category.js

This file was deleted.

26 changes: 0 additions & 26 deletions models/Hashtag.js

This file was deleted.

41 changes: 0 additions & 41 deletions models/index.js

This file was deleted.

Loading

0 comments on commit 3998d4c

Please sign in to comment.