Newer
Older
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
// define package name
package controllers
// import library
import(
"time"
"context"
"github.com/gin-gonic/gin"
"github.com/Debzou/REST-API-GO/internal/models"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/bson"
"net/http"
"log"
)
// DATABASE INSTANCE
var collection2 *mongo.Collection
// define the collection
func ConsumptionCollection(c *mongo.Database) {
collection2 = c.Collection("consumption")
}
// Post Ecolyo consumption in mongodb
func PostConsumption(c *gin.Context) {
var json models.Consumption
c.Bind(&json)
ctx, cancel:= context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
collection2.InsertOne(ctx, json)
// display message & httpstatus
c.JSON(http.StatusOK, gin.H{"message": "An user consumption is posted"})
return
}
func GetAllConsumption(c *gin.Context) {
// init table consumption structure
var results []models.Consumption
var consumption models.Consumption
// define the context
ctx, cancel:= context.WithTimeout(context.Background(), 10*time.Second)
defer cancel() // releases resources if slowOperation completes before timeout elapses
// find all consumption
cursor, err := collection2.Find(ctx, bson.D{})
if err != nil {
c.JSON(http.StatusNoContent, gin.H{"message": "err"})
panic(err)
} else {
for cursor.Next(ctx) {
// decode the document
if err := cursor.Decode(&consumption); err != nil {
log.Fatal(err)
}
// add in table
results =append(results, consumption)
}
c.JSON(http.StatusOK, gin.H{"data": results})
}
}