1package generator
2
3import (
4	"github.com/dave/jennifer/jen"
5	"github.com/graphql-go/graphql/language/ast"
6)
7
8// Fetch deprecation reason given set of directives; default to empty string.
9// Specification: https://github.com/facebook/graphql/blob/398e443983724463b8474b12a260fba31c19c2a9/spec/Section%203%20--%20Type%20System.md#deprecated
10func getDeprecationReason(ds []*ast.Directive) string {
11	// Determine if deprecated directive was given.
12	var directive *ast.Directive
13	for _, d := range ds {
14		if d.Name.Value != "deprecated" {
15			continue
16		}
17		directive = d
18	}
19
20	// If deprecated directive is not present return an empty string.
21	if directive == nil {
22		return ""
23	}
24
25	// Iterate through arguments for reason and return if given.
26	for _, arg := range directive.Arguments {
27		if arg.Name.Value != "reason" {
28			continue
29		}
30		val := arg.Value.GetValue()
31		if reason, ok := val.(string); ok {
32			return reason
33		}
34		logger.WithField("value", val).Error("given deprecation reason of unexpected type")
35		break
36	}
37
38	// As per GraphQL spec fallback to 'No longer supported'.
39	return "No longer supported"
40}
41
42func genDeprecationReason(ds []*ast.Directive) jen.Code {
43	reason := getDeprecationReason(ds)
44	return jen.Lit(reason)
45}
46