GraphQL API and utilities for the rpdata project
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

28 lines
619 B

  1. package scalars
  2. import (
  3. "fmt"
  4. "io"
  5. "time"
  6. "github.com/99designs/gqlgen/graphql"
  7. )
  8. // MarshalDate marshals time into gql Date type
  9. func MarshalDate(t time.Time) graphql.Marshaler {
  10. return graphql.WriterFunc(func(w io.Writer) {
  11. w.Write([]byte(`"` + t.Format(time.RFC3339Nano) + `"`))
  12. })
  13. }
  14. // UnmarshalDate unmarshals time from gql Date type
  15. func UnmarshalDate(v interface{}) (time.Time, error) {
  16. switch v := v.(type) {
  17. case string:
  18. return time.Parse(time.RFC3339Nano, v)
  19. case int:
  20. return time.Unix(0, int64(v)*1000000), nil
  21. default:
  22. return time.Time{}, fmt.Errorf("%T is not a valid time", v)
  23. }
  24. }