blob: f72a221b213b0c967a2fcee4bd48e6a853e0601a [file] [log] [blame]
// Licensed to Apache Software Foundation (ASF) under one or more contributor
// license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright
// ownership. Apache Software Foundation (ASF) licenses this file to you under
// the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package main
import (
"fmt"
"github.com/99designs/gqlgen/api"
"github.com/99designs/gqlgen/codegen/config"
"github.com/99designs/gqlgen/plugin/modelgen"
"go/types"
"os"
"strings"
)
func addingOmitemptyToTag(tag string) string {
jsonPrefix := strings.Index(tag, "json:\"")
if jsonPrefix < 0 {
return tag + "json:\",omitempty\""
}
endInx := strings.Index(tag[jsonPrefix+6:], "\"")
jsonTag := "json:\"" + tag[jsonPrefix+6:endInx+6] + ",omitempty\""
return jsonTag + tag[endInx+7:]
}
// Defining mutation function
func mutateHook(b *modelgen.ModelBuild) *modelgen.ModelBuild {
for _, model := range b.Models {
for _, field := range model.Fields {
switch field.Type.(type) {
case *types.Pointer:
field.Tag = addingOmitemptyToTag(field.Tag)
}
}
}
return b
}
func main() {
cfg, err := config.LoadConfigFromDefaultLocations()
if err != nil {
fmt.Fprintln(os.Stderr, "failed to load config", err.Error())
os.Exit(2)
}
// Attaching the mutation function onto modelgen plugin
p := modelgen.Plugin{
MutateHook: mutateHook,
}
err = api.Generate(cfg, api.ReplacePlugin(&p))
if err != nil {
fmt.Fprintln(os.Stderr, err.Error())
os.Exit(3)
}
}