gofr-dev / gofr

An opinionated GoLang framework for accelerated microservice development. Built in support for databases and observability.
https://gofr.dev
Apache License 2.0
3.6k stars 236 forks source link

Dgraph giving panic #1234

Open Umang01-hash opened 8 hours ago

Umang01-hash commented 8 hours ago

Describe the bug When connecting DGraph and calling it's method getting a panic:

Screenshot 2024-11-22 at 1 33 03 PM

To Reproduce Steps to reproduce the behavior, if applicable:

  1. The code is
   package main

import (
    "encoding/json"
    "fmt"

    "github.com/dgraph-io/dgo/v210/protos/api"

    "gofr.dev/pkg/gofr"

    "gofr.dev/pkg/gofr/datasource/dgraph"
)

func main() {
    // Create a new application
    app := gofr.New()

    db := dgraph.New(dgraph.Config{
        Host: "localhost",
        Port: "9080",
    })

    // Connect to Dgraph running on localhost:9080
    app.AddDgraph(db)

    // Add routes for Dgraph operations
    app.POST("/dgraph", DGraphInsertHandler)
    app.GET("/dgraph", DGraphQueryHandler)

    // Run the application
    app.Run()
}

// DGraphInsertHandler handles POST requests to insert data into Dgraph
func DGraphInsertHandler(c *gofr.Context) (interface{}, error) {
    // Example mutation data to insert into Dgraph
    mutationData := `
        {
            "set": [
                {
                    "name": "GoFr Dev"
                },
                {
                    "name": "James Doe"
                }
            ]
        }
    `

    // Create an api.Mutation object
    mutation := &api.Mutation{
        SetJson:   []byte(mutationData), // Set the JSON payload
        CommitNow: true,                 // Auto-commit the transaction
    }

    // Run the mutation in Dgraph
    response, err := c.DGraph.Mutate(c, mutation)
    if err != nil {
        return nil, err
    }

    return response, nil
}

// DGraphQueryHandler handles GET requests to fetch data from Dgraph
func DGraphQueryHandler(c *gofr.Context) (interface{}, error) {
    // A simple query to fetch all persons with a name in Dgraph
    response, err := c.DGraph.Query(c, "{ persons(func: has(name)) { uid name } }")
    if err != nil {
        return nil, err
    }

    // Cast response to *api.Response (the correct type returned by Dgraph Query)
    resp, ok := response.(*api.Response)
    if !ok {
        return nil, fmt.Errorf("unexpected response type")
    }

    // Parse the response JSON
    var result map[string]interface{}
    err = json.Unmarshal(resp.Json, &result)
    if err != nil {
        return nil, err
    }

    return result, nil
}