gqlgen
gqlgen copied to clipboard
How should I implement a directive to format time
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.
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