gqlgen icon indicating copy to clipboard operation
gqlgen copied to clipboard

How should I implement a directive to format time

Open zhouyusd opened this issue 1 year ago • 1 comments

I defined a directive:

directive @timeFormat(format: String!) on FIELD

and use

query {
    todo {
        createdAt @timeFormat(format:"2006-01-02")
    }
}

I'm trying to implement it

func NewSchema(client *ent.Client) graphql.ExecutableSchema {
	return graph.NewExecutableSchema(graph.Config{
		Resolvers: &Resolver{client: client},
		Directives: graph.DirectiveRoot{
			TimeFormat: func(ctx context.Context, obj interface{}, next graphql.Resolver, format string) (res interface{}, err error) {
				res, err = next(ctx)
				if err != nil {
					return nil, err
				}
				t, ok := res.(time.Time)
				if !ok {
					return nil, errors.New("timeFormat directive only works on time.Time")
				}
				return t.Format(format), nil
			},
		},
	})
}

I found that this is invalid.

zhouyusd avatar May 26 '23 15:05 zhouyusd

I had the same problem.

In General I used the context in the directive to pass the time format to the Marshaller.

Then I used a ContextMarshaler to retrieve the time format, from this point it is pretty straight-forward. This example helped me a lot: MyCustomBooleanScalar Just use Date as your scalar

Let me know if further explanations are needed

itraviv avatar Nov 12 '23 19:11 itraviv