-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.js
220 lines (184 loc) · 6.89 KB
/
server.js
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
const express = require('express')
const axios = require('axios');
const cheerio = require('cheerio');
const multer = require('multer');
const cors = require('cors');
const morgan = require('morgan')
const app = express()
const cookieParser = require('cookie-parser');
const User = require('./models/users')
const userRoutes = require('./routes/usersRoutes')
const blogRoutes = require('./routes/blogRoutes')
const videoRoutes = require('./routes/videoRoutes')
const quoteRoutes = require('./routes/quoteRoutes')
const Avatar = require('./models/avatar')
const avatarRoutes = require('./routes/avatarRoutes')
require('dotenv').config()
const authenticateToken = require('./middlewares/authenticateToken');
const PORT = process.env.PORT || 3001
const storage = multer.memoryStorage(); // Store file in memory for now
const upload = multer({ storage });
//Middlewares
app.use(cors());
app.use(morgan('dev'));
app.use(express.json()); // To parse JSON data in request bodies
app.use('/users',userRoutes)
app.use('/avatar',avatarRoutes)
app.use('/blogs',blogRoutes)
app.use('/videos',videoRoutes)
app.use('/quote',quoteRoutes)
app.use(express.static('build'))
app.use(express.urlencoded({ extended: true }));
const mongoose = require('mongoose');
const avatar = require('./models/avatar');
const db = async ()=>{
try{
const connect = await mongoose.connect(process.env.mongoDB_URL)
// console.log(`connected successfully ${connect.connection.host}` )
}
catch(error){
// console.log(`error is ${error}`)
}
}
// Define a custom token for morgan to log custom information
morgan.token('custom-log', (req, res) => {
return 'Custom log message';
});
// Routes
app.get('/' ,(req, res) => {
res.send('Hello from the backend!');
});
app.get('/api/:symbol', async (req, res) => {
try {
// Extract the symbol from the route parameter (:symbol)
const symbol = req.params.symbol;
const url = `https://priceapi.moneycontrol.com/pricefeed/notapplicable/inidicesindia/in%${symbol}`;
const headers = {'User-Agent': 'Mozilla/5.0',}; // You can use any User-Agent string here
// Make the GET request to the external API with axios
const response = await axios.get(url, { headers });
res.json(response.data);
} catch (error) {
// Handle errors if the request to the external API fails
console.error('Error fetching data:', error.message);
res.status(500).json({ error: 'Error fetching data' });
}
});
app.get('/scrape', async (req, res) => {
try {
const url = 'https://www.moneycontrol.com/news/business/';
const response = await axios.get(url);
const $ = cheerio.load(response.data);
const newsArticles = [];
$('h2').each((index, element) => {
const headline = $(element).find('a').attr('title');
const link = $(element).find('a').attr('href');
newsArticles.push({ headline, link });
});
res.json(newsArticles);
} catch (error) {
console.error('Error while scraping:', error);
res.status(500).json({ error: 'Internal server error' });
}
});
app.get('/apicrypto/:symbol', async (req, res) => {
try {
// Extract the symbol from the route parameter (:symbol)
const symbol = req.params.symbol;
const url = `https://priceapi.moneycontrol.com/pricefeed/cryptocurrency/v1/ticker?symbol=${symbol}`;
const headers = {'User-Agent': 'Mozilla/5.0',}; // You can use any User-Agent string here
// Make the GET request to the external API with axios
const response = await axios.get(url, { headers });
res.json(response.data);
} catch (error) {
// Handle errors if the request to the external API fails
console.error('Error fetching data:', error.message);
res.status(500).json({ error: 'Error fetching data' });
}
});
app.get('/apicurrency', async (req, res) => {
try {
const url = 'https://www.marketwatch.com/investing/currency/usdinr';
const headers = {'User-Agent': 'Mozilla/5.0'};
const response = await axios.get(url, { headers });
const html = response.data;
const $ = cheerio.load(html);
const rawCurrencyValue = $('.value').text();
const numericCurrencyValue = parseFloat(rawCurrencyValue.replace(/[^0-9.]/g, '')).toFixed(2);
res.json({ currencyValue: numericCurrencyValue });
} catch (error) {
console.error('Error fetching data:', error.message);
res.status(500).json({ error: 'Error fetching data' });
}
});
app.get('/goldRate', async (req, res) => {
try {
const url = 'https://www.91mobiles.com/finance/gold-rate-in-india';
const headers = {'User-Agent': 'Mozilla/5.0',}; // You can use any User-Agent string here
const response = await axios.get(url);
const $ = cheerio.load(response.data);
const goldRate = $('.c-prc').first().text().trim();
res.json({ rate: goldRate });
} catch (error) {
// Handle errors if the request to the external API fails
console.error('Error fetching data:', error.message);
res.status(500).json({ error: 'Error fetching data' });
}
});
app.get('/getfinnifty', async (req, res) => {
try {
const url = 'https://www.moneycontrol.com/indian-indices/nifty-fin-service-47.html';
const headers = {'User-Agent': 'Mozilla/5.0',}; // You can use any User-Agent string here
const response = await axios.get(url);
const $ = cheerio.load(response.data);
const inpriceValue = $('.inprice1 input').attr('value');
res.json({ value: inpriceValue });
} catch (error) {
res.status(500).json({ error: error.message });
}
});
app.get('/users/count', async (req, res) => {
try {
const userCount = await User.countDocuments();
res.json({ count: userCount });
} catch (error) {
console.error('Error getting user count:', error);
res.status(500).json({ error: 'Internal server error' });
}
});
app.get('/userapi', authenticateToken, async (req, res) => {
try {
const userId = req.user.id;
const user = await User.findById(userId); // Fetch user data from MongoDB
if (!user) {
return res.status(404).json({ message: 'User not found' });
}
res.json(user);
} catch (error) {
res.status(500).json({ error: 'An error occurred' });
}
});
app.get('/marketnews', async (req, res) => {
try {
const url = 'https://www.livemint.com/market';
const response = await axios.get(url);
const html = response.data;
const $ = cheerio.load(html);
const headlines = [];
$('.headline[data-title]').each((index, element) => {
const headline = $(element).attr('data-title');
const link = $(element).find('a').attr('href');
headlines.push({ headline, link });
});
res.json(headlines);
} catch (error) {
res.status(500).json({ error: 'An error occurred while scraping the data.' });
}
});
app.get('*', (req, res) => {
res.sendFile('build/index.html', { root: __dirname });
});
//Starting the server
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
db();
});