Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // In your database/models:
- type User struct {
- Name sql.NullString // Or any other maybe/option/nullable type
- }
- // In your graphql schema, use this helper to define a nullable string field:
- func resolveNullableString(p graphql.ResolveParams) (interface{}, error) {
- v := reflect.ValueOf(p.Source).Elem()
- if !v.IsValid() {
- return nil, fmt.Errorf("Invalid elem: %v", p.Source)
- }
- fieldName := convertFieldName(p.Info.FieldName)
- f := v.FieldByName(fieldName)
- if !f.IsValid() {
- return nil, fmt.Errorf("Missing field: %v", fieldName)
- }
- nullString := f.Interface().(sql.NullString)
- if nullString.Valid {
- return nullString.String, nil
- }
- return nil, nil
- }
- // You could also create other nullable types if necessary
- var nullableStringField = &graphql.Field{
- Type: graphql.String,
- Resolve: resolveNullableString,
- }
- // Then define your fields using that field:
- fields := graphql.Fields{
- "name": nullableStringField,
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement