diff --git a/dart/dart_client.go b/dart/dart_client.go index e21f48b..d6b9bec 100644 --- a/dart/dart_client.go +++ b/dart/dart_client.go @@ -14,6 +14,7 @@ import ( const ( defaultPart = "generated_rpc_client" + version = "1.0.0" Bool = "bool" Int = "int" @@ -104,7 +105,7 @@ func NewClient(schema smd.Schema, settings Settings) *Generator { // Generate returns generated Dart client func (g *Generator) Generate() ([]byte, error) { - data := templateData{Part: defaultPart, GeneratorData: gen.DefaultGeneratorData()} + data := templateData{Part: defaultPart, GeneratorData: gen.DefaultGeneratorData().AddLangAndLocalVersion(version, "dart")} if g.settings.Part != "" { data.Part = g.settings.Part diff --git a/dart/dart_client_test.go b/dart/dart_client_test.go index c02ddf9..c093a57 100644 --- a/dart/dart_client_test.go +++ b/dart/dart_client_test.go @@ -2,6 +2,7 @@ package dart import ( "bytes" + "flag" "os" "testing" @@ -9,6 +10,10 @@ import ( "github.com/vmkteam/zenrpc/v2/testdata" ) +const rpcGenFilePath = "./testdata/client.dart" + +var update = flag.Bool("update", false, "update .dart files") + func TestGenerateDartClient(t *testing.T) { rpc := zenrpc.NewServer(zenrpc.Options{}) rpc.Register("catalogue", testdata.CatalogueService{}) @@ -20,6 +25,19 @@ func TestGenerateDartClient(t *testing.T) { t.Fatalf("generate dart client: %v", err) } + if *update { + var f *os.File + f, err = os.Create(rpcGenFilePath) + if err != nil { + t.Fatal(err) + } + _, err = f.Write(generated) + if err != nil { + t.Fatal(err) + } + return + } + testData, err := os.ReadFile("./testdata/client.dart") if err != nil { t.Fatalf("open test data file: %v", err) diff --git a/dart/dart_template.go b/dart/dart_template.go index 1a3c397..7085673 100644 --- a/dart/dart_template.go +++ b/dart/dart_template.go @@ -1,6 +1,6 @@ package dart -const client = `/// Code generated from jsonrpc schema by rpcgen v{{ .Version }}; DO NOT EDIT. +const client = `/// Code generated from jsonrpc schema by rpcgen v{{ .Version }} with {{ .Lang }} v{{ .LocalVersion }}; DO NOT EDIT. import 'package:json_annotation/json_annotation.dart'; import 'package:smd_annotations/annotations.dart'; diff --git a/dart/testdata/client.dart b/dart/testdata/client.dart index 2cc10d5..794a8fb 100755 --- a/dart/testdata/client.dart +++ b/dart/testdata/client.dart @@ -1,4 +1,4 @@ -/// Code generated from jsonrpc schema by rpcgen v2.4.4; DO NOT EDIT. +/// Code generated from jsonrpc schema by rpcgen v2.5.x with dart v1.0.0; DO NOT EDIT. import 'package:json_annotation/json_annotation.dart'; import 'package:smd_annotations/annotations.dart'; diff --git a/gen/gen.go b/gen/gen.go index bb919e6..8e20366 100644 --- a/gen/gen.go +++ b/gen/gen.go @@ -10,12 +10,14 @@ import ( "golang.org/x/text/language" ) -const version = "2.5.0" +const version = "2.5.x" const DefinitionsPrefix = "#/definitions/" type GeneratorData struct { - Version string + Version string + Lang string + LocalVersion string } func DefaultGeneratorData() GeneratorData { @@ -24,6 +26,12 @@ func DefaultGeneratorData() GeneratorData { } } +func (g GeneratorData) AddLangAndLocalVersion(version, lang string) GeneratorData { + g.Lang = lang + g.LocalVersion = version + return g +} + // GetNamespaceNames return all namespace names from schema. func GetNamespaceNames(schema smd.Schema) (res []string) { m := map[string]struct{}{} diff --git a/golang/go_client.go b/golang/go_client.go index 555f107..b9b1a13 100644 --- a/golang/go_client.go +++ b/golang/go_client.go @@ -11,6 +11,11 @@ import ( "github.com/vmkteam/zenrpc/v2/smd" ) +const ( + version = "1.0.0" + lang = "golang" +) + type Settings struct { Package string } @@ -31,7 +36,7 @@ func NewClient(schema smd.Schema, settings Settings) *Generator { // Generate returns generated Go client. func (g *Generator) Generate() ([]byte, error) { - g.schema.GeneratorData = gen.DefaultGeneratorData() + g.schema.GeneratorData = gen.DefaultGeneratorData().AddLangAndLocalVersion(version, lang) g.schema.Package = g.settings.Package tmpl, err := template.New("golang client").Funcs(templateFuncs).Parse(goTpl) diff --git a/golang/go_template.go b/golang/go_template.go index 510ea93..bf78e26 100644 --- a/golang/go_template.go +++ b/golang/go_template.go @@ -1,7 +1,7 @@ package golang // goTpl contains template for Go client -const goTpl = `// Code generated from jsonrpc schema by rpcgen v{{ .Version }}; DO NOT EDIT. +const goTpl = `// Code generated from jsonrpc schema by rpcgen v{{ .Version }} with {{ .Lang }} v{{ .LocalVersion }}; DO NOT EDIT. package {{ .Package }} diff --git a/golang/rpcgen_test.go b/golang/rpcgen_test.go index 675a76b..e1e11b3 100644 --- a/golang/rpcgen_test.go +++ b/golang/rpcgen_test.go @@ -2,6 +2,7 @@ package golang import ( "bytes" + "flag" "os" "testing" @@ -9,6 +10,10 @@ import ( "github.com/vmkteam/zenrpc/v2/testdata" ) +const rpcGenFilePath = "./testdata/catalogue_client.go.test" + +var update = flag.Bool("update", false, "update .go files") + func TestGenerateGoClient(t *testing.T) { rpc := zenrpc.NewServer(zenrpc.Options{}) rpc.Register("catalogue", testdata.CatalogueService{}) @@ -22,7 +27,20 @@ func TestGenerateGoClient(t *testing.T) { t.Fatalf("generate go client: %v", err) } - testData, err := os.ReadFile("./testdata/catalogue_client.go.test") + if *update { + var f *os.File + f, err = os.Create(rpcGenFilePath) + if err != nil { + t.Fatal(err) + } + _, err = f.Write(generated) + if err != nil { + t.Fatal(err) + } + return + } + + testData, err := os.ReadFile(rpcGenFilePath) if err != nil { t.Fatalf("open test data file: %v", err) } diff --git a/golang/testdata/catalogue_client.go.test b/golang/testdata/catalogue_client.go.test index 45ea5ed..6015272 100755 --- a/golang/testdata/catalogue_client.go.test +++ b/golang/testdata/catalogue_client.go.test @@ -1,4 +1,4 @@ -// Code generated from jsonrpc schema by rpcgen v2.5.0; DO NOT EDIT. +// Code generated from jsonrpc schema by rpcgen v2.5.x with golang v1.0.0; DO NOT EDIT. package client diff --git a/kotlin/kotlin_client.go b/kotlin/kotlin_client.go index cbab05f..1723de4 100644 --- a/kotlin/kotlin_client.go +++ b/kotlin/kotlin_client.go @@ -35,6 +35,8 @@ const ( DefaultList = "emptyList()" DefaultMap = "emptyMap()" DefaultLocalTime = "LocalTime.now()" + + version = "1.0.0" ) var ( @@ -134,7 +136,7 @@ func (g *Generator) prepareTemplateData() templateData { g.settings.Class = BaseClass } - data := templateData{GeneratorData: gen.DefaultGeneratorData(), PackageAPI: g.settings.PackageAPI, Imports: g.settings.Imports, Class: g.settings.Class} + data := templateData{GeneratorData: gen.DefaultGeneratorData().AddLangAndLocalVersion(version, "kotlin"), PackageAPI: g.settings.PackageAPI, Imports: g.settings.Imports, Class: g.settings.Class} modelsMap := make(map[string]Model) servicesMap := make(map[string][]Method) diff --git a/kotlin/kotlin_template.go b/kotlin/kotlin_template.go index bcc5efa..4908a7f 100644 --- a/kotlin/kotlin_template.go +++ b/kotlin/kotlin_template.go @@ -1,6 +1,6 @@ package kotlin -const model = `/// Code generated from jsonrpc schema by rpcgen v{{ .Version }}; DO NOT EDIT. +const model = `/// Code generated from jsonrpc schema by rpcgen v{{ .Version }} with {{ .Lang }} v{{ .LocalVersion }}; DO NOT EDIT. package {{ .PackageAPI }}.model import java.time.LocalTime @@ -26,7 +26,7 @@ data class {{ $model.Name }}( ) {{ end }} ` -const protocolTemplate = `/// Code generated from jsonrpc schema by rpcgen v{{ .Version }}; DO NOT EDIT. +const protocolTemplate = `/// Code generated from jsonrpc schema by rpcgen v{{ .Version }} with {{ .Lang }} v{{ .LocalVersion }}; DO NOT EDIT. package {{ .PackageAPI }} import com.google.gson.reflect.TypeToken diff --git a/kotlin/testdata/protocol.generated.kt b/kotlin/testdata/protocol.generated.kt index 83dce54..6840db5 100644 --- a/kotlin/testdata/protocol.generated.kt +++ b/kotlin/testdata/protocol.generated.kt @@ -1,4 +1,4 @@ -/// Code generated from jsonrpc schema by rpcgen v2.7.0; DO NOT EDIT. +/// Code generated from jsonrpc schema by rpcgen v2.5.x with kotlin v1.0.0; DO NOT EDIT. package api import com.google.gson.reflect.TypeToken diff --git a/kotlin/testdata/rpc.generated.kt b/kotlin/testdata/rpc.generated.kt index f8cb50a..26156c8 100644 --- a/kotlin/testdata/rpc.generated.kt +++ b/kotlin/testdata/rpc.generated.kt @@ -1,4 +1,4 @@ -/// Code generated from jsonrpc schema by rpcgen v2.7.0; DO NOT EDIT. +/// Code generated from jsonrpc schema by rpcgen v2.5.x with kotlin v1.0.0; DO NOT EDIT. package api.model import java.time.LocalTime diff --git a/php/php_client.go b/php/php_client.go index 64da40b..6e81ea8 100644 --- a/php/php_client.go +++ b/php/php_client.go @@ -14,6 +14,7 @@ import ( const ( defaultPhpNamespace = "JsonRpcClient" + version = "1.0.0" phpBoolean = "bool" phpInt = "int" @@ -41,7 +42,7 @@ func NewClient(schema smd.Schema, phpNamespace string) *Generator { // Generate returns generate PHP client func (g *Generator) Generate() ([]byte, error) { m := g.PHPModels() - m.GeneratorData = gen.DefaultGeneratorData() + m.GeneratorData = gen.DefaultGeneratorData().AddLangAndLocalVersion(version, "php") funcMap := template.FuncMap{ "now": time.Now, diff --git a/php/php_client_test.go b/php/php_client_test.go index ab63d31..2460973 100644 --- a/php/php_client_test.go +++ b/php/php_client_test.go @@ -2,6 +2,7 @@ package php import ( "bytes" + "flag" "os" "testing" @@ -9,6 +10,10 @@ import ( "github.com/vmkteam/zenrpc/v2/testdata" ) +const rpcGenFilePath = "./testdata/RpcClient.php" + +var update = flag.Bool("update", false, "update .php files") + func TestGeneratePHPClient(t *testing.T) { rpc := zenrpc.NewServer(zenrpc.Options{}) rpc.Register("catalogue", testdata.CatalogueService{}) @@ -20,7 +25,20 @@ func TestGeneratePHPClient(t *testing.T) { t.Fatalf("generate php client: %v", err) } - testData, err := os.ReadFile("./testdata/RpcClient.php") + if *update { + var f *os.File + f, err = os.Create(rpcGenFilePath) + if err != nil { + t.Fatal(err) + } + _, err = f.Write(generated) + if err != nil { + t.Fatal(err) + } + return + } + + testData, err := os.ReadFile(rpcGenFilePath) if err != nil { t.Fatalf("open test data file: %v", err) } diff --git a/php/php_template.go b/php/php_template.go index a85b24a..6480184 100644 --- a/php/php_template.go +++ b/php/php_template.go @@ -1,7 +1,7 @@ package php const phpTpl = ` {{ if $method.Returns.Type }}Result<{{ $method.Returns.Type }}, RpcError>{{ else }}RpcError?{{ end }} { - await request(.{{ $method.SafeName }}{{ if $method.Parameters }}({{- range $index, $item := $method.Parameters }}{{ $item.Name }}: {{ $item.Name }}{{ if (notLast $index (len $method.Parameters)) }}, {{ end }}{{ end }}){{ else }}{{ end }}) + await request(.{{ $method.SafeName }}({{ if $method.Parameters }}{{- range $index, $item := $method.Parameters }}{{ $item.Name }}: {{ $item.Name }}{{ if (notLast $index (len $method.Parameters)) }}, {{ end }}{{ end }}{{ else }}{{ end }})) } {{- if (notLast $idx (len $service.Methods)) }} {{ end }} diff --git a/swift/testdata/arith.go b/swift/testdata/arith.go new file mode 100644 index 0000000..81367bb --- /dev/null +++ b/swift/testdata/arith.go @@ -0,0 +1,161 @@ +package testdata + +import ( + "context" + "errors" + "math" + + "github.com/vmkteam/zenrpc/v2" +) + +//go:generate zenrpc + +type ArithService struct{ zenrpc.Service } + +type Point struct { + X, Y int // coordinate + Z int `json:"-"` + ID int `json:"id"` // version id - 1 + BaseID int `json:"baseId"` // version id - 2 + SecondID int `json:"secondID"` // version id - 3 + CreatedAt string `json:"createdAt"` // version date - 1 + UpdatedAt string `json:"updatedAt"` // version date - 2 + ManualChangedAt string `json:"manualChangedAt"` // version date - 3 + NewLat float64 `json:"newLat"` // version group geo coordinate № - 1 + NewLon float64 `json:"newLon"` // version group geo coordinate № - 1 + Lat float64 `json:"lat"` // version group geo coordinate № - 2 + Lon float64 `json:"lon"` // version group geo coordinate № - 2 + Latitude float64 `json:"latitude"` // version group geo coordinate № - 3 + Longitude float64 `json:"longitude"` // version group geo coordinate № - 3 + BaseFloat float64 `json:"baseFloat"` // version group float - 1 + SecondFloat float32 `json:"secondFloat"` // version group float - 2 + EmptyString *string `json:"emptyString"` + Name string `json:"name"` + SecondPoints []Point `json:"secondPoints"` + NextQuotient Quotient `json:"nextQuotient"` + SecondQuotient *Quotient `json:"secondQuotient"` + Class string `json:"class"` +} + +type SecondPoint struct { +} + +// Sum sums two digits and returns error with error code as result and IP from context. +func (as ArithService) Sum(ctx context.Context, a, b int) (bool, *zenrpc.Error) { + r, _ := zenrpc.RequestFromContext(ctx) + + return true, zenrpc.NewStringError(a+b, r.Host) +} + +func (as ArithService) Positive() (bool, *zenrpc.Error) { + return true, nil +} + +func (ArithService) DoSomething() { + // some optimistic operations +} +func (ArithService) DoSomethingV2() ExternalData { + // some optimistic operations + return ExternalData{} +} + +func (ArithService) GetPoints() []Point { + return []Point{} +} + +//zenrpc:return Point test description in return +func (ArithService) DoSomethingWithPoint(p Point, pp []Point) Point { + // some optimistic operations + return p +} + +// Multiply multiples two digits and returns result. +func (as ArithService) Multiply(a, b int) int { + return a * b +} + +// CheckError throws error is isErr true. +// TEST row 2 +// +//zenrpc:500 test error +func (ArithService) CheckError(isErr bool) error { + if isErr { + return errors.New("test") + } + + return nil +} + +// CheckZenRPCError throws zenrpc error is isErr true. +// Second description row +// +//zenrpc:500 test error +func (ArithService) CheckZenRPCError(isErr bool) *zenrpc.Error { + if isErr { + return zenrpc.NewStringError(500, "test") + } + + return nil +} + +// Quotient docs +type Quotient struct { + // Quo docs + Quo int + + // Rem docs + Rem int `json:"rem"` + BaseRow string `json:"baseRow"` + RowNil *string `json:"rowNil"` + Data CycleInitStruct `json:"data"` +} + +type CycleInitStruct struct { + IsCycleInit bool `json:"isCycleInit"` +} +type ExternalData struct { + Name string `json:"name"` +} + +// Divide divides two numbers. +// +//zenrpc:a the a +//zenrpc:b the b +//zenrpc:quo result is Quotient, should be named var +//zenrpc:401 we do not serve 1 +func (as *ArithService) Divide(a, b int) (quo *Quotient, err error) { + if b == 0 { + return nil, errors.New("divide by zero") + } else if b == 1 { + return nil, zenrpc.NewError(401, errors.New("we do not serve 1")) + } + + return &Quotient{ + Quo: a / b, + Rem: a % b, + }, nil +} + +// Pow returns x**y, the base-x exponential of y. If Exp is not set then default value is 2. +// +//zenrpc:exp=2 exponent could be empty +func (as *ArithService) Pow(base float64, exp *float64) float64 { + return math.Pow(base, *exp) +} + +// Pi returns math.Pi. +func (ArithService) Pi() float64 { + return math.Pi +} + +// SumArray returns sum all items from array +// +//zenrpc:array=[]float64{1,2,4} +func (as *ArithService) SumArray(array *[]float64) float64 { + var sum float64 + + for _, i := range *array { + sum += i + } + return sum +} diff --git a/swift/testdata/protocol.generated.swift b/swift/testdata/protocol.generated.swift index ee2977d..9342c20 100644 --- a/swift/testdata/protocol.generated.swift +++ b/swift/testdata/protocol.generated.swift @@ -1,17 +1,20 @@ -/// Code generated from jsonrpc schema by rpcgen v2.4.6; DO NOT EDIT. +/// Code generated from jsonrpc schema by rpcgen v2.5.x with swift v1.0.0; DO NOT EDIT. import Foundation protocol ArithNetworking { /// CheckError throws error is isErr true. + /// TEST row 2 func arithCheckError(isErr: Bool) async -> RpcError? /// CheckZenRPCError throws zenrpc error is isErr true. + /// Second description row func arithCheckZenRPCError(isErr: Bool) async -> RpcError? /// Divide divides two numbers. func arithDivide(a: Int, b: Int) async -> Result func arithDoSomething() async -> RpcError? - func arithDoSomethingWithPoint(p: ModelPoint) async -> Result - func arithGetPoints() async -> Result<[model.Point], RpcError> + func arithDoSomethingV2() async -> Result + func arithDoSomethingWithPoint(p: Point, pp: [Point]) async -> Result + func arithGetPoints() async -> Result<[Point], RpcError> /// Multiply multiples two digits and returns result. func arithMultiply(a: Int, b: Int) async -> Result /// Pi returns math.Pi. @@ -27,12 +30,14 @@ protocol ArithNetworking { extension Networking: ArithNetworking { /// CheckError throws error is isErr true. + /// TEST row 2 /// - Returns: Result func arithCheckError(isErr: Bool) async -> RpcError? { await request(.arithCheckError(isErr: isErr)) } /// CheckZenRPCError throws zenrpc error is isErr true. + /// Second description row /// - Returns: Result func arithCheckZenRPCError(isErr: Bool) async -> RpcError? { await request(.arithCheckZenRPCError(isErr: isErr)) @@ -49,17 +54,22 @@ extension Networking: ArithNetworking { /// - Returns: Result func arithDoSomething() async -> RpcError? { - await request(.arithDoSomething) + await request(.arithDoSomething()) } - /// - Returns: Result - func arithDoSomethingWithPoint(p: ModelPoint) async -> Result { - await request(.arithDoSomethingWithPoint(p: p)) + /// - Returns: Result + func arithDoSomethingV2() async -> Result { + await request(.arithDoSomethingV2()) } - /// - Returns: Result<[model.Point], RpcError> - func arithGetPoints() async -> Result<[model.Point], RpcError> { - await request(.arithGetPoints) + /// - Returns: Result + func arithDoSomethingWithPoint(p: Point, pp: [Point]) async -> Result { + await request(.arithDoSomethingWithPoint(p: p, pp: pp)) + } + + /// - Returns: Result<[Point], RpcError> + func arithGetPoints() async -> Result<[Point], RpcError> { + await request(.arithGetPoints()) } /// Multiply multiples two digits and returns result. @@ -71,12 +81,12 @@ extension Networking: ArithNetworking { /// Pi returns math.Pi. /// - Returns: Result func arithPi() async -> Result { - await request(.arithPi) + await request(.arithPi()) } /// - Returns: Result func arithPositive() async -> Result { - await request(.arithPositive) + await request(.arithPositive()) } /// Pow returns x**y, the base-x exponential of y. If Exp is not set then default value is 2. @@ -99,27 +109,3 @@ extension Networking: ArithNetworking { await request(.arithSumArray(array: array)) } } - - -protocol CatalogueNetworking { - func catalogueFirst(groups: [Group]) async -> Result - func catalogueSecond(campaigns: [Campaign]) async -> Result - func catalogueThird() async -> Result -} - -extension Networking: CatalogueNetworking { - /// - Returns: Result - func catalogueFirst(groups: [Group]) async -> Result { - await request(.catalogueFirst(groups: groups)) - } - - /// - Returns: Result - func catalogueSecond(campaigns: [Campaign]) async -> Result { - await request(.catalogueSecond(campaigns: campaigns)) - } - - /// - Returns: Result - func catalogueThird() async -> Result { - await request(.catalogueThird) - } -} diff --git a/swift/testdata/rpc.generated.swift b/swift/testdata/rpc.generated.swift index adfa685..adf72a1 100644 --- a/swift/testdata/rpc.generated.swift +++ b/swift/testdata/rpc.generated.swift @@ -1,4 +1,4 @@ -/// Code generated from jsonrpc schema by rpcgen v2.4.5; DO NOT EDIT. +/// Code generated from jsonrpc schema by rpcgen v2.5.x with swift v1.0.0; DO NOT EDIT. import Foundation @@ -6,9 +6,19 @@ extension RPCAPI: RPCMethod { public var rpcMethod: String { switch self { case .batch(let requests): return requests.compactMap { $0.rpcMethod }.joined(separator: ",") - case .catalogueFirst: return "catalogue.First" - case .catalogueSecond: return "catalogue.Second" - case .catalogueThird: return "catalogue.Third" + case .arithCheckError: return "arith.CheckError" + case .arithCheckZenRPCError: return "arith.CheckZenRPCError" + case .arithDivide: return "arith.Divide" + case .arithDoSomething: return "arith.DoSomething" + case .arithDoSomethingV2: return "arith.DoSomethingV2" + case .arithDoSomethingWithPoint: return "arith.DoSomethingWithPoint" + case .arithGetPoints: return "arith.GetPoints" + case .arithMultiply: return "arith.Multiply" + case .arithPi: return "arith.Pi" + case .arithPositive: return "arith.Positive" + case .arithPow: return "arith.Pow" + case .arithSum: return "arith.Sum" + case .arithSumArray: return "arith.SumArray" } } } @@ -18,77 +28,229 @@ extension RPCAPI: RPCParameters { switch self { case .batch: return nil - case let .catalogueFirst(groups): - return ["groups": groups.any] + case let .arithCheckError(isErr, _): + return ["isErr": isErr] - case let .catalogueSecond(campaigns): - return ["campaigns": campaigns.any] + case let .arithCheckZenRPCError(isErr, _): + return ["isErr": isErr] - case .catalogueThird: + case let .arithDivide(a, b, _): + return ["a": a, "b": b] + + case .arithDoSomething: + return nil + + case .arithDoSomethingV2: + return nil + + case let .arithDoSomethingWithPoint(p, pp, _): + return ["p": p.any, "pp": pp.any] + + case .arithGetPoints: + return nil + + case let .arithMultiply(a, b, _): + return ["a": a, "b": b] + + case .arithPi: + return nil + + case .arithPositive: return nil + + case let .arithPow(base, exp, _): + return ["base": base, "exp": exp] + + case let .arithSum(a, b, _): + return ["a": a, "b": b] + + case let .arithSumArray(array, _): + return ["array": array.any] } } } -public enum RPCAPI { +public enum RPCAPI: Codable, Hashable { /// Make batch requests. case batch(requests: [RPCAPI]) + /// CheckError throws error is isErr true. + /// TEST row 2 + case arithCheckError(isErr: Bool, requestId: String? = nil) + /// CheckZenRPCError throws zenrpc error is isErr true. + /// Second description row + case arithCheckZenRPCError(isErr: Bool, requestId: String? = nil) + /// Divide divides two numbers. + /// - Returns: Quotient? + case arithDivide(a: Int, b: Int, requestId: String? = nil) + case arithDoSomething(requestId: String? = nil) + /// - Returns: ExternalData + case arithDoSomethingV2(requestId: String? = nil) + /// - Returns: Point + case arithDoSomethingWithPoint(p: Point, pp: [Point], requestId: String? = nil) + /// - Returns: [Point] + case arithGetPoints(requestId: String? = nil) + /// Multiply multiples two digits and returns result. + /// - Returns: Int + case arithMultiply(a: Int, b: Int, requestId: String? = nil) + /// Pi returns math.Pi. + /// - Returns: Double + case arithPi(requestId: String? = nil) /// - Returns: Bool - case catalogueFirst(groups: [Group]) - + case arithPositive(requestId: String? = nil) + /// Pow returns x**y, the base-x exponential of y. If Exp is not set then default value is 2. + /// - Returns: Double + case arithPow(base: Double, exp: Double?, requestId: String? = nil) + /// Sum sums two digits and returns error with error code as result and IP from context. /// - Returns: Bool - case catalogueSecond(campaigns: [Campaign]) + case arithSum(a: Int, b: Int, requestId: String? = nil) + /// SumArray returns sum all items from array + /// - Returns: Double + case arithSumArray(array: [Double]?, requestId: String? = nil) +} - /// - Returns: Campaign - case catalogueThird +public struct CycleInitStruct: Codable, Hashable { + @DecodableDefault.False + var isCycleInit: Bool + init(isCycleInit: Bool) { + self.isCycleInit = isCycleInit + } } - -public struct Campaign: Codable, Hashable { - @DecodableDefault.EmptyList - var groups: [Group] - @DecodableDefault.IntegerZero - var id: Int - init(groups: [Group], id: Int) { - self.groups = groups - self.id = id +public struct ExternalData: Codable, Hashable { + @DecodableDefault.EmptyString + var name: String + init(name: String) { + self.name = name } } -public struct Group: Codable, Hashable { - var child: Group? - @DecodableDefault.EmptyList - var groups: [Group] +public struct Point: Codable, Hashable { + /// coordinate + @DecodableDefault.IntegerZero + var X: Int + /// coordinate + @DecodableDefault.IntegerZero + var Y: Int + /// version group float - 1 + @DecodableDefault.DoubleZero + var baseFloat: Double + /// version id - 2 + @DecodableDefault.IntegerZero + var baseId: Int + @DecodableDefault.EmptyString + var `class`: String + /// version date - 1 + @DecodableDefault.EmptyString + var createdAt: String + var emptyString: String? + /// version id - 1 @DecodableDefault.IntegerZero var id: Int + /// version group geo coordinate № - 2 + @DecodableDefault.DoubleZero + var lat: Double + /// version group geo coordinate № - 3 + @DecodableDefault.DoubleZero + var latitude: Double + /// version group geo coordinate № - 2 + @DecodableDefault.DoubleZero + var lon: Double + /// version group geo coordinate № - 3 + @DecodableDefault.DoubleZero + var longitude: Double + /// version date - 3 + @DecodableDefault.EmptyString + var manualChangedAt: String + @DecodableDefault.EmptyString + var name: String + /// version group geo coordinate № - 1 + @DecodableDefault.DoubleZero + var newLat: Double + /// version group geo coordinate № - 1 + @DecodableDefault.DoubleZero + var newLon: Double + var nextQuotient: Quotient + /// version group float - 2 + @DecodableDefault.DoubleZero + var secondFloat: Double + /// version id - 3 + @DecodableDefault.IntegerZero + var secondID: Int @DecodableDefault.EmptyList - var nodes: [Group] - var sub: SubGroup + var secondPoints: [Point] + var secondQuotient: Quotient? + /// version date - 2 @DecodableDefault.EmptyString - var title: String - init(child: Group? = nil, groups: [Group], id: Int, nodes: [Group], sub: SubGroup, title: String) { - self.child = child - self.groups = groups + var updatedAt: String + init(X: Int, Y: Int, baseFloat: Double, baseId: Int, class: String, createdAt: String, emptyString: String? = nil, id: Int, lat: Double, latitude: Double, lon: Double, longitude: Double, manualChangedAt: String, name: String, newLat: Double, newLon: Double, nextQuotient: Quotient, secondFloat: Double, secondID: Int, secondPoints: [Point], secondQuotient: Quotient? = nil, updatedAt: String) { + self.X = X + self.Y = Y + self.baseFloat = baseFloat + self.baseId = baseId + self.class = `class` + self.createdAt = createdAt + self.emptyString = emptyString self.id = id - self.nodes = nodes - self.sub = sub - self.title = title + self.lat = lat + self.latitude = latitude + self.lon = lon + self.longitude = longitude + self.manualChangedAt = manualChangedAt + self.name = name + self.newLat = newLat + self.newLon = newLon + self.nextQuotient = nextQuotient + self.secondFloat = secondFloat + self.secondID = secondID + self.secondPoints = secondPoints + self.secondQuotient = secondQuotient + self.updatedAt = updatedAt } } -public struct SubGroup: Codable, Hashable { +public struct Quotient: Codable, Hashable { + /// Quo docs @DecodableDefault.IntegerZero - var id: Int - @DecodableDefault.EmptyList - var nodes: [Group] + var Quo: Int @DecodableDefault.EmptyString - var title: String - init(id: Int, nodes: [Group], title: String) { - self.id = id - self.nodes = nodes - self.title = title + var baseRow: String + var data: CycleInitStruct + /// Rem docs + @DecodableDefault.IntegerZero + var rem: Int + var rowNil: String? + init(Quo: Int, baseRow: String, data: CycleInitStruct, rem: Int, rowNil: String? = nil) { + self.Quo = Quo + self.baseRow = baseRow + self.data = data + self.rem = rem + self.rowNil = rowNil } } + +extension RPCAPI { + public var rpcId: String? { + switch self { + case .batch: + return nil + + case.arithCheckError(_, let requestId), + .arithCheckZenRPCError(_, let requestId), + .arithDivide(_, _, let requestId), + .arithDoSomething(let requestId), + .arithDoSomethingV2(let requestId), + .arithDoSomethingWithPoint(_, _, let requestId), + .arithGetPoints(let requestId), + .arithMultiply(_, _, let requestId), + .arithPi(let requestId), + .arithPositive(let requestId), + .arithPow(_, _, let requestId), + .arithSum(_, _, let requestId), + .arithSumArray(_, let requestId): + return requestId + } + } +} diff --git a/swift/testdata/testdata_zenrpc.go b/swift/testdata/testdata_zenrpc.go new file mode 100644 index 0000000..f6b437b --- /dev/null +++ b/swift/testdata/testdata_zenrpc.go @@ -0,0 +1,1299 @@ +// Code generated by zenrpc v2.2.12; DO NOT EDIT. + +package testdata + +import ( + "context" + "encoding/json" + + "github.com/vmkteam/zenrpc/v2" + "github.com/vmkteam/zenrpc/v2/smd" +) + +var RPC = struct { + ArithService struct{ Sum, Positive, DoSomething, DoSomethingV2, GetPoints, DoSomethingWithPoint, Multiply, CheckError, CheckZenRPCError, Divide, Pow, Pi, SumArray string } +}{ + ArithService: struct{ Sum, Positive, DoSomething, DoSomethingV2, GetPoints, DoSomethingWithPoint, Multiply, CheckError, CheckZenRPCError, Divide, Pow, Pi, SumArray string }{ + Sum: "sum", + Positive: "positive", + DoSomething: "dosomething", + DoSomethingV2: "dosomethingv2", + GetPoints: "getpoints", + DoSomethingWithPoint: "dosomethingwithpoint", + Multiply: "multiply", + CheckError: "checkerror", + CheckZenRPCError: "checkzenrpcerror", + Divide: "divide", + Pow: "pow", + Pi: "pi", + SumArray: "sumarray", + }, +} + +func (ArithService) SMD() smd.ServiceInfo { + return smd.ServiceInfo{ + Methods: map[string]smd.Service{ + "Sum": { + Description: `Sum sums two digits and returns error with error code as result and IP from context.`, + Parameters: []smd.JSONSchema{ + { + Name: "a", + Type: smd.Integer, + }, + { + Name: "b", + Type: smd.Integer, + }, + }, + Returns: smd.JSONSchema{ + Type: smd.Boolean, + }, + }, + "Positive": { + Parameters: []smd.JSONSchema{}, + Returns: smd.JSONSchema{ + Type: smd.Boolean, + }, + }, + "DoSomething": { + Parameters: []smd.JSONSchema{}, + }, + "DoSomethingV2": { + Parameters: []smd.JSONSchema{}, + Returns: smd.JSONSchema{ + Type: smd.Object, + TypeName: "ExternalData", + Properties: smd.PropertyList{ + { + Name: "name", + Type: smd.String, + }, + }, + }, + }, + "GetPoints": { + Parameters: []smd.JSONSchema{}, + Returns: smd.JSONSchema{ + Type: smd.Array, + TypeName: "[]Point", + Items: map[string]string{ + "$ref": "#/definitions/Point", + }, + Definitions: map[string]smd.Definition{ + "Point": { + Type: "object", + Properties: smd.PropertyList{ + { + Name: "X", + Description: `coordinate`, + Type: smd.Integer, + }, + { + Name: "Y", + Description: `coordinate`, + Type: smd.Integer, + }, + { + Name: "id", + Description: `version id - 1`, + Type: smd.Integer, + }, + { + Name: "baseId", + Description: `version id - 2`, + Type: smd.Integer, + }, + { + Name: "secondID", + Description: `version id - 3`, + Type: smd.Integer, + }, + { + Name: "createdAt", + Description: `version date - 1`, + Type: smd.String, + }, + { + Name: "updatedAt", + Description: `version date - 2`, + Type: smd.String, + }, + { + Name: "manualChangedAt", + Description: `version date - 3`, + Type: smd.String, + }, + { + Name: "newLat", + Description: `version group geo coordinate № - 1`, + Type: smd.Float, + }, + { + Name: "newLon", + Description: `version group geo coordinate № - 1`, + Type: smd.Float, + }, + { + Name: "lat", + Description: `version group geo coordinate № - 2`, + Type: smd.Float, + }, + { + Name: "lon", + Description: `version group geo coordinate № - 2`, + Type: smd.Float, + }, + { + Name: "latitude", + Description: `version group geo coordinate № - 3`, + Type: smd.Float, + }, + { + Name: "longitude", + Description: `version group geo coordinate № - 3`, + Type: smd.Float, + }, + { + Name: "baseFloat", + Description: `version group float - 1`, + Type: smd.Float, + }, + { + Name: "secondFloat", + Description: `version group float - 2`, + Type: smd.Float, + }, + { + Name: "emptyString", + Optional: true, + Type: smd.String, + }, + { + Name: "name", + Type: smd.String, + }, + { + Name: "secondPoints", + Type: smd.Array, + Items: map[string]string{ + "$ref": "#/definitions/Point", + }, + }, + { + Name: "nextQuotient", + Ref: "#/definitions/Quotient", + Type: smd.Object, + }, + { + Name: "secondQuotient", + Optional: true, + Ref: "#/definitions/Quotient", + Type: smd.Object, + }, + { + Name: "class", + Type: smd.String, + }, + }, + }, + "Quotient": { + Type: "object", + Properties: smd.PropertyList{ + { + Name: "Quo", + Description: `Quo docs`, + Type: smd.Integer, + }, + { + Name: "rem", + Description: `Rem docs`, + Type: smd.Integer, + }, + { + Name: "baseRow", + Type: smd.String, + }, + { + Name: "rowNil", + Optional: true, + Type: smd.String, + }, + { + Name: "data", + Ref: "#/definitions/CycleInitStruct", + Type: smd.Object, + }, + }, + }, + "CycleInitStruct": { + Type: "object", + Properties: smd.PropertyList{ + { + Name: "isCycleInit", + Type: smd.Boolean, + }, + }, + }, + }, + }, + }, + "DoSomethingWithPoint": { + Parameters: []smd.JSONSchema{ + { + Name: "p", + Type: smd.Object, + TypeName: "Point", + Properties: smd.PropertyList{ + { + Name: "X", + Description: `coordinate`, + Type: smd.Integer, + }, + { + Name: "Y", + Description: `coordinate`, + Type: smd.Integer, + }, + { + Name: "id", + Description: `version id - 1`, + Type: smd.Integer, + }, + { + Name: "baseId", + Description: `version id - 2`, + Type: smd.Integer, + }, + { + Name: "secondID", + Description: `version id - 3`, + Type: smd.Integer, + }, + { + Name: "createdAt", + Description: `version date - 1`, + Type: smd.String, + }, + { + Name: "updatedAt", + Description: `version date - 2`, + Type: smd.String, + }, + { + Name: "manualChangedAt", + Description: `version date - 3`, + Type: smd.String, + }, + { + Name: "newLat", + Description: `version group geo coordinate № - 1`, + Type: smd.Float, + }, + { + Name: "newLon", + Description: `version group geo coordinate № - 1`, + Type: smd.Float, + }, + { + Name: "lat", + Description: `version group geo coordinate № - 2`, + Type: smd.Float, + }, + { + Name: "lon", + Description: `version group geo coordinate № - 2`, + Type: smd.Float, + }, + { + Name: "latitude", + Description: `version group geo coordinate № - 3`, + Type: smd.Float, + }, + { + Name: "longitude", + Description: `version group geo coordinate № - 3`, + Type: smd.Float, + }, + { + Name: "baseFloat", + Description: `version group float - 1`, + Type: smd.Float, + }, + { + Name: "secondFloat", + Description: `version group float - 2`, + Type: smd.Float, + }, + { + Name: "emptyString", + Optional: true, + Type: smd.String, + }, + { + Name: "name", + Type: smd.String, + }, + { + Name: "secondPoints", + Type: smd.Array, + Items: map[string]string{ + "$ref": "#/definitions/Point", + }, + }, + { + Name: "nextQuotient", + Ref: "#/definitions/Quotient", + Type: smd.Object, + }, + { + Name: "secondQuotient", + Optional: true, + Ref: "#/definitions/Quotient", + Type: smd.Object, + }, + { + Name: "class", + Type: smd.String, + }, + }, + Definitions: map[string]smd.Definition{ + "Point": { + Type: "object", + Properties: smd.PropertyList{ + { + Name: "X", + Description: `coordinate`, + Type: smd.Integer, + }, + { + Name: "Y", + Description: `coordinate`, + Type: smd.Integer, + }, + { + Name: "id", + Description: `version id - 1`, + Type: smd.Integer, + }, + { + Name: "baseId", + Description: `version id - 2`, + Type: smd.Integer, + }, + { + Name: "secondID", + Description: `version id - 3`, + Type: smd.Integer, + }, + { + Name: "createdAt", + Description: `version date - 1`, + Type: smd.String, + }, + { + Name: "updatedAt", + Description: `version date - 2`, + Type: smd.String, + }, + { + Name: "manualChangedAt", + Description: `version date - 3`, + Type: smd.String, + }, + { + Name: "newLat", + Description: `version group geo coordinate № - 1`, + Type: smd.Float, + }, + { + Name: "newLon", + Description: `version group geo coordinate № - 1`, + Type: smd.Float, + }, + { + Name: "lat", + Description: `version group geo coordinate № - 2`, + Type: smd.Float, + }, + { + Name: "lon", + Description: `version group geo coordinate № - 2`, + Type: smd.Float, + }, + { + Name: "latitude", + Description: `version group geo coordinate № - 3`, + Type: smd.Float, + }, + { + Name: "longitude", + Description: `version group geo coordinate № - 3`, + Type: smd.Float, + }, + { + Name: "baseFloat", + Description: `version group float - 1`, + Type: smd.Float, + }, + { + Name: "secondFloat", + Description: `version group float - 2`, + Type: smd.Float, + }, + { + Name: "emptyString", + Optional: true, + Type: smd.String, + }, + { + Name: "name", + Type: smd.String, + }, + { + Name: "secondPoints", + Type: smd.Array, + Items: map[string]string{ + "$ref": "#/definitions/Point", + }, + }, + { + Name: "nextQuotient", + Ref: "#/definitions/Quotient", + Type: smd.Object, + }, + { + Name: "secondQuotient", + Optional: true, + Ref: "#/definitions/Quotient", + Type: smd.Object, + }, + { + Name: "class", + Type: smd.String, + }, + }, + }, + "Quotient": { + Type: "object", + Properties: smd.PropertyList{ + { + Name: "Quo", + Description: `Quo docs`, + Type: smd.Integer, + }, + { + Name: "rem", + Description: `Rem docs`, + Type: smd.Integer, + }, + { + Name: "baseRow", + Type: smd.String, + }, + { + Name: "rowNil", + Optional: true, + Type: smd.String, + }, + { + Name: "data", + Ref: "#/definitions/CycleInitStruct", + Type: smd.Object, + }, + }, + }, + "CycleInitStruct": { + Type: "object", + Properties: smd.PropertyList{ + { + Name: "isCycleInit", + Type: smd.Boolean, + }, + }, + }, + }, + }, + { + Name: "pp", + Type: smd.Array, + TypeName: "[]Point", + Items: map[string]string{ + "$ref": "#/definitions/Point", + }, + Definitions: map[string]smd.Definition{ + "Point": { + Type: "object", + Properties: smd.PropertyList{ + { + Name: "X", + Description: `coordinate`, + Type: smd.Integer, + }, + { + Name: "Y", + Description: `coordinate`, + Type: smd.Integer, + }, + { + Name: "id", + Description: `version id - 1`, + Type: smd.Integer, + }, + { + Name: "baseId", + Description: `version id - 2`, + Type: smd.Integer, + }, + { + Name: "secondID", + Description: `version id - 3`, + Type: smd.Integer, + }, + { + Name: "createdAt", + Description: `version date - 1`, + Type: smd.String, + }, + { + Name: "updatedAt", + Description: `version date - 2`, + Type: smd.String, + }, + { + Name: "manualChangedAt", + Description: `version date - 3`, + Type: smd.String, + }, + { + Name: "newLat", + Description: `version group geo coordinate № - 1`, + Type: smd.Float, + }, + { + Name: "newLon", + Description: `version group geo coordinate № - 1`, + Type: smd.Float, + }, + { + Name: "lat", + Description: `version group geo coordinate № - 2`, + Type: smd.Float, + }, + { + Name: "lon", + Description: `version group geo coordinate № - 2`, + Type: smd.Float, + }, + { + Name: "latitude", + Description: `version group geo coordinate № - 3`, + Type: smd.Float, + }, + { + Name: "longitude", + Description: `version group geo coordinate № - 3`, + Type: smd.Float, + }, + { + Name: "baseFloat", + Description: `version group float - 1`, + Type: smd.Float, + }, + { + Name: "secondFloat", + Description: `version group float - 2`, + Type: smd.Float, + }, + { + Name: "emptyString", + Optional: true, + Type: smd.String, + }, + { + Name: "name", + Type: smd.String, + }, + { + Name: "secondPoints", + Type: smd.Array, + Items: map[string]string{ + "$ref": "#/definitions/Point", + }, + }, + { + Name: "nextQuotient", + Ref: "#/definitions/Quotient", + Type: smd.Object, + }, + { + Name: "secondQuotient", + Optional: true, + Ref: "#/definitions/Quotient", + Type: smd.Object, + }, + { + Name: "class", + Type: smd.String, + }, + }, + }, + "Quotient": { + Type: "object", + Properties: smd.PropertyList{ + { + Name: "Quo", + Description: `Quo docs`, + Type: smd.Integer, + }, + { + Name: "rem", + Description: `Rem docs`, + Type: smd.Integer, + }, + { + Name: "baseRow", + Type: smd.String, + }, + { + Name: "rowNil", + Optional: true, + Type: smd.String, + }, + { + Name: "data", + Ref: "#/definitions/CycleInitStruct", + Type: smd.Object, + }, + }, + }, + "CycleInitStruct": { + Type: "object", + Properties: smd.PropertyList{ + { + Name: "isCycleInit", + Type: smd.Boolean, + }, + }, + }, + }, + }, + }, + Returns: smd.JSONSchema{ + Description: `Point test description in return`, + Type: smd.Object, + TypeName: "Point", + Properties: smd.PropertyList{ + { + Name: "X", + Description: `coordinate`, + Type: smd.Integer, + }, + { + Name: "Y", + Description: `coordinate`, + Type: smd.Integer, + }, + { + Name: "id", + Description: `version id - 1`, + Type: smd.Integer, + }, + { + Name: "baseId", + Description: `version id - 2`, + Type: smd.Integer, + }, + { + Name: "secondID", + Description: `version id - 3`, + Type: smd.Integer, + }, + { + Name: "createdAt", + Description: `version date - 1`, + Type: smd.String, + }, + { + Name: "updatedAt", + Description: `version date - 2`, + Type: smd.String, + }, + { + Name: "manualChangedAt", + Description: `version date - 3`, + Type: smd.String, + }, + { + Name: "newLat", + Description: `version group geo coordinate № - 1`, + Type: smd.Float, + }, + { + Name: "newLon", + Description: `version group geo coordinate № - 1`, + Type: smd.Float, + }, + { + Name: "lat", + Description: `version group geo coordinate № - 2`, + Type: smd.Float, + }, + { + Name: "lon", + Description: `version group geo coordinate № - 2`, + Type: smd.Float, + }, + { + Name: "latitude", + Description: `version group geo coordinate № - 3`, + Type: smd.Float, + }, + { + Name: "longitude", + Description: `version group geo coordinate № - 3`, + Type: smd.Float, + }, + { + Name: "baseFloat", + Description: `version group float - 1`, + Type: smd.Float, + }, + { + Name: "secondFloat", + Description: `version group float - 2`, + Type: smd.Float, + }, + { + Name: "emptyString", + Optional: true, + Type: smd.String, + }, + { + Name: "name", + Type: smd.String, + }, + { + Name: "secondPoints", + Type: smd.Array, + Items: map[string]string{ + "$ref": "#/definitions/Point", + }, + }, + { + Name: "nextQuotient", + Ref: "#/definitions/Quotient", + Type: smd.Object, + }, + { + Name: "secondQuotient", + Optional: true, + Ref: "#/definitions/Quotient", + Type: smd.Object, + }, + { + Name: "class", + Type: smd.String, + }, + }, + Definitions: map[string]smd.Definition{ + "Point": { + Type: "object", + Properties: smd.PropertyList{ + { + Name: "X", + Description: `coordinate`, + Type: smd.Integer, + }, + { + Name: "Y", + Description: `coordinate`, + Type: smd.Integer, + }, + { + Name: "id", + Description: `version id - 1`, + Type: smd.Integer, + }, + { + Name: "baseId", + Description: `version id - 2`, + Type: smd.Integer, + }, + { + Name: "secondID", + Description: `version id - 3`, + Type: smd.Integer, + }, + { + Name: "createdAt", + Description: `version date - 1`, + Type: smd.String, + }, + { + Name: "updatedAt", + Description: `version date - 2`, + Type: smd.String, + }, + { + Name: "manualChangedAt", + Description: `version date - 3`, + Type: smd.String, + }, + { + Name: "newLat", + Description: `version group geo coordinate № - 1`, + Type: smd.Float, + }, + { + Name: "newLon", + Description: `version group geo coordinate № - 1`, + Type: smd.Float, + }, + { + Name: "lat", + Description: `version group geo coordinate № - 2`, + Type: smd.Float, + }, + { + Name: "lon", + Description: `version group geo coordinate № - 2`, + Type: smd.Float, + }, + { + Name: "latitude", + Description: `version group geo coordinate № - 3`, + Type: smd.Float, + }, + { + Name: "longitude", + Description: `version group geo coordinate № - 3`, + Type: smd.Float, + }, + { + Name: "baseFloat", + Description: `version group float - 1`, + Type: smd.Float, + }, + { + Name: "secondFloat", + Description: `version group float - 2`, + Type: smd.Float, + }, + { + Name: "emptyString", + Optional: true, + Type: smd.String, + }, + { + Name: "name", + Type: smd.String, + }, + { + Name: "secondPoints", + Type: smd.Array, + Items: map[string]string{ + "$ref": "#/definitions/Point", + }, + }, + { + Name: "nextQuotient", + Ref: "#/definitions/Quotient", + Type: smd.Object, + }, + { + Name: "secondQuotient", + Optional: true, + Ref: "#/definitions/Quotient", + Type: smd.Object, + }, + { + Name: "class", + Type: smd.String, + }, + }, + }, + "Quotient": { + Type: "object", + Properties: smd.PropertyList{ + { + Name: "Quo", + Description: `Quo docs`, + Type: smd.Integer, + }, + { + Name: "rem", + Description: `Rem docs`, + Type: smd.Integer, + }, + { + Name: "baseRow", + Type: smd.String, + }, + { + Name: "rowNil", + Optional: true, + Type: smd.String, + }, + { + Name: "data", + Ref: "#/definitions/CycleInitStruct", + Type: smd.Object, + }, + }, + }, + "CycleInitStruct": { + Type: "object", + Properties: smd.PropertyList{ + { + Name: "isCycleInit", + Type: smd.Boolean, + }, + }, + }, + }, + }, + }, + "Multiply": { + Description: `Multiply multiples two digits and returns result.`, + Parameters: []smd.JSONSchema{ + { + Name: "a", + Type: smd.Integer, + }, + { + Name: "b", + Type: smd.Integer, + }, + }, + Returns: smd.JSONSchema{ + Type: smd.Integer, + }, + }, + "CheckError": { + Description: `CheckError throws error is isErr true. +TEST row 2`, + Parameters: []smd.JSONSchema{ + { + Name: "isErr", + Type: smd.Boolean, + }, + }, + Errors: map[int]string{ + 500: "test error", + }, + }, + "CheckZenRPCError": { + Description: `CheckZenRPCError throws zenrpc error is isErr true. +Second description row`, + Parameters: []smd.JSONSchema{ + { + Name: "isErr", + Type: smd.Boolean, + }, + }, + Errors: map[int]string{ + 500: "test error", + }, + }, + "Divide": { + Description: `Divide divides two numbers.`, + Parameters: []smd.JSONSchema{ + { + Name: "a", + Description: `the a`, + Type: smd.Integer, + }, + { + Name: "b", + Description: `the b`, + Type: smd.Integer, + }, + }, + Returns: smd.JSONSchema{ + Optional: true, + Type: smd.Object, + TypeName: "Quotient", + Properties: smd.PropertyList{ + { + Name: "Quo", + Description: `Quo docs`, + Type: smd.Integer, + }, + { + Name: "rem", + Description: `Rem docs`, + Type: smd.Integer, + }, + { + Name: "baseRow", + Type: smd.String, + }, + { + Name: "rowNil", + Optional: true, + Type: smd.String, + }, + { + Name: "data", + Ref: "#/definitions/CycleInitStruct", + Type: smd.Object, + }, + }, + Definitions: map[string]smd.Definition{ + "CycleInitStruct": { + Type: "object", + Properties: smd.PropertyList{ + { + Name: "isCycleInit", + Type: smd.Boolean, + }, + }, + }, + }, + }, + Errors: map[int]string{ + 401: "we do not serve 1", + }, + }, + "Pow": { + Description: `Pow returns x**y, the base-x exponential of y. If Exp is not set then default value is 2.`, + Parameters: []smd.JSONSchema{ + { + Name: "base", + Type: smd.Float, + }, + { + Name: "exp", + Optional: true, + Description: `exponent could be empty`, + Type: smd.Float, + }, + }, + Returns: smd.JSONSchema{ + Type: smd.Float, + }, + }, + "Pi": { + Description: `Pi returns math.Pi.`, + Parameters: []smd.JSONSchema{}, + Returns: smd.JSONSchema{ + Type: smd.Float, + }, + }, + "SumArray": { + Description: `SumArray returns sum all items from array`, + Parameters: []smd.JSONSchema{ + { + Name: "array", + Optional: true, + Type: smd.Array, + TypeName: "[]", + Items: map[string]string{ + "type": smd.Float, + }, + }, + }, + Returns: smd.JSONSchema{ + Type: smd.Float, + }, + }, + }, + } +} + +// Invoke is as generated code from zenrpc cmd +func (s ArithService) Invoke(ctx context.Context, method string, params json.RawMessage) zenrpc.Response { + resp := zenrpc.Response{} + var err error + + switch method { + case RPC.ArithService.Sum: + var args = struct { + A int `json:"a"` + B int `json:"b"` + }{} + + if zenrpc.IsArray(params) { + if params, err = zenrpc.ConvertToObject([]string{"a", "b"}, params); err != nil { + return zenrpc.NewResponseError(nil, zenrpc.InvalidParams, "", err.Error()) + } + } + + if len(params) > 0 { + if err := json.Unmarshal(params, &args); err != nil { + return zenrpc.NewResponseError(nil, zenrpc.InvalidParams, "", err.Error()) + } + } + + resp.Set(s.Sum(ctx, args.A, args.B)) + + case RPC.ArithService.Positive: + resp.Set(s.Positive()) + + case RPC.ArithService.DoSomething: + s.DoSomething() + + case RPC.ArithService.DoSomethingV2: + resp.Set(s.DoSomethingV2()) + + case RPC.ArithService.GetPoints: + resp.Set(s.GetPoints()) + + case RPC.ArithService.DoSomethingWithPoint: + var args = struct { + P Point `json:"p"` + Pp []Point `json:"pp"` + }{} + + if zenrpc.IsArray(params) { + if params, err = zenrpc.ConvertToObject([]string{"p", "pp"}, params); err != nil { + return zenrpc.NewResponseError(nil, zenrpc.InvalidParams, "", err.Error()) + } + } + + if len(params) > 0 { + if err := json.Unmarshal(params, &args); err != nil { + return zenrpc.NewResponseError(nil, zenrpc.InvalidParams, "", err.Error()) + } + } + + resp.Set(s.DoSomethingWithPoint(args.P, args.Pp)) + + case RPC.ArithService.Multiply: + var args = struct { + A int `json:"a"` + B int `json:"b"` + }{} + + if zenrpc.IsArray(params) { + if params, err = zenrpc.ConvertToObject([]string{"a", "b"}, params); err != nil { + return zenrpc.NewResponseError(nil, zenrpc.InvalidParams, "", err.Error()) + } + } + + if len(params) > 0 { + if err := json.Unmarshal(params, &args); err != nil { + return zenrpc.NewResponseError(nil, zenrpc.InvalidParams, "", err.Error()) + } + } + + resp.Set(s.Multiply(args.A, args.B)) + + case RPC.ArithService.CheckError: + var args = struct { + IsErr bool `json:"isErr"` + }{} + + if zenrpc.IsArray(params) { + if params, err = zenrpc.ConvertToObject([]string{"isErr"}, params); err != nil { + return zenrpc.NewResponseError(nil, zenrpc.InvalidParams, "", err.Error()) + } + } + + if len(params) > 0 { + if err := json.Unmarshal(params, &args); err != nil { + return zenrpc.NewResponseError(nil, zenrpc.InvalidParams, "", err.Error()) + } + } + + resp.Set(s.CheckError(args.IsErr)) + + case RPC.ArithService.CheckZenRPCError: + var args = struct { + IsErr bool `json:"isErr"` + }{} + + if zenrpc.IsArray(params) { + if params, err = zenrpc.ConvertToObject([]string{"isErr"}, params); err != nil { + return zenrpc.NewResponseError(nil, zenrpc.InvalidParams, "", err.Error()) + } + } + + if len(params) > 0 { + if err := json.Unmarshal(params, &args); err != nil { + return zenrpc.NewResponseError(nil, zenrpc.InvalidParams, "", err.Error()) + } + } + + resp.Set(s.CheckZenRPCError(args.IsErr)) + + case RPC.ArithService.Divide: + var args = struct { + A int `json:"a"` + B int `json:"b"` + }{} + + if zenrpc.IsArray(params) { + if params, err = zenrpc.ConvertToObject([]string{"a", "b"}, params); err != nil { + return zenrpc.NewResponseError(nil, zenrpc.InvalidParams, "", err.Error()) + } + } + + if len(params) > 0 { + if err := json.Unmarshal(params, &args); err != nil { + return zenrpc.NewResponseError(nil, zenrpc.InvalidParams, "", err.Error()) + } + } + + resp.Set(s.Divide(args.A, args.B)) + + case RPC.ArithService.Pow: + var args = struct { + Base float64 `json:"base"` + Exp *float64 `json:"exp"` + }{} + + if zenrpc.IsArray(params) { + if params, err = zenrpc.ConvertToObject([]string{"base", "exp"}, params); err != nil { + return zenrpc.NewResponseError(nil, zenrpc.InvalidParams, "", err.Error()) + } + } + + if len(params) > 0 { + if err := json.Unmarshal(params, &args); err != nil { + return zenrpc.NewResponseError(nil, zenrpc.InvalidParams, "", err.Error()) + } + } + + //zenrpc:exp=2 exponent could be empty + if args.Exp == nil { + var v float64 = 2 + args.Exp = &v + } + + resp.Set(s.Pow(args.Base, args.Exp)) + + case RPC.ArithService.Pi: + resp.Set(s.Pi()) + + case RPC.ArithService.SumArray: + var args = struct { + Array *[]float64 `json:"array"` + }{} + + if zenrpc.IsArray(params) { + if params, err = zenrpc.ConvertToObject([]string{"array"}, params); err != nil { + return zenrpc.NewResponseError(nil, zenrpc.InvalidParams, "", err.Error()) + } + } + + if len(params) > 0 { + if err := json.Unmarshal(params, &args); err != nil { + return zenrpc.NewResponseError(nil, zenrpc.InvalidParams, "", err.Error()) + } + } + + //zenrpc:array=[]float64{1,2,4} + if args.Array == nil { + var v []float64 = []float64{1, 2, 4} + args.Array = &v + } + + resp.Set(s.SumArray(args.Array)) + + default: + resp = zenrpc.NewResponseError(nil, zenrpc.MethodNotFound, "", nil) + } + + return resp +} diff --git a/typescript/rpcgen_test.go b/typescript/rpcgen_test.go index 988a996..7b5e1ba 100644 --- a/typescript/rpcgen_test.go +++ b/typescript/rpcgen_test.go @@ -2,6 +2,7 @@ package typescript import ( "bytes" + "flag" "os" "testing" @@ -9,6 +10,14 @@ import ( "github.com/vmkteam/zenrpc/v2/testdata" ) +const ( + clientTS = "./testdata/catalogue_client.ts" + classes = "./testdata/catalogue_with_classes.ts" + typeOnly = "./testdata/catalogue_with_types_only.ts" +) + +var update = flag.Bool("update", false, "update .ts files") + func TestGenerateTypeScriptClient(t *testing.T) { rpc := zenrpc.NewServer(zenrpc.Options{}) rpc.Register("catalogue", testdata.CatalogueService{}) @@ -20,7 +29,20 @@ func TestGenerateTypeScriptClient(t *testing.T) { t.Fatalf("generate typescript client: %v", err) } - testData, err := os.ReadFile("./testdata/catalogue_client.ts") + if *update { + var f *os.File + f, err = os.Create(clientTS) + if err != nil { + t.Fatal(err) + } + _, err = f.Write(generated) + if err != nil { + t.Fatal(err) + } + return + } + + testData, err := os.ReadFile(clientTS) if err != nil { t.Fatalf("open test data file: %v", err) } @@ -45,7 +67,20 @@ func TestGenerateTypeScriptClasses(t *testing.T) { t.Fatalf("generate typescript client: %v", err) } - testData, err := os.ReadFile("./testdata/catalogue_with_classes.ts") + if *update { + var f *os.File + f, err = os.Create(classes) + if err != nil { + t.Fatal(err) + } + _, err = f.Write(generated) + if err != nil { + t.Fatal(err) + } + return + } + + testData, err := os.ReadFile(classes) if err != nil { t.Fatalf("open test data file: %v", err) } @@ -70,7 +105,20 @@ func TestGenerateTypeScriptTypesOnly(t *testing.T) { t.Fatalf("generate typescript client: %v", err) } - testData, err := os.ReadFile("./testdata/catalogue_with_types_only.ts") + if *update { + var f *os.File + f, err = os.Create(typeOnly) + if err != nil { + t.Fatal(err) + } + _, err = f.Write(generated) + if err != nil { + t.Fatal(err) + } + return + } + + testData, err := os.ReadFile(typeOnly) if err != nil { t.Fatalf("open test data file: %v", err) } diff --git a/typescript/testdata/catalogue_client.ts b/typescript/testdata/catalogue_client.ts index 16b2207..1b4614b 100644 --- a/typescript/testdata/catalogue_client.ts +++ b/typescript/testdata/catalogue_client.ts @@ -1,4 +1,4 @@ -/* Code generated from jsonrpc schema by rpcgen v2.4.0; DO NOT EDIT. */ +/* Code generated from jsonrpc schema by rpcgen v2.5.x with typescript v1.0.0; DO NOT EDIT. */ /* eslint-disable */ export interface ICampaign { id: number, diff --git a/typescript/testdata/catalogue_with_classes.ts b/typescript/testdata/catalogue_with_classes.ts index c3ae51b..adf1c56 100755 --- a/typescript/testdata/catalogue_with_classes.ts +++ b/typescript/testdata/catalogue_with_classes.ts @@ -1,4 +1,4 @@ -/* Code generated from jsonrpc schema by rpcgen v2.4.0; DO NOT EDIT. */ +/* Code generated from jsonrpc schema by rpcgen v2.5.x with typescript v1.0.0; DO NOT EDIT. */ /* eslint-disable */ export interface ICampaign { id: number, diff --git a/typescript/testdata/catalogue_with_types_only.ts b/typescript/testdata/catalogue_with_types_only.ts index f03f0ed..5cdc864 100755 --- a/typescript/testdata/catalogue_with_types_only.ts +++ b/typescript/testdata/catalogue_with_types_only.ts @@ -1,4 +1,4 @@ -/* Code generated from jsonrpc schema by rpcgen v2.4.0; DO NOT EDIT. */ +/* Code generated from jsonrpc schema by rpcgen v2.5.x with typescript v1.0.0; DO NOT EDIT. */ /* eslint-disable */ export interface ICampaign { id: number, diff --git a/typescript/typescript_client.go b/typescript/typescript_client.go index 63426e4..09cfb61 100644 --- a/typescript/typescript_client.go +++ b/typescript/typescript_client.go @@ -18,6 +18,7 @@ const ( voidResponse = "void" viewOps = "viewOps" numberType = "number" + version = "1.0.0" ) type Generator struct { @@ -42,7 +43,7 @@ type TypeMapper func(in smd.JSONSchema, tsType Type) Type // Generate returns generate TypeScript client func (g *Generator) Generate() ([]byte, error) { tsModels := g.tsModels() - tsModels.GeneratorData = gen.DefaultGeneratorData() + tsModels.GeneratorData = gen.DefaultGeneratorData().AddLangAndLocalVersion(version, "typescript") var fns = template.FuncMap{ "len": func(a interface{}) int { diff --git a/typescript/typescript_template.go b/typescript/typescript_template.go index 971425e..f7765a9 100644 --- a/typescript/typescript_template.go +++ b/typescript/typescript_template.go @@ -1,6 +1,6 @@ package typescript -const client = `/* Code generated from jsonrpc schema by rpcgen v{{ .Version }}; DO NOT EDIT. */ +const client = `/* Code generated from jsonrpc schema by rpcgen v{{ .Version }} with {{ .Lang }} v{{ .LocalVersion }}; DO NOT EDIT. */ /* eslint-disable */ {{- range .Interfaces }} export interface {{ .Name }} {