99designs / gqlgen

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

Example of using InterceptRootField with error inside the Interceptor #2700

Open ysaakpr opened 1 year ago

ysaakpr commented 1 year ago

I am using InterceptRootField as following

func (a MyExtension) InterceptRootField(ctx context.Context, next graphql.RootResolver) graphql.Marshaler {

    fc := graphql.GetRootFieldContext(ctx)

    if fc.Object == "__schema" {
        return next(ctx)
    }

    if fc.Field.Definition != nil && fc.Field.Definition.Directives != nil {
        dir := fc.Field.Definition.Directives
        if dir.ForName("IgnoreAuth") != nil {
            return next(ctx)
        }
    }

    err, ok := ctx.Value(CtxAuthKeyError).(error)
    if ok {
        log.Err(err).Msg("error while authentication in core gql")
        graphql.AddError(ctx, dErrors.Err401(err.Error()).GQLError(ctx))
        return graphql.Null
    }

    sess := session.GetSessionFromRequestContext(ctx)
    if sess == nil {
        log.Err(err).Msg("error while authentication, nil session container")

        graphql.AddError(ctx, dErrors.Err401("error while authentication, nil session container"))
        return graphql.Null
    }

    return next(ctx)
}

My schema looks like this

directive @IgnoreAuth on FIELD_DEFINITION
extend type Mutation{
    apiFirst: Response! @IgnoreAuth
    apiSecond: Response!
}

Mutation api that i called

mutation multiApis {
  apiFirst   {
    status
  }
  apiSecond {
    status
  }
}

What did you expect?

In the above example, i have one api which continues execution, and another send a graphql.Null marshaller for second response since my api validation fails.

But i am not getting the data for the first api response, and data is null with an error.

What am i doing wrong? Or is this expected ?

ysaakpr commented 1 year ago

I searched the whole guthub with InterceptRootField, and couldnt find any reference implementations.

Are there any documentation on how to throw errors while u are inside a InterceptRootField interceptor?