当前位置: 首页>>代码示例>>Golang>>正文


Golang design.AttributeDefinition类代码示例

本文整理汇总了Golang中github.com/goadesign/goa/design.AttributeDefinition的典型用法代码示例。如果您正苦于以下问题:Golang AttributeDefinition类的具体用法?Golang AttributeDefinition怎么用?Golang AttributeDefinition使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了AttributeDefinition类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: Params

// Params describe the action parameters, either path parameters identified via wildcards or query
// string parameters if there is no corresponding path parameter. Each parameter is described via
// the Param function which uses the same DSL as the Attribute DSL. Here is an example:
//
//	Params(func() {
//		Param("id", Integer)		// A path parameter defined using e.g. GET("/:id")
//		Param("sort", String, func() {	// A query string parameter
//			Enum("asc", "desc")
//		})
//	})
//
// Params can be used inside Action to define the action parameters, Resource to define common
// parameters to all the resource actions or API to define common parameters to all the API actions.
//
// If Params is used inside Resource or Action then the resource base media type attributes provide
// default values for all the properties of params with identical names. For example:
//
//     var BottleMedia = MediaType("application/vnd.bottle", func() {
//         Attributes(func() {
//             Attribute("name", String, "The name of the bottle", func() {
//                 MinLength(2) // BottleMedia has one attribute "name" which is a
//                              // string that must be at least 2 characters long.
//             })
//         })
//         View("default", func() {
//             Attribute("name")
//         })
//     })
//
//     var _ = Resource("Bottle", func() {
//         DefaultMedia(BottleMedia) // Resource "Bottle" uses "BottleMedia" as default
//         Action("show", func() {   // media type.
//             Routing(GET("/:name"))
//             Params(func() {
//                 Param("name") // inherits type, description and validation from
//                               // BottleMedia "name" attribute
//             })
//         })
//     })
//
func Params(dsl func()) {
	var params *design.AttributeDefinition
	switch def := dslengine.CurrentDefinition().(type) {
	case *design.ActionDefinition:
		params = newAttribute(def.Parent.MediaType)
	case *design.ResourceDefinition:
		params = newAttribute(def.MediaType)
	case *design.APIDefinition:
		params = new(design.AttributeDefinition)
	default:
		dslengine.IncompatibleDSL()
	}
	params.Type = make(design.Object)
	if !dslengine.Execute(dsl, params) {
		return
	}
	switch def := dslengine.CurrentDefinition().(type) {
	case *design.ActionDefinition:
		def.Params = def.Params.Merge(params) // Useful for traits
	case *design.ResourceDefinition:
		def.Params = def.Params.Merge(params) // Useful for traits
	case *design.APIDefinition:
		def.Params = def.Params.Merge(params) // Useful for traits
	}
}
开发者ID:konstantin-dzreev,项目名称:goa,代码行数:65,代码来源:action.go

示例2: RecursiveFinalizer

// RecursiveFinalizer produces Go code that sets the default values for fields recursively for the
// given attribute.
func RecursiveFinalizer(att *design.AttributeDefinition, target string, depth int, vs ...map[string]bool) string {
	var assignments []string
	if o := att.Type.ToObject(); o != nil {
		if mt, ok := att.Type.(*design.MediaTypeDefinition); ok {
			if len(vs) == 0 {
				vs = []map[string]bool{make(map[string]bool)}
			} else if _, ok := vs[0][mt.TypeName]; ok {
				return ""
			}
			vs[0][mt.TypeName] = true
			att = mt.AttributeDefinition
		} else if ut, ok := att.Type.(*design.UserTypeDefinition); ok {
			if len(vs) == 0 {
				vs = []map[string]bool{make(map[string]bool)}
			} else if _, ok := vs[0][ut.TypeName]; ok {
				return ""
			}
			vs[0][ut.TypeName] = true
			att = ut.AttributeDefinition
		}
		o.IterateAttributes(func(n string, catt *design.AttributeDefinition) error {
			if att.HasDefaultValue(n) {
				data := map[string]interface{}{
					"target":     target,
					"field":      n,
					"catt":       catt,
					"depth":      depth,
					"isDatetime": catt.Type == design.DateTime,
					"defaultVal": printVal(catt.Type, catt.DefaultValue),
				}
				assignments = append(assignments, RunTemplate(assignmentT, data))
			}
			assignment := RecursiveFinalizer(
				catt,
				fmt.Sprintf("%s.%s", target, Goify(n, true)),
				depth+1,
				vs...,
			)
			if assignment != "" {
				if catt.Type.IsObject() {
					assignment = fmt.Sprintf("%sif %s.%s != nil {\n%s\n%s}",
						Tabs(depth), target, Goify(n, true), assignment, Tabs(depth))
				}
				assignments = append(assignments, assignment)
			}
			return nil
		})
	} else if a := att.Type.ToArray(); a != nil {
		data := map[string]interface{}{
			"elemType": a.ElemType,
			"target":   target,
			"depth":    1,
		}
		assignment := RunTemplate(arrayAssignmentT, data)
		if assignment != "" {
			assignments = append(assignments, assignment)
		}
	}
	return strings.Join(assignments, "\n")
}
开发者ID:konstantin-dzreev,项目名称:goa,代码行数:62,代码来源:finalizer.go

示例3: ArrayOf

// ArrayOf creates an array type from its element type. The result can be used anywhere a type can.
// Examples:
//
//	var Bottle = Type("bottle", func() {
//		Attribute("name")
//	})
//
//	var Bottles = ArrayOf(Bottle)
//
//	Action("update", func() {
//		Params(func() {
//			Param("ids", ArrayOf(Integer))
//		})
//		Payload(ArrayOf(Bottle))  // Equivalent to Payload(Bottles)
//	})
//
// If you are looking to return a collection of elements in a Response
// clause, refer to CollectionOf.  ArrayOf creates a type, where
// CollectionOf creates a media type.
func ArrayOf(t design.DataType) *design.Array {
	at := design.AttributeDefinition{Type: t}
	if ds, ok := t.(design.DataStructure); ok {
		at.APIVersions = ds.Definition().APIVersions
	}
	return &design.Array{ElemType: &at}
}
开发者ID:intfrr,项目名称:goa,代码行数:26,代码来源:type.go

示例4: attributeTags

// attributeTags computes the struct field tags.
func attributeTags(parent, att *design.AttributeDefinition, name string, private bool) string {
	var elems []string
	keys := make([]string, len(att.Metadata))
	i := 0
	for k := range att.Metadata {
		keys[i] = k
		i++
	}
	sort.Strings(keys)
	for _, key := range keys {
		val := att.Metadata[key]
		if strings.HasPrefix(key, "struct:tag:") {
			name := key[11:]
			value := strings.Join(val, ",")
			elems = append(elems, fmt.Sprintf("%s:\"%s\"", name, value))
		}
	}
	if len(elems) > 0 {
		return " `" + strings.Join(elems, " ") + "`"
	}
	// Default algorithm
	var omit string
	if private || (!parent.IsRequired(name) && !parent.HasDefaultValue(name)) {
		omit = ",omitempty"
	}
	return fmt.Sprintf(" `form:\"%s%s\" json:\"%s%s\" xml:\"%s%s\"`", name, omit, name, omit, name, omit)
}
开发者ID:konstantin-dzreev,项目名称:goa,代码行数:28,代码来源:types.go

示例5: goTypeDefObject

// goTypeDefObject returns the Go code that defines a Go struct.
func goTypeDefObject(obj design.Object, def *design.AttributeDefinition, tabs int, jsonTags, private bool) string {
	var buffer bytes.Buffer
	buffer.WriteString("struct {\n")
	keys := make([]string, len(obj))
	i := 0
	for n := range obj {
		keys[i] = n
		i++
	}
	sort.Strings(keys)
	for _, name := range keys {
		WriteTabs(&buffer, tabs+1)
		field := obj[name]
		typedef := GoTypeDef(field, tabs+1, jsonTags, private)
		if (field.Type.IsPrimitive() && private) || field.Type.IsObject() || def.IsPrimitivePointer(name) {
			typedef = "*" + typedef
		}
		fname := GoifyAtt(field, name, true)
		var tags string
		if jsonTags {
			tags = attributeTags(def, field, name, private)
		}
		desc := obj[name].Description
		if desc != "" {
			desc = strings.Replace(desc, "\n", "\n\t// ", -1)
			desc = fmt.Sprintf("// %s\n\t", desc)
		}
		buffer.WriteString(fmt.Sprintf("%s%s %s%s\n", desc, fname, typedef, tags))
	}
	WriteTabs(&buffer, tabs)
	buffer.WriteString("}")
	return buffer.String()
}
开发者ID:konstantin-dzreev,项目名称:goa,代码行数:34,代码来源:types.go

示例6: paramsFromDefinition

func paramsFromDefinition(params *design.AttributeDefinition, path string) ([]*Parameter, error) {
	if params == nil {
		return nil, nil
	}
	obj := params.Type.ToObject()
	if obj == nil {
		return nil, fmt.Errorf("invalid parameters definition, not an object")
	}
	res := make([]*Parameter, len(obj))
	i := 0
	wildcards := design.ExtractWildcards(path)
	obj.IterateAttributes(func(n string, at *design.AttributeDefinition) error {
		in := "query"
		required := params.IsRequired(n)
		for _, w := range wildcards {
			if n == w {
				in = "path"
				required = true
				break
			}
		}
		param := paramFor(at, n, in, required)
		res[i] = param
		i++
		return nil
	})
	return res, nil
}
开发者ID:konstantin-dzreev,项目名称:goa,代码行数:28,代码来源:swagger.go

示例7: RecursivePublicizer

// RecursivePublicizer produces code that copies fields from the private struct to the
// public struct
func RecursivePublicizer(att *design.AttributeDefinition, source, target string, depth int) string {
	var publications []string
	if o := att.Type.ToObject(); o != nil {
		if mt, ok := att.Type.(*design.MediaTypeDefinition); ok {
			// Hmm media types should never get here
			att = mt.AttributeDefinition
		} else if ut, ok := att.Type.(*design.UserTypeDefinition); ok {
			att = ut.AttributeDefinition
		}
		o.IterateAttributes(func(n string, catt *design.AttributeDefinition) error {
			publication := Publicizer(
				catt,
				fmt.Sprintf("%s.%s", source, Goify(n, true)),
				fmt.Sprintf("%s.%s", target, Goify(n, true)),
				catt.Type.IsPrimitive() && !att.IsPrimitivePointer(n),
				depth+1,
				false,
			)
			publication = fmt.Sprintf("%sif %s.%s != nil {\n%s\n%s}",
				Tabs(depth), source, Goify(n, true), publication, Tabs(depth))
			publications = append(publications, publication)
			return nil
		})
	}
	return strings.Join(publications, "\n")
}
开发者ID:ajoulie,项目名称:goa,代码行数:28,代码来源:publicizer.go

示例8: payload

func payload(isOptional bool, p interface{}, dsls ...func()) {
	if len(dsls) > 1 {
		dslengine.ReportError("too many arguments given to Payload")
		return
	}
	if a, ok := actionDefinition(); ok {
		var att *design.AttributeDefinition
		var dsl func()
		switch actual := p.(type) {
		case func():
			dsl = actual
			att = newAttribute(a.Parent.MediaType)
			att.Type = design.Object{}
		case *design.AttributeDefinition:
			att = design.DupAtt(actual)
		case *design.UserTypeDefinition:
			if len(dsls) == 0 {
				a.Payload = actual
				a.PayloadOptional = isOptional
				return
			}
			att = design.DupAtt(actual.Definition())
		case *design.MediaTypeDefinition:
			att = design.DupAtt(actual.AttributeDefinition)
		case string:
			ut, ok := design.Design.Types[actual]
			if !ok {
				dslengine.ReportError("unknown payload type %s", actual)
			}
			att = design.DupAtt(ut.AttributeDefinition)
		case *design.Array:
			att = &design.AttributeDefinition{Type: actual}
		case *design.Hash:
			att = &design.AttributeDefinition{Type: actual}
		case design.Primitive:
			att = &design.AttributeDefinition{Type: actual}
		default:
			dslengine.ReportError("invalid Payload argument, must be a type, a media type or a DSL building a type")
			return
		}
		if len(dsls) == 1 {
			if dsl != nil {
				dslengine.ReportError("invalid arguments in Payload call, must be (type), (dsl) or (type, dsl)")
			}
			dsl = dsls[0]
		}
		if dsl != nil {
			dslengine.Execute(dsl, att)
		}
		rn := camelize(a.Parent.Name)
		an := camelize(a.Name)
		a.Payload = &design.UserTypeDefinition{
			AttributeDefinition: att,
			TypeName:            fmt.Sprintf("%s%sPayload", an, rn),
		}
		a.PayloadOptional = isOptional
	}
}
开发者ID:konstantin-dzreev,项目名称:goa,代码行数:58,代码来源:action.go

示例9: attToObject

func attToObject(name string, parent, att *design.AttributeDefinition) *ObjectType {
	obj := &ObjectType{}
	obj.Label = name
	obj.Name = codegen.Goify(name, false)
	obj.Type = codegen.GoTypeRef(att.Type, nil, 0, false)
	if att.Type.IsPrimitive() && parent.IsPrimitivePointer(name) {
		obj.Pointer = "*"
	}
	return obj
}
开发者ID:smessier,项目名称:goa,代码行数:10,代码来源:test_generator.go

示例10: Required

// Required adds a "required" validation to the attribute.
// See http://json-schema.org/latest/json-schema-validation.html#anchor61.
func Required(names ...string) {
	var at *design.AttributeDefinition
	if a, ok := attributeDefinition(false); ok {
		at = a
	} else if mt, ok := mediaTypeDefinition(true); ok {
		at = mt.AttributeDefinition
	} else {
		return
	}
	if at.Type != nil && at.Type.Kind() != design.ObjectKind {
		incompatibleAttributeType("required", at.Type.Name(), "an object")
	} else {
		at.Validations = append(at.Validations, &dslengine.RequiredValidationDefinition{Names: names})
	}
}
开发者ID:RouGang,项目名称:goa,代码行数:17,代码来源:attribute.go

示例11: RecursiveChecker

// RecursiveChecker produces Go code that runs the validation checks recursively over the given
// attribute.
func RecursiveChecker(att *design.AttributeDefinition, nonzero, required bool, target, context string, depth int) string {
	var checks []string
	validation := ValidationChecker(att, nonzero, required, target, context, depth)
	if validation != "" {
		checks = append(checks, validation)
	}
	if o := att.Type.ToObject(); o != nil {
		if mt, ok := att.Type.(*design.MediaTypeDefinition); ok {
			att = mt.AttributeDefinition
		} else if ut, ok := att.Type.(*design.UserTypeDefinition); ok {
			att = ut.AttributeDefinition
		}
		o.IterateAttributes(func(n string, catt *design.AttributeDefinition) error {
			actualDepth := depth
			if catt.Type.IsObject() {
				actualDepth = depth + 1
			}
			validation := RecursiveChecker(
				catt,
				att.IsNonZero(n),
				att.IsRequired(n),
				fmt.Sprintf("%s.%s", target, Goify(n, true)),
				fmt.Sprintf("%s.%s", context, n),
				actualDepth,
			)
			if validation != "" {
				if catt.Type.IsObject() {
					validation = fmt.Sprintf("%sif %s.%s != nil {\n%s\n%s}",
						Tabs(depth), target, Goify(n, true), validation, Tabs(depth))
				}
				checks = append(checks, validation)
			}
			return nil
		})
	} else if a := att.Type.ToArray(); a != nil {
		data := map[string]interface{}{
			"elemType": a.ElemType,
			"context":  context,
			"target":   target,
			"depth":    1,
		}
		validation := RunTemplate(arrayValT, data)
		if validation != "" {
			checks = append(checks, validation)
		}
	}
	return strings.Join(checks, "\n")
}
开发者ID:RouGang,项目名称:goa,代码行数:50,代码来源:validation.go

示例12: addAttributeToModel

func addAttributeToModel(name string, att *design.AttributeDefinition, m *RelationalModelDefinition) {
	var parent *design.AttributeDefinition
	parent = m.AttributeDefinition
	if parent != nil {
		if parent.Type == nil {
			parent.Type = design.Object{}
		}
		if _, ok := parent.Type.(design.Object); !ok {
			dslengine.ReportError("can't define child attributes on attribute of type %s", parent.Type.Name())
			return
		}

		parent.Type.(design.Object)[name] = att
	}

}
开发者ID:goadesign,项目名称:gorma,代码行数:16,代码来源:relationalmodel.go

示例13: Payload

// Payload implements the action payload DSL. An action payload describes the HTTP request body
// data structure. The function accepts either a type or a DSL that describes the payload members
// using the Member DSL which accepts the same syntax as the Attribute DSL. This function can be
// called passing in a type, a DSL or both. Examples:
//
//	Payload(BottlePayload)		// Request payload is described by the BottlePayload type
//
//	Payload(func() {		// Request payload is an object and is described inline
//		Member("Name")
//	})
//
//	Payload(BottlePayload, func() {	// Request payload is described by merging the inline
//		Required("Name")	// definition into the BottlePayload type.
//	})
//
func Payload(p interface{}, dsls ...func()) {
	if len(dsls) > 1 {
		ReportError("too many arguments given to Payload")
		return
	}
	if a, ok := actionDefinition(true); ok {
		var att *design.AttributeDefinition
		var dsl func()
		switch actual := p.(type) {
		case func():
			dsl = actual
			att = newAttribute(a.Parent.MediaType)
			att.Type = design.Object{}
		case *design.AttributeDefinition:
			att = actual.Dup()
		case design.DataStructure:
			att = actual.Definition().Dup()
		case string:
			ut, ok := design.Design.Types[actual]
			if !ok {
				ReportError("unknown payload type %s", actual)
			}
			att = ut.AttributeDefinition.Dup()
		case *design.Array:
			att = &design.AttributeDefinition{Type: actual}
		case *design.Hash:
			att = &design.AttributeDefinition{Type: actual}
		case design.Primitive:
			att = &design.AttributeDefinition{Type: actual}
		}
		if len(dsls) == 1 {
			if dsl != nil {
				ReportError("invalid arguments in Payload call, must be (type), (dsl) or (type, dsl)")
			}
			dsl = dsls[0]
		}
		if dsl != nil {
			ExecuteDSL(dsl, att)
		}
		rn := inflect.Camelize(a.Parent.Name)
		an := inflect.Camelize(a.Name)
		a.Payload = &design.UserTypeDefinition{
			AttributeDefinition: att,
			TypeName:            fmt.Sprintf("%s%sPayload", an, rn),
		}
	}
}
开发者ID:jianjunliu,项目名称:goa,代码行数:62,代码来源:action.go

示例14: BaseParams

// BaseParams defines the API base path parameters. These parameters may correspond to wildcards in
// the BasePath or URL query string values.
// The DSL for describing each Param is the Attribute DSL.
func BaseParams(dsl func()) {
	params := new(design.AttributeDefinition)
	if !dslengine.Execute(dsl, params) {
		return
	}
	params.NonZeroAttributes = make(map[string]bool)
	for n := range params.Type.ToObject() {
		params.NonZeroAttributes[n] = true
	}
	if a, ok := apiDefinition(false); ok {
		a.BaseParams = params
	} else if v, ok := versionDefinition(false); ok {
		v.BaseParams = params
	} else if r, ok := resourceDefinition(true); ok {
		r.BaseParams = params
	}
}
开发者ID:stuartweir,项目名称:goa,代码行数:20,代码来源:api.go

示例15: BaseParams

// BaseParams defines the API base path parameters. These parameters may correspond to wildcards in
// the BasePath or URL query string values.
// The DSL for describing each Param is the Attribute DSL.
func BaseParams(dsl func()) {
	params := new(design.AttributeDefinition)
	if !dslengine.Execute(dsl, params) {
		return
	}
	params.NonZeroAttributes = make(map[string]bool)
	for n := range params.Type.ToObject() {
		params.NonZeroAttributes[n] = true
	}

	switch def := dslengine.CurrentDefinition().(type) {
	case *design.APIDefinition:
		def.BaseParams = params
	case *design.ResourceDefinition:
		def.BaseParams = params
	default:
		dslengine.IncompatibleDSL()
	}
}
开发者ID:ajoulie,项目名称:goa,代码行数:22,代码来源:api.go


注:本文中的github.com/goadesign/goa/design.AttributeDefinition类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。