Code Monkey home page Code Monkey logo

struct2ts's Introduction

struct2ts GoDoc

An extremely simple and powerful Go struct to Typescript Class generator.

Inspired by tkrajina/typescriptify-golang-structs.

Install

go get -u -v github.com/OneOfOne/struct2ts/...

Features

  • Fairly decent command line interface if you don't wanna write a generator yourself.
  • Automatically handles Go int64 timestamps <-> Javascript Date.
  • Automatically handles json tags.

Options

There's an extra struct tag to control the output, ts, valid options are

  • - omit this field.
  • date handle converting time.Time{}.Unix() <-> javascript Date.
  • ,no-null only valid for struct fields, forces creating a new class rather than using null in TS.
  • ,null allows any field type to be null.

Example

  • Input:
type OtherStruct struct {
	T time.Time `json:"t,omitempty"`
}

type ComplexStruct struct {
	S           string       `json:"s,omitempty"`
	I           int          `json:"i,omitempty"`
	F           float64      `json:"f,omitempty"`
	TS          *int64       `json:"ts,omitempty" ts:"date,null"`
	T           time.Time    `json:"t,omitempty"` // automatically handled
	NullOther   *OtherStruct `json:"o,omitempty"`
	NoNullOther *OtherStruct `json:"nno,omitempty" ts:",no-null"`
}
  • Output:
// ... helpers...
// struct2ts:github.com/OneOfOne/struct2ts_test.ComplexStructOtherStruct
class ComplexStructOtherStruct {
	t: Date;

	constructor(data?: any) {
		const d: any = (data && typeof data === 'object') ? ToObject(data) : {};
		this.t = ('t' in d) ? ParseDate(d.t) : new Date();
	}

	toObject(): any {
		const cfg: any = {};
		cfg.t = 'string';
		return ToObject(this, cfg);
	}
}

// struct2ts:github.com/OneOfOne/struct2ts_test.ComplexStruct
class ComplexStruct {
	s: string;
	i: number;
	f: number;
	ts: Date | null;
	t: Date;
	o: ComplexStructOtherStruct | null;
	nno: ComplexStructOtherStruct;

	constructor(data?: any) {
		const d: any = (data && typeof data === 'object') ? ToObject(data) : {};
		this.s = ('s' in d) ? d.s as string : '';
		this.i = ('i' in d) ? d.i as number : 0;
		this.f = ('f' in d) ? d.f as number : 0;
		this.ts = ('ts' in d) ? ParseDate(d.ts) : null;
		this.t = ('t' in d) ? ParseDate(d.t) : new Date();
		this.o = ('o' in d) ? new ComplexStructOtherStruct(d.o) : null;
		this.nno = new ComplexStructOtherStruct(d.nno);
	}

	toObject(): any {
		const cfg: any = {};
		cfg.i = 'number';
		cfg.f = 'number';
		cfg.t = 'string';
		return ToObject(this, cfg);
	}
}
// ...exports...

Command Line Usage

➤ struct2ts -h
usage: struct2ts [<flags>] [<pkg.struct>...]

Flags:
	-h, --help                  Show context-sensitive help (also try --help-long
								and --help-man).
		--indent="\t"           Output indentation.
	-m, --mark-optional-fields  Add `?` to fields with omitempty.
	-6, --es6                   generate es6 code
	-C, --no-ctor               Don't generate a ctor.
	-T, --no-toObject           Don't generate a Class.toObject() method.
	-E, --no-exports            Don't automatically export the generated types.
	-D, --no-date               Don't automatically handle time.Unix () <-> JS
								Date().
	-H, --no-helpers            Don't output the helpers.
	-N, --no-default-values     Don't assign default/zero values in the ctor.
	-i, --interface             Only generate an interface (disables all the other
								options).
	-s, --src-only              Only output the Go code (helpful if you want to
								edit it yourself).
	-p, --package-name="main"   the package name to use if --src-only is set.
	-k, --keep-temp             Keep the generated Go file, ignored if --src-only
								is set.
	-o, --out="-"               Write the output to a file instead of stdout.
	-V, --version               Show application version.

Args:
	[<pkg.struct>]  List of structs to convert (github.com/you/auth/users.User,
					users.User or users.User:AliasUser).

Advanced

Custom output per model

type CustomTypescript interface {
	RenderCustomTypescript(w io.Writer) (err error)
}

If your model implements a RenderCustomTypescript(w io.Writer) (err error) function it will inject what ever you write to the writer at the end of the model. struct2ts will handle the first level of indenting for you.

TODO

  • Use xast to skip reflection.
  • Support annoymous structs.
  • Support ES6.

License

This project is released under the BSD 3-clause "New" or "Revised" License.

struct2ts's People

Contributors

arran4 avatar benoitkugler avatar hasenj avatar oneofone avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

struct2ts's Issues

Generate all Structs in a file

Hello, I'm trying to generate TS classes for all exported structs in a given file. I can't seem to be able to do this. What is the trick? on https://github.com/tkrajina/typescriptify-golang-structs you can just specify a file:

If all your structs are in one file, you can convert them with:

tscriptify -package=package/with/your/models -target=target_ts_file.ts path/to/file/with/structs.go

I tried a number of variations to specify a file from the command line, but I always get errors. Is this implemented? or what am I missing?

Thanks.

Date to string type

Is there an option to convert stuct date to a string when generating typescript?

Anything that is not `-` or `date` should be use as type for interfaces

As stated.

Something like:

type Custom struct {
    MyValue `ts:"MyCustomType"`
}

Should become:

interface Custom {
    my_value: MyCustomType
}

For importing the types, I use a script with something like echo "import {Type} from '@types'" > src/types/golang.ts before running struct2ts, if someone is wondering.

How to handle go modules

I'm trying to run this tool as a go generator like this:

//go:generate go run github.com/OneOfOne/struct2ts/cmd/struct2ts my.path/my_pkg.ServerInfoResponse -o ./MOD.ts

Yet it fails, as it can't resolve the module via HTTP. It's not published, and even if it was, I wouldn't want it to resolve the repository, I would like to get the code from the current source.

I'm running the command from inside the module directory, but it seems to make no difference, as the executable is ran in a temporary folder by go run.

How should I approach this? My aim is to automatically generate typescript interfaces when compiling the relative go structures.

Thanks

[]interface{} not converted to any[]

From #13 (comment)

A struct with

Vars           []map[string]interface{} `config:"vars" json:"vars,omitempty"`

is converted to:

vars?: map[string]interface {}[];

instead of

vars?: { [key: string]: any }[];

but if we drop the array

Vars           map[string]interface{} `config:"vars" json:"vars,omitempty"`

it's converted to

vars?: { [key: string]: any };

Read source from vendor/ folder

I have a problem using struct2ts (version 1.0.2) when struct2ts and the package it operates on are not installed in $GOPATH, only vendor/.
The reason why I do this is because I'm managing my dependencies (including struct2ts) with dep and running go generate in a docker container as part of the build.

Any plans of supporting this way of doing things?

Error message:

main.go:112: executing: go run /tmp/s2ts_gen_1549295504494674900_5577006791947779410.go
/tmp/s2ts_gen_1549295504494674900_5577006791947779410.go:10:2: cannot find package "github.com/private_dependency/pkg/dependency_service" in any of:
        /usr/local/go/src/github.com/private_dependency/pkg/dependency_service (from $GOROOT)
        /go/src/github.com/private_dependency/pkg/dependency_service (from $GOPATH)
/tmp/s2ts_gen_1549295504494674900_5577006791947779410.go:11:2: cannot find package "github.com/OneOfOne/struct2ts" in any of:
        /usr/local/go/src/github.com/OneOfOne/struct2ts (from $GOROOT)
        /go/src/github.com/OneOfOne/struct2ts (from $GOPATH)
main.go:119: exit status 1

New release

Is it possible to release a new github release version / tag?

Examples for use in code

Sorry for the question, but is this only possible to use this in the command line?
I would like to use it in my code.
Can you give an example for that. thanks.

nullable arrays

Hi and thanks for this package !

From what I understand, it's common in Go to have a "nil" slice. In Go, it's not a problem since a "nil" slice behaves the same as "0 length" slice.
But when you use JSON to communicate such a slice, it gets serialized to "null", thus causing problems in TypeScript.

Thus, shouldn't be safer to switch CanBeNull to true for Slice and Array types ?
(it's a one liner fix, in s2ts.go, line 109)

Interface{} type not converted to any

Small fix needed when converting an interface{} to typescript. At the moment the generated code is:

    data: { [key: string]: interface {} } | null;

While it should be:

    data: { [key: string]: any } | null;

fatal error: stack overflow

Step to reproduce:

go get github.com/aliyun/alibaba-cloud-sdk-go
struct2ts -i -H github.com/aliyun/alibaba-cloud-sdk-go/services/ccc.AddBulkPhoneNumbersResponse

Will receive an error

main.go:112: executing: go run ./s2ts_gen_1570601947058436000_5577006791947779410.go
runtime: goroutine stack exceeds 1000000000-byte limit
fatal error: stack overflow

I guess it is a type that has a circular reference that causes the problem.
PhoneNumber.SkillGroups.SkillGroup[0].OutboundPhoneNumbers[0]'s type is PhoneNumber.

To be compatible with the lastest tslint

The generated class will be reported as this

The class property 'uid' must be marked either 'private', 'public', or 'protected'
    148 | export class music {
    149 |   Name: string;
  > 150 |   uid: string;

might be a good idea to add public tag for them

Strict mode on ToObject

I would like the ability to only export fields defined by the typescript. Type script doesn't seem to have a native way to do this as of the version I'm using (but there are a couple of promising things) so I imagine it might need to be a modification of the toObject function to be more aware I guess.

In my specific case I'm using it for communicating an object back and forwards between the two applications but some JS libraries seem to be contaminating the object.

Underscore in package name causes havoc

I think I found the problem that was partially related to my previous issue. I tried generating a model from a package that was called apps_api, and it failed citing that it couldn't find the name (there was no import in the generated file). Renaming the package to appsapi worked.

Also I noticed that a package name with dashes gets converted to underscores somewhere, but I can't remember where I saw this. Maybe it's a go thing, I have no idea.

The setup is as follows:

  • Module with subfolder called apps-api and the package is called apps_api (inside the subfolder)
  • go:generate command inside an interfaces.go file inside the apps-api folder
  • Running it causes an error:

build command-line-arguments: cannot load my-server/apps_api: cannot find module providing package my-server/apps_api

Removing the underscore from the package name fixed it temporarily.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.