-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlanguageController.js
More file actions
71 lines (57 loc) · 2.49 KB
/
languageController.js
File metadata and controls
71 lines (57 loc) · 2.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
// src/controllers/languageController.js
const User = require('../models/userModel');
const defaultTopics = require('../models/topicModel');
const apiResponse = require('../utils/apiResponse');
exports.getTopicsByLanguage = async (req, res) => {
try {
const language = req.body.language;
let user = await User.findOne({ firebaseUserId: req.userId });
if (!user) {
return res.status(404).json(apiResponse.error('User not found'));
}
// If not, get topics from topic model
const topic = defaultTopics.find(topic => topic.language === language);
if (!topic) {
return res.status(404).json(apiResponse.error('Language not found'));
}
// Update user topics field with the new topic
user.topics.push({ language, topics: topic.topics });
await user.save();
// Return topics to frontend
res.json(apiResponse.success(user.topics, 'Topics found'));
} catch (error) {
console.error('Error getting topics:', error);
res.status(500).json(apiResponse.error('Error getting topics', error.message));
}
};
exports.saveTopicsInUserProfile = async (req, res) => {
try {
console.log("Initial request body:", req.body);
const user = await User.findOne({ firebaseUserId: req.userId });
if (!user) {
return res.status(404).json(apiResponse.error('User not found'));
}
// Extract topics array from request body
const topics = Array.isArray(req.body) ? req.body : req.body.topics;
console.log("Processed topics:", topics);
// Validate topics
if (!topics || !Array.isArray(topics)) {
console.log("Invalid topics structure:", topics);
return res.status(400).json(apiResponse.error('Invalid topics format'));
}
// Validate topic structure
for (const topic of topics) {
if (!topic.language || !Array.isArray(topic.topics)) {
console.log("Invalid topic structure:", topic);
return res.status(400).json(apiResponse.error('Each topic must have language and topics array'));
}
}
user.topics = topics;
await user.save();
console.log('Topics saved successfully:', user.topics);
return res.json(apiResponse.success(user.topics, 'Topics saved successfully'));
} catch (error) {
console.error('Error saving topics:', error);
return res.status(500).json(apiResponse.error('Error saving topics', error.message));
}
};