newrelic / go-agent

New Relic Go Agent
Apache License 2.0
762 stars 297 forks source link

Integration for gqlgen #848

Closed KunalSin9h closed 6 months ago

KunalSin9h commented 6 months ago

Summary

gqlgen (https://github.com/99designs/gqlgen) is a schema first golang's graphql library. I am requesting for support of gqlgen.

gwkline commented 6 months ago

You can do this with middleware (at least partially). This example is for gin, but should apply for any server package as long as you properly set the NR agent in the context:

func (h *Handler) Graphql() gin.HandlerFunc {
    resolver := &resolver.Resolver{
        Repository: h.Repository,
    }
    c := generated.Config{Resolvers: resolver}
    serv := handler.New(generated.NewExecutableSchema(c))

    // ...
        // apply the middleware to each incoming request
    serv.AroundOperations(func(ctx context.Context, next graphql.OperationHandler) graphql.ResponseHandler {
        return h.newRelicMiddleware(ctx, next)
    })

    return func(c *gin.Context) {
        serv.ServeHTTP(c.Writer, c.Request)
    }
}

func (h *Handler) newRelicMiddleware(ctx context.Context, next graphql.OperationHandler) graphql.ResponseHandler {
    opContext := graphql.GetOperationContext(ctx)
    tx := newrelic.FromContext(ctx)
    // sets the transaction name, e.g. "query/userConnection"
    tx.SetName(fmt.Sprintf("%s/%s", opContext.Operation.Operation, opContext.Operation.Name))
    tx.AddAttribute("variables", opContext.Variables)

    return next(ctx)
}
KunalSin9h commented 6 months ago

@gwkline thanks, i will try