GithubHelp home page GithubHelp logo

bel's Introduction

Generate TypeScript interfaces from Go structs/interfaces - useful for JSON RPC

Go Report Card GoDoc gocover.run Stability: Active

Open in Gitpod

bel is used in production in https://gitpod.io.

Getting started

bel is easy to use. There are two steps involved: extract the Typescript information, and generate the Typescript code.

package main

import (
    "github.com/32leaves/bel"
)

type Demo struct {
    Foo string `json:"foo,omitempty"`
    Bar uint32
    Baz struct {
        FirstField  bool
        SecondField *string
    }
}

func main() {
    ts, err := bel.Extract(Demo{})
    if err != nil {
        panic(err)
    }

    err = bel.Render(ts)
    if err != nil {
        panic(err)
    }
}

produces something akin to (sans formatting):

export interface Demo {
    foo?: string
    Bar: number
    Baz: {
        FirstField: boolean
        SecondField: string
    }
}

Converting interfaces

You can also convert Golang interfaces to TypeScript interfaces. This is particularly handy for JSON RPC:

package main

import (
    "os"
    "github.com/32leaves/bel"
)

type DemoService interface {
    SayHello(name, msg string) (string, error)
}

func main() {
    ts, err := bel.Extract((*DemoService)(nil))
    if err != nil {
        panic(err)
    }

    err = bel.Render(ts)
    if err != nil {
        panic(err)
    }
}

produces something akin to (sans formatting):

export interface DemoService {
    SayHello(arg0: string, arg1: string): string
}

Advanced Usage

You can try all the examples mentioned below in Gitpod.

FollowStructs

Follow structs enable the transitive generation of types. See examples/embed-structs.go.

would produce code for the interface UserService, as well as the struct it refers to AddUserRequest, and User because it's referenced by AddUserRequest. Without FollowStructs we'd simply refer to the types by name, but would not generate code for them.

SortAlphabetically

SortAlphabetically sorts all types and their members by alphabetical order. This produces more deterministic/stable output, which is great for making things comparable across pull requests. See examples/sort-alphabetically.go.

EmbedStructs

Embed structs is similar to FollowStructs except that it produces a single canonical type for each structure. Whenever one struct references another, that reference is resolved and the definition of the other is embedded. See examples/embed-structs.go.

NameAnonStructs

NameAnonStructs is kind of the opposite of EmbedStructs. When we encounter a nested anonymous struct, we make give this previously anonymous structure a name and refer to it using this name. See examples/name-anon-structs.go.

CustomNamer

CustomNamer enables full control over the TypeScript type names. This is handy to enforce a custom coding guideline, or to add a prefix/suffix to the generated type names. See examples/custom-namer.go.

Enums

See examples/enums.go.

Go famously does not have enums, but rather type aliases and consts. Using reflection alone there is no way to obtain a comprehensive list of type values, as the linker might optimize and remove some. bel supports the extraction of enums by parsing the Go source code. Note that this is merely a heuristic and may fail in your case. If it does not work, bel falls back to the underlying type.

Enums can be generated as TypeScript enum or as sum types. Use the bel.GenerateEnumsAsSumTypes flag to change this behaviour.

Code Generation

See examples/code-generation.go.

When generating the TypeScript code you might want to wrap everything in a namespace. To that end bel.GenerateNamespace("myNamespaceName") can be used.

By default bel adds a comment to the files it generates. You can influcence this comment (and any other code that comes before the generated code) using bel.GeneratePreamble and bel.GenerateAdditionalPreamble.

You can configure the io.Writer that bel uses using bel.GenerateOutputTo.

Contributing

All contributions/PR/issue/beer are welcome ❤️.

It's easiest to work with bel using Gitpod: Open in Gitpod

bel's People

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

Watchers

 avatar  avatar  avatar

bel's Issues

Properly extract enums/const

Something like

type Foo string
const (
    Bar = "bar"
    Baz = "baz"
)

type UsesFoo struct {
    Field Foo
}

results in Field being extracted as type string rather than Foo.
Ideally we'd have an enum Foo coming out of the extractor.

Using Go reflection this cannot be done [1, 2]. We could however parse the Golang source and extract the const values that way.

[1] https://stackoverflow.com/questions/33189060/is-there-a-way-to-iterate-over-constant-used-as-enum
[2] https://groups.google.com/forum/#!topic/golang-nuts/M0ORoEU115o

Missing error check in fielpath.WalkFunc

Stacktrace:

panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x18 pc=0x5584e9]

goroutine 1 [running]:
github.com/32leaves/bel.NewParsedSourceEnumHandler.func1(0x615603, 0x15, 0x0, 0x0, 0x653880, 0xc000100b10, 0x40, 0x5f6a00)
	/workspace/go/pkg/mod/github.com/32leaves/[email protected]/enum.go:32 +0x49
path/filepath.Walk(0x615603, 0x15, 0xc0001318e0, 0x0, 0x1000000006595a0)
	/home/gitpod/go/src/path/filepath/path.go:404 +0x6a
github.com/32leaves/bel.NewParsedSourceEnumHandler(0x615603, 0x15, 0x0, 0x0, 0x653880)
	/workspace/go/pkg/mod/github.com/32leaves/[email protected]/enum.go:31 +0xf7
main.main()
	/tmp/build/gitpod-core-components-licensor-typescript--lib.b4eb6140f12b76cf914379726822bcd956b92256/ee/genapi.go:25 +0x8f
exit status 2

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.