99designs / gqlgen

go generate based graphql server library
https://gqlgen.com
MIT License
9.96k stars 1.17k forks source link

Adding directive to specific field #2433

Open AdieOlami opened 1 year ago

AdieOlami commented 1 year ago

What happened?

I created an Auth directive and passed it to just one query but seems like no query works if that single one fails. This is not the given expectation

What did you expect?

I wan only the only query to reflect this directive

Minimal graphql.schema and models to reproduce

directive @auth on FIELD_DEFINITION

type Data {
    code: Int!     
    status: String!  
    message: String!   
    packages: [String!]!
}

type PackageData {
    code: Int!     
    status: String!  
    message: String!   
    package: String!
}

type Query {
  completedPackages(limit: Int!, page: Int!): Data!
  getPackage(id: ID!): PackageData!
  activePackages(limit: Int!, page: Int!): Data! @auth
}

func Auth(ctx context.Context, obj interface{}, next graphql.Resolver) (interface{}, error) {
    tokenData, err := middleware.CtxValue(ctx)
    if err != nil {
        return nil, err
    }
    if tokenData == nil {
        return nil, &gqlerror.Error{
            Message: "Access Denied",
        }
    }

    return next(ctx)
}

func GraphqlHandler(db *mongo.Database) gin.HandlerFunc {
    // NewExecutableSchema and Config are in the generated.go file
    // Resolver is in the resolver.go file
    c := generated.Config{Resolvers: &graph.Resolver{Collection: db.Collection("deliveries")}}
    c.Directives.Auth = directives.Auth
    h := handler.NewDefaultServer(
        generated.NewExecutableSchema(c))

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

versions

endigma commented 9 months ago

This behavior is also inconsistent between custom types and builtins from what I've observed

endigma commented 9 months ago

You can get around this using graphql.AddError like:

if err != nil {
        graphql.AddError(ctx, err)

        return nil, nil
    }