Advertisement
Guest User

Untitled

a guest
Mar 28th, 2017
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.91 KB | None | 0 0
  1. // In your database/models:
  2. type User struct {
  3. Name sql.NullString // Or any other maybe/option/nullable type
  4. }
  5.  
  6. // In your graphql schema, use this helper to define a nullable string field:
  7. func resolveNullableString(p graphql.ResolveParams) (interface{}, error) {
  8. v := reflect.ValueOf(p.Source).Elem()
  9. if !v.IsValid() {
  10. return nil, fmt.Errorf("Invalid elem: %v", p.Source)
  11. }
  12. fieldName := convertFieldName(p.Info.FieldName)
  13. f := v.FieldByName(fieldName)
  14. if !f.IsValid() {
  15. return nil, fmt.Errorf("Missing field: %v", fieldName)
  16. }
  17.  
  18. nullString := f.Interface().(sql.NullString)
  19. if nullString.Valid {
  20. return nullString.String, nil
  21. }
  22.  
  23. return nil, nil
  24. }
  25.  
  26. // You could also create other nullable types if necessary
  27. var nullableStringField = &graphql.Field{
  28. Type: graphql.String,
  29. Resolve: resolveNullableString,
  30. }
  31.  
  32. // Then define your fields using that field:
  33. fields := graphql.Fields{
  34. "name": nullableStringField,
  35. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement