aboutsummaryrefslogtreecommitdiff
path: root/backend/db/mongo.go
blob: b29f5f2cfd9e423f02a9837fa1726c5775519a78 (plain) (blame)
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
package db

import (
	"context"
	"fmt"
	"time"

	log "github.com/sirupsen/logrus"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

var Session *mongo.Session
var pastes *mongo.Collection

func initSessions(user, pass, ip string) {
	log.Infof("attempting connection to %s", ip)

	// build uri string
	URIfmt := "mongodb://%s:%s@%s:27017"
	mongoURI := fmt.Sprintf(URIfmt, user, pass, ip)

	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	client, err := mongo.Connect(ctx, options.Client().ApplyURI(mongoURI))
	if err != nil {
		log.Fatalf("error establishing connection to mongo: %s", err.Error())
	}

	// ensure expiry check
  expiryIndex := options.Index().SetExpireAfterSeconds(0)
	sessionTTL := mongo.IndexModel{
		Keys: []string{"expiry"},
    Options: expiryIndex,
	}

	// ensure hashes are unique
  uniqueIndex := options.Index().SetUnique(true)
	uniqueHashes := mongo.IndexModel{
		Keys:    []string{"hash"},
    Options: uniqueIndex,
	}

	_, _ = client.Database("main").Collection("pastes").Indexes().CreateOne(ctx, sessionTTL)
	_, _ = client.Database("main").Collection("pastes").Indexes().CreateOne(ctx, uniqueHashes)

	// Define connection to Databases
	pastes = client.Database("main").Collection("pastes")
}

func insert(new Paste) error {
	ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
	defer cancel()
  _, err := pastes.InsertOne(ctx, new)
  return err
}

func fetch(hash string) (Paste, error) {
	p := Paste{}
	q := bson.M{"hash": hash}
	ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
	defer cancel()
	result := pastes.FindOne(ctx, q)
	if (result.Err() != nil) {
	  return p, result.Err()
	} else {
	  result.Decode(&p)
	  return p, nil
	}
}