2

Kanan Rahimov (KenanBek)

 2 years ago
source link: https://kenanbek.github.io/go-dgraph-wrapper
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Go Dgraph Wrapper

Published: Apr 28, 2020 / Last modified: Apr 28, 2020

This is an example of Dgraph Go wrapper I use in one of my projects. It wraps context, connection and client. Transaction handling is not ideal yet but I will keep updating this page.

package dgraph

import (
	"context"
	"encoding/json"
	"github.com/dgraph-io/dgo/v200"
	"github.com/dgraph-io/dgo/v200/protos/api"
	"google.golang.org/grpc"
	"log"
)

type DBInstance struct {
	ctx  context.Context
	conn *grpc.ClientConn
	cln  *dgo.Dgraph
	txn  *dgo.Txn
}

func NewDB() *DBInstance {
	ctx := context.TODO()

	conn, err := grpc.Dial("localhost:9080", grpc.WithInsecure())
	if err != nil {
		log.Fatal(err)
	}

	cln := dgo.NewDgraphClient(api.NewDgraphClient(conn))
	txn := cln.NewTxn()

	return &DBInstance{
		ctx:  ctx,
		conn: conn,
		cln:  cln,
		txn:  txn,
	}
}

func (db *DBInstance) Mutate(value interface{}) (*api.Response, error) {
	var err error

	b, err := json.Marshal(value)
	if err != nil {
		log.Fatal("failed to marshal", err)
	}

	mu := &api.Mutation{
		SetJson: b,
	}
	res, err := db.txn.Mutate(db.ctx, mu)
	if err != nil {
		log.Fatal("failed to mutate", err)
	}

	return res, err
}

func (db *DBInstance) CommitAndClose() error {
	var err error

	if db.txn != nil {
		err = db.txn.Commit(db.ctx)
		if err != nil {
			log.Fatal("failed to commit", err)
			return err
		}
	}

	err = db.conn.Close()
	if err != nil {
		log.Fatal("failed to close connection", err)
		return err
	}

	return nil
}

[ Tags ]

graph graph database dgraph go golang wrapper

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK