-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
112 lines (105 loc) · 2.54 KB
/
main.go
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
package main
import (
"CPEventsBackend/pkgs/codechef"
"context"
"log"
"time"
"github.com/gin-contrib/cors"
"github.com/gin-gonic/gin"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
var password string = "<Redacted>"
var user string = "<Redacted>"
var url string = "mongodb+srv://" + user + ":" + password + "@<Redacted>/test?retryWrites=true&w=majority"
var results []codechef.CodechefEvent
func updateDatabaseCodechef() {
ctx := context.TODO()
clientOpt := options.Client().ApplyURI(url)
client, err := mongo.Connect(ctx, clientOpt)
if err != nil {
log.Fatal(err)
}
codechefCollection := client.Database("EventsBase").Collection("codechef-database")
delAll, err := codechefCollection.DeleteMany(ctx, bson.D{{}})
if err != nil {
log.Fatal(err)
}
log.Printf("Documents Deleted from codechef database: %d\n", delAll.DeletedCount)
docs := make([]interface{}, 0, 2000)
for _, value := range codechef.GetContestDataFromCodeChef() {
docs = append(docs, interface{}(value))
}
insertAll, err := codechefCollection.InsertMany(ctx, docs)
if err != nil {
log.Fatal(err)
}
log.Println("Documents Inserted to codechef database:", len(insertAll.InsertedIDs))
client.Disconnect(ctx)
}
func GetCodechefEvents() {
ctx := context.TODO()
clientOpt := options.Client().ApplyURI(url)
client, err := mongo.Connect(ctx, clientOpt)
if err != nil {
log.Fatal(err)
}
results = make([]codechef.CodechefEvent, 0, 2000)
codechefCollection := client.Database("EventsBase").Collection("codechef-database")
cur, err := codechefCollection.Find(ctx, bson.D{{}})
if err != nil {
log.Fatal(err)
}
for cur.Next(ctx) {
var e codechef.CodechefEvent
err = cur.Decode(&e)
if err != nil {
log.Fatal(err)
}
results = append(results, e)
}
if err := cur.Err(); err != nil {
log.Fatal(err)
}
cur.Close(ctx)
client.Disconnect(ctx)
}
func updateRoutine() {
for true {
GetCodechefEvents()
time.Sleep(4 * time.Minute)
}
}
func databaseUpdateRoutine() {
for true {
time.Sleep(15 * time.Minute)
updateDatabaseCodechef()
}
}
func handleCodechefGET(ctx *gin.Context) {
if len(results) == 0 {
ctx.JSON(500, map[string]string{
"status": "fail",
})
} else {
ctx.JSON(200, map[string]interface{}{
"status": "success",
"events": results,
})
}
}
func main() {
go updateRoutine()
go databaseUpdateRoutine()
router := gin.New()
router.Use(cors.Default())
api := router.Group("/api")
{
v1 := api.Group("/v1")
{
v1.GET("/codechef", handleCodechefGET)
}
}
router.Run()
}