Ejemplo n.º 1
0
// toSchemaHref produces a href that replaces the path wildcards with JSON schema references when
// appropriate.
func toSchemaHref(api *design.APIDefinition, r *design.RouteDefinition) string {
	params := r.Params()
	args := make([]interface{}, len(params))
	for i, p := range params {
		args[i] = fmt.Sprintf("/{%s}", p)
	}
	tmpl := design.WildcardRegex.ReplaceAllLiteralString(r.FullPath(), "%s")
	return fmt.Sprintf(tmpl, args...)
}
Ejemplo n.º 2
0
func buildPathFromDefinition(s *Swagger, api *design.APIDefinition, route *design.RouteDefinition) error {
	action := route.Parent
	tagNames, err := tagNamesFromDefinition([]design.MetadataDefinition{action.Parent.Metadata, action.Metadata})
	if err != nil {
		return err
	}
	params, err := paramsFromDefinition(action.AllParams(), route.FullPath())
	if err != nil {
		return err
	}
	responses := make(map[string]*Response, len(action.Responses))
	for _, r := range action.Responses {
		resp, err := responseFromDefinition(s, api, r)
		if err != nil {
			return err
		}
		responses[strconv.Itoa(r.Status)] = resp
	}
	if action.Payload != nil {
		payloadSchema := genschema.TypeSchema(api, action.Payload)
		pp := &Parameter{
			Name:        "payload",
			In:          "body",
			Description: action.Payload.Description,
			Required:    true,
			Schema:      payloadSchema,
		}
		params = append(params, pp)
	}
	operationID := fmt.Sprintf("%s#%s", action.Parent.Name, action.Name)
	index := 0
	for i, rt := range action.Routes {
		if rt == route {
			index = i
			break
		}
	}
	if index > 0 {
		operationID = fmt.Sprintf("%s#%d", operationID, index)
	}
	schemes := action.Schemes
	if len(schemes) == 0 {
		schemes = api.Schemes
	}
	operation := &Operation{
		Tags:         tagNames,
		Description:  action.Description,
		ExternalDocs: docsFromDefinition(action.Docs),
		OperationID:  operationID,
		Consumes:     []string{"application/json"},
		Produces:     []string{"application/json"},
		Parameters:   params,
		Responses:    responses,
		Schemes:      schemes,
		Deprecated:   false,
	}
	key := design.WildcardRegex.ReplaceAllStringFunc(
		route.FullPath(),
		func(w string) string {
			return fmt.Sprintf("/{%s}", w[2:])
		},
	)
	if key == "" {
		key = "/"
	}
	key = strings.TrimPrefix(key, api.BasePath)
	var path *Path
	var ok bool
	if path, ok = s.Paths[key]; !ok {
		path = new(Path)
		s.Paths[key] = path
	}
	switch route.Verb {
	case "GET":
		path.Get = operation
	case "PUT":
		path.Put = operation
	case "POST":
		path.Post = operation
	case "DELETE":
		path.Delete = operation
	case "OPTIONS":
		path.Options = operation
	case "HEAD":
		path.Head = operation
	case "PATCH":
		path.Patch = operation
	}
	return nil
}