feat: extend ts typing to support string literals

This commit is contained in:
franklin 2021-04-27 14:12:24 +02:00
parent 821de9c715
commit 73f60cc932
23 changed files with 455 additions and 259 deletions

View File

@ -112,7 +112,7 @@ func Build(conf *config.Config, goPath string) {
goPaths = append(goPaths, vendorDirectory)
}
pkgName, services, structs, scalars, constants, err := Read(goPaths, conf.Module, packageName, target.Services)
pkgName, services, structs, scalars, constants, constantTypes, err := Read(goPaths, conf.Module, packageName, target.Services)
if err != nil {
fmt.Fprintln(os.Stderr, "\t an error occured while trying to understand your code: ", err)
@ -140,7 +140,7 @@ func Build(conf *config.Config, goPath string) {
os.Exit(3)
}
err = renderTypescriptStructsToPackages(conf.ModuleKind, structs, conf.Mappings, constants, scalars, mappedTypeScript)
err = renderTypescriptStructsToPackages(conf.ModuleKind, structs, conf.Mappings, constants, constantTypes, scalars, mappedTypeScript)
if err != nil {
fmt.Fprintln(os.Stderr, "struct gen err for target", name, err)
os.Exit(4)

View File

@ -1,5 +1,37 @@
/* eslint:disable */
var GoTSRPC;
(function (GoTSRPC) {
var Demo;
(function (Demo) {
// constants from github.com/foomo/gotsrpc/demo
Demo.GoConst = {
CustomTypeIntOne: 1,
CustomTypeIntThree: 3,
CustomTypeIntTwo: 2,
CustomTypeStringOne: "one",
CustomTypeStringThree: "three",
CustomTypeStringTwo: "two"
};
})(Demo = GoTSRPC.Demo || (GoTSRPC.Demo = {}));
})(GoTSRPC || (GoTSRPC = {}));
/* eslint:disable */
var GoTSRPC;
(function (GoTSRPC) {
var Demo;
(function (Demo) {
var Nested;
(function (Nested) {
// constants from github.com/foomo/gotsrpc/demo/nested
Nested.GoConst = {
CustomTypeNestedOne: "one",
CustomTypeNestedThree: "three",
CustomTypeNestedTwo: "two"
};
})(Nested = Demo.Nested || (Demo.Nested = {}));
})(Demo = GoTSRPC.Demo || (GoTSRPC.Demo = {}));
})(GoTSRPC || (GoTSRPC = {}));
/* eslint:disable */
var GoTSRPC;
(function (GoTSRPC) {
GoTSRPC.call = function (endPoint, method, args, success, err) {
var request = new XMLHttpRequest();
@ -92,14 +124,8 @@ var GoTSRPC;
this.endPoint = endPoint;
this.transport = transport;
}
BarClient.prototype.hello = function (number, success, err) {
this.transport(this.endPoint, "Hello", [number], success, err);
};
BarClient.prototype.inheritance = function (inner, nested, inline, success, err) {
this.transport(this.endPoint, "Inheritance", [inner, nested, inline], success, err);
};
BarClient.prototype.repeat = function (one, two, success, err) {
this.transport(this.endPoint, "Repeat", [one, two], success, err);
BarClient.prototype.customType = function (customTypeInt, customTypeString, CustomTypeStruct, success, err) {
this.transport(this.endPoint, "CustomType", [customTypeInt, customTypeString, CustomTypeStruct], success, err);
};
BarClient.defaultInst = new BarClient;
return BarClient;

View File

@ -1,5 +1,27 @@
package demo
import (
"github.com/foomo/gotsrpc/demo/nested"
)
type (
CustomTypeInt int
CustomTypeString string
CustomTypeFoo string
)
const (
CustomTypeIntOne CustomTypeInt = 1
CustomTypeIntTwo CustomTypeInt = 2
CustomTypeIntThree CustomTypeInt = 3
)
const (
CustomTypeStringOne CustomTypeString = "one"
CustomTypeStringTwo CustomTypeString = "two"
CustomTypeStringThree CustomTypeString = "three"
)
type (
Inner struct {
One string `json:"one"`
@ -12,10 +34,21 @@ type (
Inner `json:",inline"`
Two string `json:"two"`
}
CustomTypeStruct struct {
CustomTypeFoo CustomTypeFoo
CustomTypeInt CustomTypeInt
CustomTypeString CustomTypeString
CustomTypeNested nested.CustomTypeNested
Check Check
}
//Check struct {
// Foo string
//}
)
type Bar interface {
Hello(number int64) int
Repeat(one, two string) (three, four bool)
Inheritance(inner Inner, nested OuterNested, inline OuterInline) (Inner, OuterNested, OuterInline)
//Hello(w http.ResponseWriter, r *http.Request, number int64) int
//Repeat(one, two string) (three, four bool)
//Inheritance(inner Inner, nested OuterNested, inline OuterInline) (Inner, OuterNested, OuterInline)
CustomType(customTypeInt CustomTypeInt, customTypeString CustomTypeString, CustomTypeStruct CustomTypeStruct) (*CustomTypeInt, *CustomTypeString, CustomTypeStruct)
}

7
demo/bar_vo.go Normal file
View File

@ -0,0 +1,7 @@
package demo
type (
Check struct {
Foo string
}
)

View File

@ -294,41 +294,21 @@ type (
callStatsHandler gotsrpc.GoRPCCallStatsHandlerFun
}
BarHelloRequest struct {
Number int64
BarCustomTypeRequest struct {
CustomTypeInt CustomTypeInt
CustomTypeString CustomTypeString
CustomTypeStruct CustomTypeStruct
}
BarHelloResponse struct {
RetHello_0 int
}
BarInheritanceRequest struct {
Inner Inner
Nested OuterNested
Inline OuterInline
}
BarInheritanceResponse struct {
RetInheritance_0 Inner
RetInheritance_1 OuterNested
RetInheritance_2 OuterInline
}
BarRepeatRequest struct {
One string
Two string
}
BarRepeatResponse struct {
Three bool
Four bool
BarCustomTypeResponse struct {
RetCustomType_0 *CustomTypeInt
RetCustomType_1 *CustomTypeString
RetCustomType_2 CustomTypeStruct
}
)
func init() {
gob.Register(BarHelloRequest{})
gob.Register(BarHelloResponse{})
gob.Register(BarInheritanceRequest{})
gob.Register(BarInheritanceResponse{})
gob.Register(BarRepeatRequest{})
gob.Register(BarRepeatResponse{})
gob.Register(BarCustomTypeRequest{})
gob.Register(BarCustomTypeResponse{})
}
func NewBarGoRPCProxy(addr string, service Bar, tlsConfig *tls.Config) *BarGoRPCProxy {
@ -369,18 +349,10 @@ func (p *BarGoRPCProxy) handler(clientAddr string, request interface{}) (respons
funcName := funcNameParts[len(funcNameParts)-1]
switch funcName {
case "BarHelloRequest":
req := request.(BarHelloRequest)
retHello_0 := p.service.Hello(req.Number)
response = BarHelloResponse{RetHello_0: retHello_0}
case "BarInheritanceRequest":
req := request.(BarInheritanceRequest)
retInheritance_0, retInheritance_1, retInheritance_2 := p.service.Inheritance(req.Inner, req.Nested, req.Inline)
response = BarInheritanceResponse{RetInheritance_0: retInheritance_0, RetInheritance_1: retInheritance_1, RetInheritance_2: retInheritance_2}
case "BarRepeatRequest":
req := request.(BarRepeatRequest)
three, four := p.service.Repeat(req.One, req.Two)
response = BarRepeatResponse{Three: three, Four: four}
case "BarCustomTypeRequest":
req := request.(BarCustomTypeRequest)
retCustomType_0, retCustomType_1, retCustomType_2 := p.service.CustomType(req.CustomTypeInt, req.CustomTypeString, req.CustomTypeStruct)
response = BarCustomTypeResponse{RetCustomType_0: retCustomType_0, RetCustomType_1: retCustomType_1, RetCustomType_2: retCustomType_2}
default:
fmt.Println("Unkown request type", reflect.TypeOf(request).String())
}

View File

@ -195,35 +195,13 @@ func (tsc *BarGoRPCClient) Stop() {
tsc.Client.Stop()
}
func (tsc *BarGoRPCClient) Hello(number int64) (retHello_0 int, clientErr error) {
req := BarHelloRequest{Number: number}
func (tsc *BarGoRPCClient) CustomType(customTypeInt CustomTypeInt, customTypeString CustomTypeString, CustomTypeStruct CustomTypeStruct) (retCustomType_0 *CustomTypeInt, retCustomType_1 *CustomTypeString, retCustomType_2 CustomTypeStruct, clientErr error) {
req := BarCustomTypeRequest{CustomTypeInt: customTypeInt, CustomTypeString: customTypeString, CustomTypeStruct: CustomTypeStruct}
rpcCallRes, rpcCallErr := tsc.Client.Call(req)
if rpcCallErr != nil {
clientErr = rpcCallErr
return
}
response := rpcCallRes.(BarHelloResponse)
return response.RetHello_0, nil
}
func (tsc *BarGoRPCClient) Inheritance(inner Inner, nested OuterNested, inline OuterInline) (retInheritance_0 Inner, retInheritance_1 OuterNested, retInheritance_2 OuterInline, clientErr error) {
req := BarInheritanceRequest{Inner: inner, Nested: nested, Inline: inline}
rpcCallRes, rpcCallErr := tsc.Client.Call(req)
if rpcCallErr != nil {
clientErr = rpcCallErr
return
}
response := rpcCallRes.(BarInheritanceResponse)
return response.RetInheritance_0, response.RetInheritance_1, response.RetInheritance_2, nil
}
func (tsc *BarGoRPCClient) Repeat(one string, two string) (three bool, four bool, clientErr error) {
req := BarRepeatRequest{One: one, Two: two}
rpcCallRes, rpcCallErr := tsc.Client.Call(req)
if rpcCallErr != nil {
clientErr = rpcCallErr
return
}
response := rpcCallRes.(BarRepeatResponse)
return response.Three, response.Four, nil
response := rpcCallRes.(BarCustomTypeResponse)
return response.RetCustomType_0, response.RetCustomType_1, response.RetCustomType_2, nil
}

View File

@ -314,59 +314,24 @@ func (p *BarGoTSRPCProxy) ServeHTTP(w http.ResponseWriter, r *http.Request) {
callStats.Service = "Bar"
}
switch funcName {
case "Hello":
case "CustomType":
var (
arg_number int64
arg_customTypeInt CustomTypeInt
arg_customTypeString CustomTypeString
arg_CustomTypeStruct CustomTypeStruct
)
args = []interface{}{&arg_number}
args = []interface{}{&arg_customTypeInt, &arg_customTypeString, &arg_CustomTypeStruct}
err := gotsrpc.LoadArgs(&args, callStats, r)
if err != nil {
gotsrpc.ErrorCouldNotLoadArgs(w)
return
}
executionStart := time.Now()
helloRet := p.service.Hello(arg_number)
customTypeRet, customTypeRet_1, customTypeRet_2 := p.service.CustomType(arg_customTypeInt, arg_customTypeString, arg_CustomTypeStruct)
if callStats != nil {
callStats.Execution = time.Now().Sub(executionStart)
}
gotsrpc.Reply([]interface{}{helloRet}, callStats, r, w)
return
case "Inheritance":
var (
arg_inner Inner
arg_nested OuterNested
arg_inline OuterInline
)
args = []interface{}{&arg_inner, &arg_nested, &arg_inline}
err := gotsrpc.LoadArgs(&args, callStats, r)
if err != nil {
gotsrpc.ErrorCouldNotLoadArgs(w)
return
}
executionStart := time.Now()
inheritanceRet, inheritanceRet_1, inheritanceRet_2 := p.service.Inheritance(arg_inner, arg_nested, arg_inline)
if callStats != nil {
callStats.Execution = time.Now().Sub(executionStart)
}
gotsrpc.Reply([]interface{}{inheritanceRet, inheritanceRet_1, inheritanceRet_2}, callStats, r, w)
return
case "Repeat":
var (
arg_one string
arg_two string
)
args = []interface{}{&arg_one, &arg_two}
err := gotsrpc.LoadArgs(&args, callStats, r)
if err != nil {
gotsrpc.ErrorCouldNotLoadArgs(w)
return
}
executionStart := time.Now()
repeatThree, repeatFour := p.service.Repeat(arg_one, arg_two)
if callStats != nil {
callStats.Execution = time.Now().Sub(executionStart)
}
gotsrpc.Reply([]interface{}{repeatThree, repeatFour}, callStats, r, w)
gotsrpc.Reply([]interface{}{customTypeRet, customTypeRet_1, customTypeRet_2}, callStats, r, w)
return
default:
gotsrpc.ClearStats(r)

View File

@ -146,9 +146,7 @@ func (tsc *HTTPDemoGoTSRPCClient) TestScalarInPlace() (retTestScalarInPlace_0 Sc
}
type BarGoTSRPCClient interface {
Hello(number int64) (retHello_0 int, clientErr error)
Inheritance(inner Inner, nested OuterNested, inline OuterInline) (retInheritance_0 Inner, retInheritance_1 OuterNested, retInheritance_2 OuterInline, clientErr error)
Repeat(one string, two string) (three bool, four bool, clientErr error)
CustomType(customTypeInt CustomTypeInt, customTypeString CustomTypeString, CustomTypeStruct CustomTypeStruct) (retCustomType_0 *CustomTypeInt, retCustomType_1 *CustomTypeString, retCustomType_2 CustomTypeStruct, clientErr error)
}
type HTTPBarGoTSRPCClient struct {
@ -172,23 +170,9 @@ func NewBarGoTSRPCClientWithClient(url string, endpoint string, client *net_http
Client: gotsrpc.NewClientWithHttpClient(client),
}
}
func (tsc *HTTPBarGoTSRPCClient) Hello(number int64) (retHello_0 int, clientErr error) {
args := []interface{}{number}
reply := []interface{}{&retHello_0}
clientErr = tsc.Client.Call(tsc.URL, tsc.EndPoint, "Hello", args, reply)
return
}
func (tsc *HTTPBarGoTSRPCClient) Inheritance(inner Inner, nested OuterNested, inline OuterInline) (retInheritance_0 Inner, retInheritance_1 OuterNested, retInheritance_2 OuterInline, clientErr error) {
args := []interface{}{inner, nested, inline}
reply := []interface{}{&retInheritance_0, &retInheritance_1, &retInheritance_2}
clientErr = tsc.Client.Call(tsc.URL, tsc.EndPoint, "Inheritance", args, reply)
return
}
func (tsc *HTTPBarGoTSRPCClient) Repeat(one string, two string) (three bool, four bool, clientErr error) {
args := []interface{}{one, two}
reply := []interface{}{&three, &four}
clientErr = tsc.Client.Call(tsc.URL, tsc.EndPoint, "Repeat", args, reply)
func (tsc *HTTPBarGoTSRPCClient) CustomType(customTypeInt CustomTypeInt, customTypeString CustomTypeString, CustomTypeStruct CustomTypeStruct) (retCustomType_0 *CustomTypeInt, retCustomType_1 *CustomTypeString, retCustomType_2 CustomTypeStruct, clientErr error) {
args := []interface{}{customTypeInt, customTypeString, CustomTypeStruct}
reply := []interface{}{&retCustomType_0, &retCustomType_1, &retCustomType_2}
clientErr = tsc.Client.Call(tsc.URL, tsc.EndPoint, "CustomType", args, reply)
return
}

View File

@ -1,5 +1,13 @@
package nested
type CustomTypeNested string
const (
CustomTypeNestedOne CustomTypeNested = "one"
CustomTypeNestedTwo CustomTypeNested = "two"
CustomTypeNestedThree CustomTypeNested = "three"
)
type Nested struct {
Name string
Any Any

View File

@ -17,19 +17,18 @@ export class DemoClient {
constructor(
public transport:<T>(method: string, data?: any[]) => Promise<T>
) {}
async any(any:any, anyList:any[], anyMap:{[index:string]:any}):Promise<{ret:any; ret_1:any[]; ret_2:{[index:string]:any}}> {
let response = await this.transport<{0:any; 1:any[]; 2:{[index:string]:any}}>("Any", [any, anyList, anyMap])
async any(any:github_com_foomo_gotsrpc_demo_nested.Any, anyList:github_com_foomo_gotsrpc_demo_nested.Any[], anyMap:{[index:string]:github_com_foomo_gotsrpc_demo_nested.Any}):Promise<{ret:github_com_foomo_gotsrpc_demo_nested.Any; ret_1:github_com_foomo_gotsrpc_demo_nested.Any[]; ret_2:{[index:string]:github_com_foomo_gotsrpc_demo_nested.Any}}> {
let response = await this.transport<{0:github_com_foomo_gotsrpc_demo_nested.Any; 1:github_com_foomo_gotsrpc_demo_nested.Any[]; 2:{[index:string]:github_com_foomo_gotsrpc_demo_nested.Any}}>("Any", [any, anyList, anyMap])
let responseObject = {ret : response[0], ret_1 : response[1], ret_2 : response[2]};
return responseObject;
}
async extractAddress(person:github_com_foomo_gotsrpc_demo.Person):Promise<github_com_foomo_gotsrpc_demo.Address> {
async extractAddress(person:github_com_foomo_gotsrpc_demo.Person):Promise<{addr:github_com_foomo_gotsrpc_demo.Address; e:github_com_foomo_gotsrpc_demo.Err}> {
let response = await this.transport<{0:github_com_foomo_gotsrpc_demo.Address; 1:github_com_foomo_gotsrpc_demo.Err}>("ExtractAddress", [person])
let err = response[1];
if(err) { throw err }
return response[0]
let responseObject = {addr : response[0], e : response[1]};
return responseObject;
}
async giveMeAScalar():Promise<{amount:number; wahr:boolean; hier:string}> {
let response = await this.transport<{0:number; 1:boolean; 2:string}>("GiveMeAScalar", [])
async giveMeAScalar():Promise<{amount:github_com_foomo_gotsrpc_demo_nested.Amount; wahr:github_com_foomo_gotsrpc_demo_nested.True; hier:github_com_foomo_gotsrpc_demo.ScalarInPlace}> {
let response = await this.transport<{0:github_com_foomo_gotsrpc_demo_nested.Amount; 1:github_com_foomo_gotsrpc_demo_nested.True; 2:github_com_foomo_gotsrpc_demo.ScalarInPlace}>("GiveMeAScalar", [])
let responseObject = {amount : response[0], wahr : response[1], hier : response[2]};
return responseObject;
}
@ -45,8 +44,8 @@ export class DemoClient {
async helloNumberMaps(intMap:{[index:number]:string}):Promise<{[index:number]:string}> {
return (await this.transport<{0:{[index:number]:string}}>("HelloNumberMaps", [intMap]))[0]
}
async helloScalarError():Promise<string> {
return (await this.transport<{0:string}>("HelloScalarError", []))[0]
async helloScalarError():Promise<github_com_foomo_gotsrpc_demo.ScalarError> {
return (await this.transport<{0:github_com_foomo_gotsrpc_demo.ScalarError}>("HelloScalarError", []))[0]
}
async mapCrap():Promise<{[index:string]:number[]}> {
return (await this.transport<{0:{[index:string]:number[]}}>("MapCrap", []))[0]
@ -54,8 +53,8 @@ export class DemoClient {
async nest():Promise<github_com_foomo_gotsrpc_demo_nested.Nested[]> {
return (await this.transport<{0:github_com_foomo_gotsrpc_demo_nested.Nested[]}>("Nest", []))[0]
}
async testScalarInPlace():Promise<string> {
return (await this.transport<{0:string}>("TestScalarInPlace", []))[0]
async testScalarInPlace():Promise<github_com_foomo_gotsrpc_demo.ScalarInPlace> {
return (await this.transport<{0:github_com_foomo_gotsrpc_demo.ScalarInPlace}>("TestScalarInPlace", []))[0]
}
}
export class BarClient {
@ -63,17 +62,9 @@ export class BarClient {
constructor(
public transport:<T>(method: string, data?: any[]) => Promise<T>
) {}
async hello(number:number):Promise<number> {
return (await this.transport<{0:number}>("Hello", [number]))[0]
}
async inheritance(inner:github_com_foomo_gotsrpc_demo.Inner, nested:github_com_foomo_gotsrpc_demo.OuterNested, inline:github_com_foomo_gotsrpc_demo.OuterInline):Promise<{ret:github_com_foomo_gotsrpc_demo.Inner; ret_1:github_com_foomo_gotsrpc_demo.OuterNested; ret_2:github_com_foomo_gotsrpc_demo.OuterInline}> {
let response = await this.transport<{0:github_com_foomo_gotsrpc_demo.Inner; 1:github_com_foomo_gotsrpc_demo.OuterNested; 2:github_com_foomo_gotsrpc_demo.OuterInline}>("Inheritance", [inner, nested, inline])
async customType(customTypeInt:github_com_foomo_gotsrpc_demo.CustomTypeInt, customTypeString:github_com_foomo_gotsrpc_demo.CustomTypeString, CustomTypeStruct:github_com_foomo_gotsrpc_demo.CustomTypeStruct):Promise<{ret:github_com_foomo_gotsrpc_demo.CustomTypeInt; ret_1:github_com_foomo_gotsrpc_demo.CustomTypeString; ret_2:github_com_foomo_gotsrpc_demo.CustomTypeStruct}> {
let response = await this.transport<{0:github_com_foomo_gotsrpc_demo.CustomTypeInt; 1:github_com_foomo_gotsrpc_demo.CustomTypeString; 2:github_com_foomo_gotsrpc_demo.CustomTypeStruct}>("CustomType", [customTypeInt, customTypeString, CustomTypeStruct])
let responseObject = {ret : response[0], ret_1 : response[1], ret_2 : response[2]};
return responseObject;
}
async repeat(one:string, two:string):Promise<{three:boolean; four:boolean}> {
let response = await this.transport<{0:boolean; 1:boolean}>("Repeat", [one, two])
let responseObject = {three : response[0], four : response[1]};
return responseObject;
}
}

View File

@ -2,6 +2,12 @@
// hello commonjs - we need some imports - sorted in alphabetical order, by go package
import * as github_com_foomo_gotsrpc_demo from './demo'; // demo/output-commonjs-async/demo-nested.ts to demo/output-commonjs-async/demo.ts
import * as github_com_foomo_gotsrpc_demo_nested from './demo-nested'; // demo/output-commonjs-async/demo-nested.ts to demo/output-commonjs-async/demo-nested.ts
// github.com/foomo/gotsrpc/demo/nested.Amount
export type Amount = number
// github.com/foomo/gotsrpc/demo/nested.Any
export type Any = any
// github.com/foomo/gotsrpc/demo/nested.CustomTypeNested
export type CustomTypeNested = "one" | "two" | "three"
// github.com/foomo/gotsrpc/demo/nested.Nested
export interface Nested {
Name:string;
@ -15,4 +21,12 @@ export interface Nested {
Bla:string;
};
}
// github.com/foomo/gotsrpc/demo/nested.True
export type True = boolean
// constants from github.com/foomo/gotsrpc/demo/nested
export const GoConst = {
CustomTypeNestedOne : "one",
CustomTypeNestedThree : "three",
CustomTypeNestedTwo : "two",
}
// end of common js

View File

@ -14,24 +14,30 @@ export interface Address {
NestedPtr?:github_com_foomo_gotsrpc_demo_nested.Nested;
NestedStruct:github_com_foomo_gotsrpc_demo_nested.Nested;
}
// github.com/foomo/gotsrpc/demo.Bar
export type Bar = any
// github.com/foomo/gotsrpc/demo.Check
export interface Check {
Foo:string;
}
// github.com/foomo/gotsrpc/demo.CustomTypeFoo
export type CustomTypeFoo = string
// github.com/foomo/gotsrpc/demo.CustomTypeInt
export type CustomTypeInt = 1 | 2 | 3
// github.com/foomo/gotsrpc/demo.CustomTypeString
export type CustomTypeString = "one" | "two" | "three"
// github.com/foomo/gotsrpc/demo.CustomTypeStruct
export interface CustomTypeStruct {
CustomTypeFoo:github_com_foomo_gotsrpc_demo.CustomTypeFoo;
CustomTypeInt:github_com_foomo_gotsrpc_demo.CustomTypeInt;
CustomTypeString:github_com_foomo_gotsrpc_demo.CustomTypeString;
CustomTypeNested:github_com_foomo_gotsrpc_demo_nested.CustomTypeNested;
Check:github_com_foomo_gotsrpc_demo.Check;
}
// github.com/foomo/gotsrpc/demo.Err
export interface Err {
message:string;
}
// github.com/foomo/gotsrpc/demo.Inner
export interface Inner {
one:string;
}
// github.com/foomo/gotsrpc/demo.OuterInline
export interface OuterInline {
one:string;
two:string;
}
// github.com/foomo/gotsrpc/demo.OuterNested
export interface OuterNested {
inner:github_com_foomo_gotsrpc_demo.Inner;
two:string;
}
// github.com/foomo/gotsrpc/demo.Person
export interface Person {
Name:string;
@ -46,4 +52,17 @@ export interface Person {
};
DNA:string;
}
// github.com/foomo/gotsrpc/demo.ScalarError
export type ScalarError = string
// github.com/foomo/gotsrpc/demo.ScalarInPlace
export type ScalarInPlace = string
// constants from github.com/foomo/gotsrpc/demo
export const GoConst = {
CustomTypeIntOne : 1,
CustomTypeIntThree : 3,
CustomTypeIntTwo : 2,
CustomTypeStringOne : "one",
CustomTypeStringThree : "three",
CustomTypeStringTwo : "two",
}
// end of common js

View File

@ -11,13 +11,13 @@ export class FooClient {
}
export class DemoClient {
constructor(public endPoint:string = "/service/demo", public transport:(endPoint:string, method:string, args:any[], success:any, err:any) => void) { }
any(any:any, anyList:any[], anyMap:{[index:string]:any}, success:(ret:any, ret_1:any[], ret_2:{[index:string]:any}) => void, err:(request:XMLHttpRequest, e?:Error) => void) {
any(any:github_com_foomo_gotsrpc_demo_nested.Any, anyList:github_com_foomo_gotsrpc_demo_nested.Any[], anyMap:{[index:string]:github_com_foomo_gotsrpc_demo_nested.Any}, success:(ret:github_com_foomo_gotsrpc_demo_nested.Any, ret_1:github_com_foomo_gotsrpc_demo_nested.Any[], ret_2:{[index:string]:github_com_foomo_gotsrpc_demo_nested.Any}) => void, err:(request:XMLHttpRequest, e?:Error) => void) {
this.transport(this.endPoint, "Any", [any, anyList, anyMap], success, err);
}
extractAddress(person:github_com_foomo_gotsrpc_demo.Person, success:(addr:github_com_foomo_gotsrpc_demo.Address, e:github_com_foomo_gotsrpc_demo.Err) => void, err:(request:XMLHttpRequest, e?:Error) => void) {
this.transport(this.endPoint, "ExtractAddress", [person], success, err);
}
giveMeAScalar(success:(amount:number, wahr:boolean, hier:string) => void, err:(request:XMLHttpRequest, e?:Error) => void) {
giveMeAScalar(success:(amount:github_com_foomo_gotsrpc_demo_nested.Amount, wahr:github_com_foomo_gotsrpc_demo_nested.True, hier:github_com_foomo_gotsrpc_demo.ScalarInPlace) => void, err:(request:XMLHttpRequest, e?:Error) => void) {
this.transport(this.endPoint, "GiveMeAScalar", [], success, err);
}
hello(name:string, success:(ret:string, ret_1:github_com_foomo_gotsrpc_demo.Err) => void, err:(request:XMLHttpRequest, e?:Error) => void) {
@ -29,7 +29,7 @@ export class DemoClient {
helloNumberMaps(intMap:{[index:number]:string}, success:(floatMap:{[index:number]:string}) => void, err:(request:XMLHttpRequest, e?:Error) => void) {
this.transport(this.endPoint, "HelloNumberMaps", [intMap], success, err);
}
helloScalarError(success:(err:string) => void, err:(request:XMLHttpRequest, e?:Error) => void) {
helloScalarError(success:(err:github_com_foomo_gotsrpc_demo.ScalarError) => void, err:(request:XMLHttpRequest, e?:Error) => void) {
this.transport(this.endPoint, "HelloScalarError", [], success, err);
}
mapCrap(success:(crap:{[index:string]:number[]}) => void, err:(request:XMLHttpRequest, e?:Error) => void) {
@ -38,19 +38,13 @@ export class DemoClient {
nest(success:(ret:github_com_foomo_gotsrpc_demo_nested.Nested[]) => void, err:(request:XMLHttpRequest, e?:Error) => void) {
this.transport(this.endPoint, "Nest", [], success, err);
}
testScalarInPlace(success:(ret:string) => void, err:(request:XMLHttpRequest, e?:Error) => void) {
testScalarInPlace(success:(ret:github_com_foomo_gotsrpc_demo.ScalarInPlace) => void, err:(request:XMLHttpRequest, e?:Error) => void) {
this.transport(this.endPoint, "TestScalarInPlace", [], success, err);
}
}
export class BarClient {
constructor(public endPoint:string = "/service/bar", public transport:(endPoint:string, method:string, args:any[], success:any, err:any) => void) { }
hello(number:number, success:(ret:number) => void, err:(request:XMLHttpRequest, e?:Error) => void) {
this.transport(this.endPoint, "Hello", [number], success, err);
}
inheritance(inner:github_com_foomo_gotsrpc_demo.Inner, nested:github_com_foomo_gotsrpc_demo.OuterNested, inline:github_com_foomo_gotsrpc_demo.OuterInline, success:(ret:github_com_foomo_gotsrpc_demo.Inner, ret_1:github_com_foomo_gotsrpc_demo.OuterNested, ret_2:github_com_foomo_gotsrpc_demo.OuterInline) => void, err:(request:XMLHttpRequest, e?:Error) => void) {
this.transport(this.endPoint, "Inheritance", [inner, nested, inline], success, err);
}
repeat(one:string, two:string, success:(three:boolean, four:boolean) => void, err:(request:XMLHttpRequest, e?:Error) => void) {
this.transport(this.endPoint, "Repeat", [one, two], success, err);
customType(customTypeInt:github_com_foomo_gotsrpc_demo.CustomTypeInt, customTypeString:github_com_foomo_gotsrpc_demo.CustomTypeString, CustomTypeStruct:github_com_foomo_gotsrpc_demo.CustomTypeStruct, success:(ret:github_com_foomo_gotsrpc_demo.CustomTypeInt, ret_1:github_com_foomo_gotsrpc_demo.CustomTypeString, ret_2:github_com_foomo_gotsrpc_demo.CustomTypeStruct) => void, err:(request:XMLHttpRequest, e?:Error) => void) {
this.transport(this.endPoint, "CustomType", [customTypeInt, customTypeString, CustomTypeStruct], success, err);
}
}

View File

@ -2,6 +2,12 @@
// hello commonjs - we need some imports - sorted in alphabetical order, by go package
import * as github_com_foomo_gotsrpc_demo from './demo'; // demo/output-commonjs/demo-nested.ts to demo/output-commonjs/demo.ts
import * as github_com_foomo_gotsrpc_demo_nested from './demo-nested'; // demo/output-commonjs/demo-nested.ts to demo/output-commonjs/demo-nested.ts
// github.com/foomo/gotsrpc/demo/nested.Amount
export type Amount = number
// github.com/foomo/gotsrpc/demo/nested.Any
export type Any = any
// github.com/foomo/gotsrpc/demo/nested.CustomTypeNested
export type CustomTypeNested = "one" | "two" | "three"
// github.com/foomo/gotsrpc/demo/nested.Nested
export interface Nested {
Name:string;
@ -15,4 +21,12 @@ export interface Nested {
Bla:string;
};
}
// github.com/foomo/gotsrpc/demo/nested.True
export type True = boolean
// constants from github.com/foomo/gotsrpc/demo/nested
export const GoConst = {
CustomTypeNestedOne : "one",
CustomTypeNestedThree : "three",
CustomTypeNestedTwo : "two",
}
// end of common js

View File

@ -14,24 +14,30 @@ export interface Address {
NestedPtr?:github_com_foomo_gotsrpc_demo_nested.Nested;
NestedStruct:github_com_foomo_gotsrpc_demo_nested.Nested;
}
// github.com/foomo/gotsrpc/demo.Bar
export type Bar = any
// github.com/foomo/gotsrpc/demo.Check
export interface Check {
Foo:string;
}
// github.com/foomo/gotsrpc/demo.CustomTypeFoo
export type CustomTypeFoo = string
// github.com/foomo/gotsrpc/demo.CustomTypeInt
export type CustomTypeInt = 1 | 2 | 3
// github.com/foomo/gotsrpc/demo.CustomTypeString
export type CustomTypeString = "one" | "two" | "three"
// github.com/foomo/gotsrpc/demo.CustomTypeStruct
export interface CustomTypeStruct {
CustomTypeFoo:github_com_foomo_gotsrpc_demo.CustomTypeFoo;
CustomTypeInt:github_com_foomo_gotsrpc_demo.CustomTypeInt;
CustomTypeString:github_com_foomo_gotsrpc_demo.CustomTypeString;
CustomTypeNested:github_com_foomo_gotsrpc_demo_nested.CustomTypeNested;
Check:github_com_foomo_gotsrpc_demo.Check;
}
// github.com/foomo/gotsrpc/demo.Err
export interface Err {
message:string;
}
// github.com/foomo/gotsrpc/demo.Inner
export interface Inner {
one:string;
}
// github.com/foomo/gotsrpc/demo.OuterInline
export interface OuterInline {
one:string;
two:string;
}
// github.com/foomo/gotsrpc/demo.OuterNested
export interface OuterNested {
inner:github_com_foomo_gotsrpc_demo.Inner;
two:string;
}
// github.com/foomo/gotsrpc/demo.Person
export interface Person {
Name:string;
@ -46,4 +52,17 @@ export interface Person {
};
DNA:string;
}
// github.com/foomo/gotsrpc/demo.ScalarError
export type ScalarError = string
// github.com/foomo/gotsrpc/demo.ScalarInPlace
export type ScalarInPlace = string
// constants from github.com/foomo/gotsrpc/demo
export const GoConst = {
CustomTypeIntOne : 1,
CustomTypeIntThree : 3,
CustomTypeIntTwo : 2,
CustomTypeStringOne : "one",
CustomTypeStringThree : "three",
CustomTypeStringTwo : "two",
}
// end of common js

View File

@ -36,13 +36,13 @@ module GoTSRPC.Demo {
export class DemoClient {
static defaultInst = new DemoClient;
constructor(public endPoint:string = "/service/demo", public transport = GoTSRPC.call) { }
any(any:any, anyList:any[], anyMap:{[index:string]:any}, success:(ret:any, ret_1:any[], ret_2:{[index:string]:any}) => void, err:(request:XMLHttpRequest, e?:Error) => void) {
any(any:GoTSRPC.Demo.Nested.Any, anyList:GoTSRPC.Demo.Nested.Any[], anyMap:{[index:string]:GoTSRPC.Demo.Nested.Any}, success:(ret:GoTSRPC.Demo.Nested.Any, ret_1:GoTSRPC.Demo.Nested.Any[], ret_2:{[index:string]:GoTSRPC.Demo.Nested.Any}) => void, err:(request:XMLHttpRequest, e?:Error) => void) {
this.transport(this.endPoint, "Any", [any, anyList, anyMap], success, err);
}
extractAddress(person:GoTSRPC.Demo.Person, success:(addr:GoTSRPC.Demo.Address, e:GoTSRPC.Demo.Err) => void, err:(request:XMLHttpRequest, e?:Error) => void) {
this.transport(this.endPoint, "ExtractAddress", [person], success, err);
}
giveMeAScalar(success:(amount:number, wahr:boolean, hier:string) => void, err:(request:XMLHttpRequest, e?:Error) => void) {
giveMeAScalar(success:(amount:GoTSRPC.Demo.Nested.Amount, wahr:GoTSRPC.Demo.Nested.True, hier:GoTSRPC.Demo.ScalarInPlace) => void, err:(request:XMLHttpRequest, e?:Error) => void) {
this.transport(this.endPoint, "GiveMeAScalar", [], success, err);
}
hello(name:string, success:(ret:string, ret_1:GoTSRPC.Demo.Err) => void, err:(request:XMLHttpRequest, e?:Error) => void) {
@ -54,7 +54,7 @@ module GoTSRPC.Demo {
helloNumberMaps(intMap:{[index:number]:string}, success:(floatMap:{[index:number]:string}) => void, err:(request:XMLHttpRequest, e?:Error) => void) {
this.transport(this.endPoint, "HelloNumberMaps", [intMap], success, err);
}
helloScalarError(success:(err:string) => void, err:(request:XMLHttpRequest, e?:Error) => void) {
helloScalarError(success:(err:GoTSRPC.Demo.ScalarError) => void, err:(request:XMLHttpRequest, e?:Error) => void) {
this.transport(this.endPoint, "HelloScalarError", [], success, err);
}
mapCrap(success:(crap:{[index:string]:number[]}) => void, err:(request:XMLHttpRequest, e?:Error) => void) {
@ -63,21 +63,15 @@ module GoTSRPC.Demo {
nest(success:(ret:GoTSRPC.Demo.Nested.Nested[]) => void, err:(request:XMLHttpRequest, e?:Error) => void) {
this.transport(this.endPoint, "Nest", [], success, err);
}
testScalarInPlace(success:(ret:string) => void, err:(request:XMLHttpRequest, e?:Error) => void) {
testScalarInPlace(success:(ret:GoTSRPC.Demo.ScalarInPlace) => void, err:(request:XMLHttpRequest, e?:Error) => void) {
this.transport(this.endPoint, "TestScalarInPlace", [], success, err);
}
}
export class BarClient {
static defaultInst = new BarClient;
constructor(public endPoint:string = "/service/bar", public transport = GoTSRPC.call) { }
hello(number:number, success:(ret:number) => void, err:(request:XMLHttpRequest, e?:Error) => void) {
this.transport(this.endPoint, "Hello", [number], success, err);
}
inheritance(inner:GoTSRPC.Demo.Inner, nested:GoTSRPC.Demo.OuterNested, inline:GoTSRPC.Demo.OuterInline, success:(ret:GoTSRPC.Demo.Inner, ret_1:GoTSRPC.Demo.OuterNested, ret_2:GoTSRPC.Demo.OuterInline) => void, err:(request:XMLHttpRequest, e?:Error) => void) {
this.transport(this.endPoint, "Inheritance", [inner, nested, inline], success, err);
}
repeat(one:string, two:string, success:(three:boolean, four:boolean) => void, err:(request:XMLHttpRequest, e?:Error) => void) {
this.transport(this.endPoint, "Repeat", [one, two], success, err);
customType(customTypeInt:GoTSRPC.Demo.CustomTypeInt, customTypeString:GoTSRPC.Demo.CustomTypeString, CustomTypeStruct:GoTSRPC.Demo.CustomTypeStruct, success:(ret:GoTSRPC.Demo.CustomTypeInt, ret_1:GoTSRPC.Demo.CustomTypeString, ret_2:GoTSRPC.Demo.CustomTypeStruct) => void, err:(request:XMLHttpRequest, e?:Error) => void) {
this.transport(this.endPoint, "CustomType", [customTypeInt, customTypeString, CustomTypeStruct], success, err);
}
}
}

View File

@ -1,5 +1,11 @@
/* eslint:disable */
module GoTSRPC.Demo.Nested {
// github.com/foomo/gotsrpc/demo/nested.Amount
export type Amount = number
// github.com/foomo/gotsrpc/demo/nested.Any
export type Any = any
// github.com/foomo/gotsrpc/demo/nested.CustomTypeNested
export type CustomTypeNested = "one" | "two" | "three"
// github.com/foomo/gotsrpc/demo/nested.Nested
export interface Nested {
Name:string;
@ -13,4 +19,12 @@ module GoTSRPC.Demo.Nested {
Bla:string;
};
}
// github.com/foomo/gotsrpc/demo/nested.True
export type True = boolean
// constants from github.com/foomo/gotsrpc/demo/nested
export const GoConst = {
CustomTypeNestedOne : "one",
CustomTypeNestedThree : "three",
CustomTypeNestedTwo : "two",
}
}

View File

@ -12,24 +12,30 @@ module GoTSRPC.Demo {
NestedPtr?:GoTSRPC.Demo.Nested.Nested;
NestedStruct:GoTSRPC.Demo.Nested.Nested;
}
// github.com/foomo/gotsrpc/demo.Bar
export type Bar = any
// github.com/foomo/gotsrpc/demo.Check
export interface Check {
Foo:string;
}
// github.com/foomo/gotsrpc/demo.CustomTypeFoo
export type CustomTypeFoo = string
// github.com/foomo/gotsrpc/demo.CustomTypeInt
export type CustomTypeInt = 1 | 2 | 3
// github.com/foomo/gotsrpc/demo.CustomTypeString
export type CustomTypeString = "one" | "two" | "three"
// github.com/foomo/gotsrpc/demo.CustomTypeStruct
export interface CustomTypeStruct {
CustomTypeFoo:GoTSRPC.Demo.CustomTypeFoo;
CustomTypeInt:GoTSRPC.Demo.CustomTypeInt;
CustomTypeString:GoTSRPC.Demo.CustomTypeString;
CustomTypeNested:GoTSRPC.Demo.Nested.CustomTypeNested;
Check:GoTSRPC.Demo.Check;
}
// github.com/foomo/gotsrpc/demo.Err
export interface Err {
message:string;
}
// github.com/foomo/gotsrpc/demo.Inner
export interface Inner {
one:string;
}
// github.com/foomo/gotsrpc/demo.OuterInline
export interface OuterInline {
one:string;
two:string;
}
// github.com/foomo/gotsrpc/demo.OuterNested
export interface OuterNested {
inner:GoTSRPC.Demo.Inner;
two:string;
}
// github.com/foomo/gotsrpc/demo.Person
export interface Person {
Name:string;
@ -44,4 +50,17 @@ module GoTSRPC.Demo {
};
DNA:string;
}
// github.com/foomo/gotsrpc/demo.ScalarError
export type ScalarError = string
// github.com/foomo/gotsrpc/demo.ScalarInPlace
export type ScalarInPlace = string
// constants from github.com/foomo/gotsrpc/demo
export const GoConst = {
CustomTypeIntOne : 1,
CustomTypeIntThree : 3,
CustomTypeIntTwo : 2,
CustomTypeStringOne : "one",
CustomTypeStringThree : "three",
CustomTypeStringTwo : "two",
}
}

19
go.go
View File

@ -8,11 +8,13 @@ import (
)
func (v *Value) isHTTPResponseWriter() bool {
return v.StructType != nil && v.StructType.Name == "ResponseWriter" && v.StructType.Package == "net/http"
return (v.StructType != nil && v.StructType.Name == "ResponseWriter" && v.StructType.Package == "net/http") ||
(v.Scalar != nil && v.Scalar.Name == "ResponseWriter" && v.Scalar.Package == "net/http")
}
func (v *Value) isHTTPRequest() bool {
return v.IsPtr && v.StructType != nil && v.StructType.Name == "Request" && v.StructType.Package == "net/http"
return (v.IsPtr && v.StructType != nil && v.StructType.Name == "Request" && v.StructType.Package == "net/http") ||
(v.IsPtr && v.Scalar != nil && v.Scalar.Name == "Request" && v.Scalar.Package == "net/http")
}
func (v *Value) goType(aliases map[string]string, packageName string) (t string) {
@ -32,11 +34,10 @@ func (v *Value) goType(aliases map[string]string, packageName string) (t string)
case v.Map != nil:
t += `map[` + v.Map.KeyGoType + `]` + v.Map.Value.goType(aliases, packageName)
case v.Scalar != nil:
// TODO this is a hack to retrieve string types
if packageName != v.Scalar.Package {
if packageName != v.Scalar.Package && aliases[v.Scalar.Package] != "" {
t += aliases[v.Scalar.Package] + "."
}
t += v.Scalar.Name[len(v.Scalar.Package)+1:]
t += v.Scalar.Name
case v.IsInterface:
t += "interface{}"
default:
@ -109,6 +110,12 @@ func (v *Value) emptyLiteral(aliases map[string]string) (e string) {
e += alias + "."
}
e += v.StructType.Name + "{}"
case v.Scalar != nil:
alias := aliases[v.Scalar.Package]
if alias != "" {
e += alias + "."
}
e += v.Scalar.Name + "{}"
case v.IsInterface:
e += "interface{}{}"
}
@ -164,6 +171,8 @@ func extractImports(fields []*Field, fullPackageName string, aliases map[string]
extractImport(f.Value.StructType.Package)
} else if f.Value.Array != nil && f.Value.Array.Value.StructType != nil {
extractImport(f.Value.Array.Value.StructType.Package)
} else if f.Value.Array != nil && f.Value.Array.Value.Scalar != nil {
extractImport(f.Value.Array.Value.Scalar.Package)
} else if f.Value.Scalar != nil {
extractImport(f.Value.Scalar.Package)
}

View File

@ -106,3 +106,11 @@ type Scalar struct {
Package string
Type ScalarType
}
func (st *Scalar) FullName() string {
fullName := st.Package + "." + st.Name
if len(fullName) == 0 {
fullName = st.Name
}
return fullName
}

View File

@ -225,6 +225,73 @@ func loadConstants(pkg *ast.Package) map[string]*ast.BasicLit {
}
}
return constants
}
func loadConstantTypes(pkg *ast.Package) map[string]interface{} {
constants := map[string]interface{}{}
for _, file := range pkg.Files {
for _, decl := range file.Decls {
if reflect.ValueOf(decl).Type().String() == "*ast.GenDecl" {
genDecl := decl.(*ast.GenDecl)
switch genDecl.Tok {
case token.TYPE:
trace("got a type", genDecl.Specs)
for _, spec := range genDecl.Specs {
if reflect.ValueOf(spec).Type().String() == "*ast.TypeSpec" {
spec := spec.(*ast.TypeSpec)
if _, ok := constants[spec.Name.Name]; ok {
continue
}
switch reflect.ValueOf(spec.Type).Type().String() {
case "*ast.InterfaceType":
constants[spec.Name.Name] = "any"
case "*ast.Ident":
specIdent := spec.Type.(*ast.Ident)
switch specIdent.Name {
case "byte":
constants[spec.Name.Name] = "any"
case "string":
constants[spec.Name.Name] = "string"
case "bool":
constants[spec.Name.Name] = "boolean"
case "float", "float32", "float64",
"int", "int8", "int16", "int32", "int64",
"uint", "uint8", "uint16", "uint32", "uint64":
constants[spec.Name.Name] = "number"
default:
trace("unhandled type", reflect.ValueOf(spec.Type).Type().String())
}
default:
trace("ignoring type", reflect.ValueOf(spec.Type).Type().String())
}
}
}
case token.CONST:
trace("got a const", genDecl.Specs)
for _, spec := range genDecl.Specs {
if reflect.ValueOf(spec).Type().String() == "*ast.ValueSpec" {
spec := spec.(*ast.ValueSpec)
if specType, ok := spec.Type.(*ast.Ident); ok {
for _, val := range spec.Values {
if reflect.ValueOf(val).Type().String() == "*ast.BasicLit" {
firstValueLit := val.(*ast.BasicLit)
var values []*ast.BasicLit
if value, ok := constants[specType.Name]; ok {
if v, ok := value.([]*ast.BasicLit); ok {
values = v
}
}
constants[specType.Name] = append(values, firstValueLit)
}
}
}
}
}
}
}
}
}
return constants
}
@ -239,6 +306,7 @@ func Read(
structs map[string]*Struct,
scalars map[string]*Scalar,
constants map[string]map[string]*ast.BasicLit,
constantTypes map[string]map[string]interface{},
err error,
) {
if len(serviceMap) == 0 {
@ -297,6 +365,22 @@ func Read(
}
}
}
constantTypes = map[string]map[string]interface{}{}
for _, structDef := range structs {
if structDef != nil {
structPackage := structDef.Package
_, ok := constantTypes[structPackage]
if !ok {
// fmt.Println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>", structPackage)
pkg, constPkgErr := parsePackage(goPaths, gomod, structPackage)
if constPkgErr != nil {
err = constPkgErr
return
}
constantTypes[structPackage] = loadConstantTypes(pkg)
}
}
}
// fix arg and return field lists
for _, service := range services {
@ -375,7 +459,7 @@ func collectTypes(goPaths []string, gomod config.Namespace, missingTypes map[str
}
}
trace("found scalars in", goPaths, packageName)
for scalarName, scalar := range parsedPackageScalars {
for scalarName, scalar := range packageScalars {
trace(" scalar", scalarName, scalar)
}
traceData(parsedPackageScalars)
@ -469,6 +553,12 @@ func (s *Struct) DepsSatisfied(missingTypes map[string]bool, structs map[string]
fieldStructType = field.Value.Array.Value.StructType
} else if field.Value.Map != nil && field.Value.Map.Value.StructType != nil {
fieldStructType = field.Value.Map.Value.StructType
} else if field.Value.Scalar != nil && needsWork(field.Value.Scalar.FullName()) {
return false
} else if field.Value.Array != nil && field.Value.Array.Value.Scalar != nil && needsWork(field.Value.Array.Value.Scalar.FullName()) {
return false
} else if field.Value.Map != nil && field.Value.Map.Value.Scalar != nil && needsWork(field.Value.Map.Value.Scalar.FullName()) {
return false
}
if fieldStructType != nil {
if needsWork(fieldStructType.FullName()) {
@ -563,7 +653,12 @@ func collectScalarTypes(fields []*Field, scalarTypes map[string]bool) {
if len(scalarType.Package) == 0 {
fullName = scalarType.Name
}
scalarTypes[fullName] = true
switch fullName {
case "error", "net/http.Request", "net/http.ResponseWriter":
continue
default:
scalarTypes[fullName] = true
}
}
}
}

View File

@ -123,9 +123,10 @@ func getScalarFromAstIdent(ident *ast.Ident) ScalarType {
if ident.Obj != nil && ident.Obj.Decl != nil && reflect.ValueOf(ident.Obj.Decl).Type().String() == "*ast.TypeSpec" {
typeSpec := ident.Obj.Decl.(*ast.TypeSpec)
if reflect.ValueOf(typeSpec.Type).Type().String() == "*ast.Ident" {
return getScalarFromAstIdent(typeSpec.Type.(*ast.Ident))
return ScalarType(ident.Name) //getScalarFromAstIdent(typeSpec.Type.(*ast.Ident))
}
} else if ident.Obj == nil {
return ScalarType(ident.Name)
}
return ScalarTypeNone
}
@ -140,29 +141,23 @@ func getTypesFromAstType(ident *ast.Ident) (structType string, scalarType Scalar
return
}
func readAstType(v *Value, fieldIdent *ast.Ident, fileImports fileImportSpecMap) {
func readAstType(v *Value, fieldIdent *ast.Ident, fileImports fileImportSpecMap, packageName string) {
structType, scalarType := getTypesFromAstType(fieldIdent)
v.ScalarType = scalarType
if len(structType) > 0 {
v.StructType = &StructType{
Name: structType,
Package: fileImports.getPackagePath(""),
Package: fileImports.getPackagePath(packageName),
}
} else if fieldIdent.Name[:1] == strings.ToUpper(fieldIdent.Name[:1]) {
v.Scalar = &Scalar{
Package: fileImports.getPackagePath(packageName),
Name: fieldIdent.Name,
Type: scalarType,
}
} else {
v.GoScalarType = fieldIdent.Name
if fieldIdent.Obj != nil && fieldIdent.Obj.Decl != nil && reflect.ValueOf(fieldIdent.Obj.Decl).Type().String() == "*ast.TypeSpec" {
//typeSpec := fieldIdent.Obj.Decl.(*ast.TypeSpec)
//fmt.Println("-------------------------------------->", fieldIdent.Name, reflect.ValueOf(typeSpec.Type).Type())
v.Scalar = &Scalar{
Package: fileImports.getPackagePath(""),
Name: fieldIdent.Name,
Type: scalarType,
}
//jsonDump(v)
}
}
//
}
func readAstStarExpr(v *Value, starExpr *ast.StarExpr, fileImports fileImportSpecMap) {
@ -170,7 +165,7 @@ func readAstStarExpr(v *Value, starExpr *ast.StarExpr, fileImports fileImportSpe
switch reflect.ValueOf(starExpr.X).Type().String() {
case "*ast.Ident":
ident := starExpr.X.(*ast.Ident)
readAstType(v, ident, fileImports)
readAstType(v, ident, fileImports, "")
case "*ast.StructType":
// nested anonymous
readAstStructType(v, starExpr.X.(*ast.StructType), fileImports)
@ -222,7 +217,8 @@ func readAstSelectorExpr(v *Value, selectorExpr *ast.SelectorExpr, fileImports f
// that could be the package name
//selectorIdent := selectorExpr.X.(*ast.Ident)
// fmt.Println(selectorExpr, selectorExpr.X.(*ast.Ident))
readAstType(v, selectorExpr.X.(*ast.Ident), fileImports)
//readAstType(v, selectorExpr.X.(*ast.Ident), fileImports)
readAstType(v, selectorExpr.Sel, fileImports, selectorExpr.X.(*ast.Ident).Name)
if v.StructType != nil {
v.StructType.Package = fileImports.getPackagePath(v.StructType.Name)
v.StructType.Name = selectorExpr.Sel.Name
@ -256,7 +252,7 @@ func (v *Value) loadExpr(expr ast.Expr, fileImports fileImportSpecMap) {
//readAstArrayType(v.Array.Value, fieldArray.Elt.(*ast.ArrayType), fileImports)
v.Array.Value.loadExpr(fieldArray.Elt.(*ast.ArrayType), fileImports)
case "*ast.Ident":
readAstType(v.Array.Value, fieldArray.Elt.(*ast.Ident), fileImports)
readAstType(v.Array.Value, fieldArray.Elt.(*ast.Ident), fileImports, "")
case "*ast.StarExpr":
readAstStarExpr(v.Array.Value, fieldArray.Elt.(*ast.StarExpr), fileImports)
case "*ast.MapType":
@ -275,7 +271,7 @@ func (v *Value) loadExpr(expr ast.Expr, fileImports fileImportSpecMap) {
}
case "*ast.Ident":
fieldIdent := expr.(*ast.Ident)
readAstType(v, fieldIdent, fileImports)
readAstType(v, fieldIdent, fileImports, "")
case "*ast.StarExpr":
// a pointer on sth
readAstStarExpr(v, expr.(*ast.StarExpr), fileImports)

View File

@ -35,6 +35,15 @@ func (v *Value) tsType(mappings config.TypeScriptMappings, scalars map[string]*S
ts.app("[]")
}
case v.Scalar != nil:
if v.Scalar.Package != "" {
mapping, ok := mappings[v.Scalar.Package]
var tsModule string
if ok {
tsModule = mapping.TypeScriptModule
}
ts.app(tsModule + "." + tsTypeFromScalarType(v.ScalarType))
return
}
ts.app(tsTypeFromScalarType(v.Scalar.Type))
case v.StructType != nil:
if v.StructType.Package != "" {
@ -138,6 +147,7 @@ func renderTypescriptStructsToPackages(
structs map[string]*Struct,
mappings config.TypeScriptMappings,
constants map[string]map[string]*ast.BasicLit,
constantTypes map[string]map[string]interface{},
scalarTypes map[string]*Scalar,
mappedTypeScript map[string]map[string]*code,
) (err error) {
@ -165,6 +175,33 @@ func renderTypescriptStructsToPackages(
return
}
}
for packageName, packageConstantTypes := range constantTypes {
if len(packageConstantTypes) > 0 {
packageCodeMap, ok := codeMap[packageName]
if !ok {
err = errors.New("missing code mapping for go package : " + packageName + " => you have to add a mapping from this go package to a TypeScript module in your build-config.yml in the mappings section")
return
}
for packageConstantTypeName, packageConstantTypeValues := range packageConstantTypes {
packageCodeMap[packageConstantTypeName] = newCode(" ")
if !(moduleKind == config.ModuleKindCommonJS) {
packageCodeMap[packageConstantTypeName].ind(1)
}
packageCodeMap[packageConstantTypeName].l("// " + packageName + "." + packageConstantTypeName)
if packageConstantTypeValuesList, ok := packageConstantTypeValues.([]*ast.BasicLit); ok {
var values []string
for _, packageConstantTypeValue := range packageConstantTypeValuesList {
values = append(values, packageConstantTypeValue.Value)
}
packageCodeMap[packageConstantTypeName].l("export type " + packageConstantTypeName + " = " + strings.Join(values, " | "))
} else if packageConstantTypeValuesString, ok := packageConstantTypeValues.(string); ok {
packageCodeMap[packageConstantTypeName].l("export type " + packageConstantTypeName + " = " + packageConstantTypeValuesString)
}
}
}
}
ensureCodeInPackage := func(goPackage string) {
_, ok := mappedTypeScript[goPackage]
if !ok {