buildValidations builds the data required to generate validations for the projected types.
(projected *expr.AttributeExpr, scope *codegen.NameScope)
| 2250 | // buildValidations builds the data required to generate validations for the |
| 2251 | // projected types. |
| 2252 | func buildValidations(projected *expr.AttributeExpr, scope *codegen.NameScope) []*ValidateData { |
| 2253 | ut := projected.Type.(expr.UserType) |
| 2254 | tname := scope.GoTypeName(projected) |
| 2255 | var validations []*ValidateData |
| 2256 | if rt, isrt := ut.(*expr.ResultTypeExpr); isrt { |
| 2257 | // for result types we create a validation function containing view |
| 2258 | // specific validation logic for each view |
| 2259 | arr := expr.AsArray(projected.Type) |
| 2260 | for _, view := range rt.Views { |
| 2261 | data := map[string]any{ |
| 2262 | "Projected": tname, |
| 2263 | "ArgVar": "result", |
| 2264 | "Source": "result", |
| 2265 | "IsCollection": arr != nil, |
| 2266 | } |
| 2267 | var vn string |
| 2268 | name := "Validate" + tname |
| 2269 | if view.Name != expr.DefaultView { |
| 2270 | vn = codegen.Goify(view.Name, true) |
| 2271 | name += vn |
| 2272 | } |
| 2273 | |
| 2274 | if arr != nil { |
| 2275 | // dealing with an array type |
| 2276 | data["Source"] = "item" |
| 2277 | data["ValidateVar"] = "Validate" + scope.GoTypeName(arr.ElemType) + vn |
| 2278 | } else { |
| 2279 | var fields []map[string]any |
| 2280 | o := &expr.Object{} |
| 2281 | walkViewAttrs(expr.AsObject(projected.Type), view, func(name string, attr, vatt *expr.AttributeExpr) { |
| 2282 | if rt, ok := attr.Type.(*expr.ResultTypeExpr); ok { |
| 2283 | // use explicitly specified view (if any) for the attribute, |
| 2284 | // otherwise use default |
| 2285 | vw := "" |
| 2286 | if v, ok := vatt.Meta.Last(expr.ViewMetaKey); ok && v != expr.DefaultView { |
| 2287 | vw = v |
| 2288 | } |
| 2289 | fields = append(fields, map[string]any{ |
| 2290 | "Name": name, |
| 2291 | "ValidateVar": "Validate" + scope.GoTypeName(attr) + codegen.Goify(vw, true), |
| 2292 | "IsRequired": rt.Attribute().IsRequired(name), |
| 2293 | }) |
| 2294 | } else { |
| 2295 | o.Set(name, attr) |
| 2296 | } |
| 2297 | }) |
| 2298 | ctx := projectedTypeContext("", !expr.IsPrimitive(projected.Type), scope) |
| 2299 | data["Validate"] = codegen.ValidationCode(&expr.AttributeExpr{Type: o, Validation: rt.Validation}, rt, ctx, true, false, true, "result") |
| 2300 | data["Fields"] = fields |
| 2301 | } |
| 2302 | |
| 2303 | buf := &bytes.Buffer{} |
| 2304 | if err := validateTypeCodeTmpl.Execute(buf, data); err != nil { |
| 2305 | panic(err) // bug |
| 2306 | } |
| 2307 | |
| 2308 | validations = append(validations, &ValidateData{ |
| 2309 | Name: name, |
no test coverage detected