mirror of
https://github.com/Floriansylvain/RenewCMS.git
synced 2026-08-19 11:43:22 +02:00
Cleaned, refactored, added db init script
This commit is contained in:
+23
-1
@@ -1,7 +1,29 @@
|
||||
package internal
|
||||
|
||||
import "github.com/gin-gonic/gin"
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"go.mongodb.org/mongo-driver/bson"
|
||||
)
|
||||
|
||||
type Article struct {
|
||||
Id_name string `json:"id_name" bson:"id_name"`
|
||||
Date int64 `json:"date" bson:"date"`
|
||||
Content interface{} `json:"content" bson:"content"`
|
||||
}
|
||||
|
||||
func AddArticle(c *gin.Context) {
|
||||
var article Article
|
||||
if c.BindJSON(&article) != nil {
|
||||
SendErrorMessageToClient(c, "Could not correctly parse the article.")
|
||||
}
|
||||
|
||||
document, err := bson.Marshal(article)
|
||||
if err != nil {
|
||||
SendErrorMessageToClient(c, "Could not correctly marshal the article.")
|
||||
}
|
||||
|
||||
err = pushDocument(Location{Database: "gohcms", Collection: "articles"}, document)
|
||||
if err != nil {
|
||||
SendErrorMessageToClient(c, "Could not insert document into DB.")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
package internal
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"go.mongodb.org/mongo-driver/mongo"
|
||||
"go.mongodb.org/mongo-driver/mongo/options"
|
||||
)
|
||||
|
||||
type Location struct {
|
||||
Database string
|
||||
Collection string
|
||||
}
|
||||
|
||||
func getNewClient() *mongo.Client {
|
||||
client, err := mongo.Connect(
|
||||
context.TODO(),
|
||||
options.Client().ApplyURI("mongodb://db:27017/"))
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return client
|
||||
}
|
||||
|
||||
func pushDocument(location Location, document interface{}) error {
|
||||
client := getNewClient()
|
||||
defer client.Disconnect(context.TODO())
|
||||
|
||||
coll := client.Database(location.Database).Collection(location.Collection)
|
||||
_, err := coll.InsertOne(context.TODO(), document)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// func getDocument(database string, collection string) {
|
||||
// }
|
||||
@@ -0,0 +1,15 @@
|
||||
package internal
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type errorMessage struct {
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
func SendErrorMessageToClient(c *gin.Context, message string) {
|
||||
c.JSON(http.StatusBadRequest, errorMessage{Message: message})
|
||||
}
|
||||
Reference in New Issue
Block a user