Skip to content

Commit

Permalink
Regig Next JS support CLI options
Browse files Browse the repository at this point in the history
  • Loading branch information
DomBlack committed Jun 28, 2022
1 parent b4af18a commit 15192c6
Show file tree
Hide file tree
Showing 7 changed files with 273 additions and 160 deletions.
59 changes: 42 additions & 17 deletions cli/cmd/encore/gen.go
Expand Up @@ -5,6 +5,7 @@ import (
"fmt"
"io/ioutil"
"os"
"strings"
"time"

"github.com/spf13/cobra"
Expand All @@ -21,10 +22,15 @@ func init() {
rootCmd.AddCommand(genCmd)

var (
output string
lang string
envName string
nextJsSupport bool
output string
lang string
envName string
preset string

tsOptions = &daemonpb.GenClientRequest_TypeScriptOptions{
Namespaces: true,
Swr: false,
}
)

genClientCmd := &cobra.Command{
Expand All @@ -38,15 +44,29 @@ Use '--env=local' to generate it based on your local development version of the
Supported language codes are:
typescript: A TypeScript-client using the in-browser Fetch API
go: A Go client using net/http"
Support presets are:
nextjs: Generates a TypScript client for use within a Next.js application
`,
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {
if output == "" && lang == "" {
fatal("specify at least one of --output or --lang.")
if output == "" && lang == "" && preset == "" {
fatal("specify at least one of --output, --lang or --preset.")
}
appID := args[0]

if lang == "" {
if preset != "" {
switch strings.ToLower(preset) {
case "nextjs", "next.js":
lang = string(codegen.LangTypeScript)
tsOptions = &daemonpb.GenClientRequest_TypeScriptOptions{
Namespaces: false,
Swr: true,
}
default:
fatal("unknown preset " + preset + "\n\nSupported presets are: nextjs")
}
} else if lang == "" {
var ok bool
l, ok := codegen.Detect(output)
if !ok {
Expand All @@ -62,19 +82,15 @@ Supported language codes are:
lang = string(l)
}

if nextJsSupport && lang != "typescript" {
fatal("--nextjs is only supported for typescript")
}

ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()

daemon := setupDaemon(ctx)
resp, err := daemon.GenClient(ctx, &daemonpb.GenClientRequest{
AppId: appID,
EnvName: envName,
Lang: lang,
NextJsSupport: nextJsSupport,
AppId: appID,
EnvName: envName,
Lang: lang,
Ts: tsOptions,
})
if err != nil {
fatal(err)
Expand Down Expand Up @@ -106,6 +122,15 @@ Supported language codes are:
genClientCmd.Flags().StringVarP(&envName, "env", "e", "", "The environment to fetch the API for (defaults to the primary environment)")
_ = genClientCmd.RegisterFlagCompletionFunc("env", autoCompleteEnvSlug)

genClientCmd.Flags().BoolVar(&nextJsSupport, "nextjs", false, "Generates a TypeScript client which is compatible with a Next.js (disable Namespaces)")
_ = genClientCmd.RegisterFlagCompletionFunc("nextjs", autoCompleteFromStaticList("true", "false"))
genClientCmd.Flags().StringVarP(&preset, "preset", "p", "", "Configures the client generation based on a given preset")
_ = genClientCmd.RegisterFlagCompletionFunc(
"preset",
autoCompleteFromStaticList("nextjs\tConfigures the client generation for Next.js using TypeScript"),
)

genClientCmd.Flags().BoolVar(&tsOptions.Namespaces, "ts.namespaces", true, "Use namespaces in TypeScript to mirror Go packages")
_ = genClientCmd.RegisterFlagCompletionFunc("ts.namespaces", autoCompleteFromStaticList("true", "false"))

genClientCmd.Flags().BoolVar(&tsOptions.Namespaces, "ts.swr", false, "Write SWR functions in the Typescript client")
_ = genClientCmd.RegisterFlagCompletionFunc("ts.swr", autoCompleteFromStaticList("true", "false"))
}
2 changes: 1 addition & 1 deletion cli/daemon/daemon.go
Expand Up @@ -103,7 +103,7 @@ func (s *Server) GenClient(ctx context.Context, params *daemonpb.GenClientReques
}

lang := codegen.Lang(params.Lang)
code, err := codegen.Client(lang, params.AppId, md, params.NextJsSupport)
code, err := codegen.Client(lang, params.AppId, md, params.Ts)
if err != nil {
return nil, status.Error(codes.InvalidArgument, err.Error())
}
Expand Down
2 changes: 1 addition & 1 deletion cli/daemon/run/run_test.go
Expand Up @@ -108,7 +108,7 @@ func TestEndToEndWithApp(t *testing.T) {

// Use golden to test that the generated clients are as expected for the echo test app
for lang, path := range map[codegen.Lang]string{codegen.LangGo: "client/client.go", codegen.LangTypeScript: "client.ts"} {
client, err := codegen.Client(lang, "slug", build.Parse.Meta, false)
client, err := codegen.Client(lang, "slug", build.Parse.Meta, nil)
if err != nil {
fmt.Println(err.Error())
c.FailNow()
Expand Down
9 changes: 7 additions & 2 deletions cli/internal/codegen/client.go
Expand Up @@ -9,6 +9,7 @@ import (
"runtime/debug"
"strings"

daemonpb "encr.dev/proto/encore/daemon"
meta "encr.dev/proto/encore/parser/meta/v1"
)

Expand Down Expand Up @@ -44,7 +45,7 @@ func Detect(path string) (lang Lang, ok bool) {
}

// Client generates an API client based on the given app metadata.
func Client(lang Lang, appSlug string, md *meta.Data, nextJsSupport bool) (code []byte, err error) {
func Client(lang Lang, appSlug string, md *meta.Data, tsOptions *daemonpb.GenClientRequest_TypeScriptOptions) (code []byte, err error) {
defer func() {
if e := recover(); e != nil {
err = fmt.Errorf("codegen.Client %s %s panicked: %v\n%s", lang, appSlug, e, debug.Stack())
Expand All @@ -54,7 +55,11 @@ func Client(lang Lang, appSlug string, md *meta.Data, nextJsSupport bool) (code
var gen generator
switch lang {
case LangTypeScript:
gen = &typescript{generatorVersion: typescriptGenLatestVersion, noNamespaces: nextJsSupport, generateSWRHelpers: nextJsSupport}
if tsOptions == nil {
tsOptions = &daemonpb.GenClientRequest_TypeScriptOptions{Namespaces: true}
}

gen = &typescript{generatorVersion: typescriptGenLatestVersion, noNamespaces: !tsOptions.Namespaces, generateSWRHelpers: tsOptions.Swr}
case LangGo:
gen = &golang{generatorVersion: goGenLatestVersion}
default:
Expand Down
5 changes: 3 additions & 2 deletions cli/internal/codegen/client_test.go
Expand Up @@ -14,6 +14,7 @@ import (

"encr.dev/parser"
"encr.dev/pkg/golden"
daemonpb "encr.dev/proto/encore/daemon"
)

func TestMain(m *testing.M) {
Expand Down Expand Up @@ -61,15 +62,15 @@ func TestClientCodeGeneration(t *testing.T) {
c.Run(testName, func(c *qt.C) {
c.Assert(ok, qt.IsTrue, qt.Commentf("Unable to detect language type for %s", file.Name()))

generatedClient, err := Client(language, "app", res.Meta, false)
generatedClient, err := Client(language, "app", res.Meta, &daemonpb.GenClientRequest_TypeScriptOptions{Namespaces: true, Swr: false})
c.Assert(err, qt.IsNil)

golden.TestAgainst(c, file.Name(), string(generatedClient))
})

if ok && language == LangTypeScript {
c.Run(testName+"_nextjs_support", func(c *qt.C) {
generatedClient, err := Client(language, "app", res.Meta, true)
generatedClient, err := Client(language, "app", res.Meta, &daemonpb.GenClientRequest_TypeScriptOptions{Namespaces: false, Swr: true})
c.Assert(err, qt.IsNil)

golden.TestAgainst(c, "nextjs_"+file.Name(), string(generatedClient))
Expand Down

0 comments on commit 15192c6

Please sign in to comment.