Iris: How can we use "context.Background()" with dgraph (graph database)

Created on 2 May 2018  Â·  3Comments  Â·  Source: kataras/iris

Hi,

I am using dgraph (graph database) for my app - https://github.com/dgraph-io/dgo

And using it's dgraph client - I am stuck at issue of context.Background which dgraph client uses from context package

Since, IRIS has it's own context, it's conflicting with it.

Code Example :-

package main

import (
    "context"
    "encoding/json"
    "fmt"
    "log"
    "time"

    "github.com/dgraph-io/dgo"
    "github.com/dgraph-io/dgo/protos/api"
    "google.golang.org/grpc"
)

type School struct {
    Name string `json:"name,omitempty"`
}

type loc struct {
    Type   string    `json:"type,omitempty"`
    Coords []float64 `json:"coordinates,omitempty"`
}

// If omitempty is not set, then edges with empty values (0 for int/float, "" for string, false
// for bool) would be created for values not specified explicitly.

type Person struct {
    Uid      string     `json:"uid,omitempty"`
    Name     string     `json:"name,omitempty"`
    Age      int        `json:"age,omitempty"`
    Dob      *time.Time `json:"dob,omitempty"`
    Married  bool       `json:"married,omitempty"`
    Raw      []byte     `json:"raw_bytes",omitempty`
    Friends  []Person   `json:"friend,omitempty"`
    Location loc        `json:"loc,omitempty"`
    School   []School   `json:"school,omitempty"`
}

func check(err error) {
    if err != nil {
        log.Fatal(err)
    }
}

func main() {
    conn, err := grpc.Dial("127.0.0.1:9080", grpc.WithInsecure())
    check(err)
    defer conn.Close()

    dc := api.NewDgraphClient(conn)
    dg := dgo.NewDgraphClient(dc)

    dob := time.Date(1980, 01, 01, 23, 0, 0, 0, time.UTC)

    p := Person{
        Name:    "Alice",
        Age:     26,
        Married: true,
        Location: loc{
            Type:   "Point",
            Coords: []float64{1.1, 2},
        },
        Dob: &dob,
        Raw: []byte("raw_bytes"),
        Friends: []Person{{
            Name: "Bob",
            Age:  24,
        }, {
            Name: "Charlie",
            Age:  29,
        }},
        School: []School{{
            Name: "Crown Public School",
        }},
    }

    op := &api.Operation{}
    op.Schema = `
        name: string @index(exact) .
        age: int .
        married: bool .
        loc: geo .
        dob: datetime .
    `

    ctx := context.Background()
    err = dg.Alter(ctx, op)
    check(err)

    mu := &api.Mutation{
        CommitNow: true,
    }
    pb, err := json.Marshal(p)
    check(err)

    mu.SetJson = pb
    assigned, err := dg.NewTxn().Mutate(ctx, mu)
    check(err)

    // Assigned uids for nodes which were created would be returned in the resp.AssignedUids map.
    variables := map[string]string{"$id": assigned.Uids["blank-0"]}
    q := `query Me($id: string){
        me(func: uid($id)) {
            name
            dob
            age
            loc
            raw_bytes
            married
            friend @filter(eq(name, "Bob")){
                name
                age
            }
            school {
                name
            }
        }
    }`

    resp, err := dg.NewTxn().QueryWithVars(ctx, q, variables)
    check(err)

    type Root struct {
        Me []Person `json:"me"`
    }

    var r Root
    err = json.Unmarshal(resp.Json, &r)
    check(err)

    // fmt.Printf("Me: %+v\n", r.Me)
    // R.Me would be same as the person that we set above.

    fmt.Println(string(resp.Json))
}

As you see in above code, dgraph client uses contextpackage for context.Background.

Is it possible to use with IRIS ?

Most helpful comment

I really loved you right now, you didn't prejudice my answer, you didn't take it as a bad personal thing (like some haters would do), because it wasn't, realy. You seem extremely clever and "down to earth" person, believe me, you can learn even faster than you know so far, wish you the bests, I'll be here for you as well @rebootcode :)

All 3 comments

Hello, first of all Iris has nothing to do with this and you should knew about it.

The standard context package can be used anywhere, it's just a helper for handling timeouts with a common way, nothing more and nothing less, iris has nothing to do with it, it doesn't have any relation, so it can't be conflict.

Iris' context is an HTTP LIFECYCLE CONTEXT. For your information, net/http package uses the context package, you can grab it inside iris handler by ctx.Request().Context().

Although you can just import the context standard go package and use context.Background() as you already do. Your code should work as it's and even if it's not, it is not Iris' problem, this code snippet doesn't even include Iris, how could you ever imagine that Iris can be conflicted here? :P

More help written in the kataras/iris/FAQ.md: in Iris (and go 1.9+) you don't have to import the github.com/kataras/iris/context directly, use the iris.Context alias instead for an iris handler: func(ctx iris.Context){}.

Now, the following is for everybody not only for you dear @rebootcode: If or when you need help on your personal or even company-scale projects you can just chat with me and I will be glad to help you, you don't have to open issues here about other packages, github issues pages exists for other reasons, I have to teach you, if you ask for it, and I can't do this from here, please respect the project, me and most of all yourself.

Sincerely,
Gerasimos Maropoulos

Hi bro, Thanks for the help. I am just trying to learn graph database by building an app using Iris. This is how I try to learn.
I am a slow learner and my plan is to switch to go (iris) and graph database from PHP/Python-MySQL pair to "go / dart" and 'graph database" before I can build anything big.

I will ask next time in the chat box for such question, "lesson learned" and sorry for this inconvenience.

I really appreciate your hard work and I will definitely be paying back to you one day for your such an amazing and hard effort towards a community.
You are truly inspiring and definitely deserves more, and I personally will definitely do when I am ready and take go ( iris ) to my profession :+1:

I really loved you right now, you didn't prejudice my answer, you didn't take it as a bad personal thing (like some haters would do), because it wasn't, realy. You seem extremely clever and "down to earth" person, believe me, you can learn even faster than you know so far, wish you the bests, I'll be here for you as well @rebootcode :)

Was this page helpful?
0 / 5 - 0 ratings

Related issues

ZetDeveloper picture ZetDeveloper  Â·  3Comments

chiquitawow picture chiquitawow  Â·  5Comments

caimingyi484 picture caimingyi484  Â·  4Comments

AlbinoGeek picture AlbinoGeek  Â·  3Comments

stefanwuthrich picture stefanwuthrich  Â·  4Comments