-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
79 lines (66 loc) · 1.95 KB
/
index.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
/* eslint-disable */
const express = require("express");
const cors = require("cors");
const mongoose = require("mongoose");
const router = require("./routes/main.routes");
const schedule = require("node-schedule");
const dayWord = require("./models/dayWord");
const Words = require("./models/words");
require("dotenv").config();
const PORT = process.env.PORT || 5000;
const mongoUri = process.env.mongoUri;
const app = express();
app.use(express.json({ extended: true }));
app.use(
"/api",
cors({
origin: process.env.CLIENT_URL
}),
router
);
const getWords = async () => {
try {
const words = await Words.find();
return words[0].words;
} catch (e) {
return e;
}
};
const getTodayWord = async () => {
const words = await getWords();
const randomWord = words[Math.floor(Math.random() * words.length)];
const today = new Date();
const todayDate = `${today.getDate()}-${
today.getMonth() + 1
}-${today.getFullYear()}`;
await dayWord.findOneAndUpdate({ date: todayDate }, { name: randomWord });
};
// For inserting new day words
const insertDayWords = async () => {
const words = await getWords();
const today = new Date();
const asyncLoop = async () => {
// Before using make sure to change dates in wordDate and also the loop condition, it depends on number of the days in certain month
for (let i = 1; i < 31; i++) {
const randomWord = words[Math.floor(Math.random() * words.length)];
const wordDate = `${i}-${today.getMonth() + 3}-${today.getFullYear()}`;
const newDayWord = new dayWord({ name: randomWord, date: wordDate });
await newDayWord.save();
}
};
asyncLoop();
};
const start = async () => {
try {
await mongoose.connect(mongoUri, {
useNewUrlParser: true,
useUnifiedTopology: true
});
app.listen(PORT, () => console.log(`Server is running on port ${PORT}`));
} catch (error) {
console.log(error);
process.exit(1);
}
};
start();
/* eslint-enable */