Skip to content

Commit

Permalink
option for using lower camelcase in message field name (#6)
Browse files Browse the repository at this point in the history
  • Loading branch information
lyonlai authored Nov 25, 2020
1 parent 6014620 commit d668aa2
Show file tree
Hide file tree
Showing 23 changed files with 205 additions and 106 deletions.
1 change: 0 additions & 1 deletion .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -61,5 +61,4 @@ jobs:
- name: Run integration tests
run: |
cd integration_tests
make client-protos
./scripts/test-ci.sh
14 changes: 11 additions & 3 deletions generator/template.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"text/template"

"github.com/Masterminds/sprig"
"github.com/iancoleman/strcase"

"github.com/squareup/protoc-gen-grpc-gateway-ts/data"
"github.com/squareup/protoc-gen-grpc-gateway-ts/registry"
Expand All @@ -32,17 +33,17 @@ const tmpl = `
{{- if .HasOneOfFields}}
type Base{{.Name}} = {
{{- range .NonOneOfFields}}
{{.Name}}?: {{tsType .}}
{{fieldName .Name}}?: {{tsType .}}
{{- end}}
}
export type {{.Name}} = Base{{.Name}}
{{range $groupId, $fields := .OneOfFieldsGroups}} & OneOf<{ {{range $index, $field := $fields}}{{$field.Name}}: {{tsType $field}}{{if (lt (add $index 1) (len $fields))}}; {{end}}{{end}} }>
{{range $groupId, $fields := .OneOfFieldsGroups}} & OneOf<{ {{range $index, $field := $fields}}{{fieldName $field.Name}}: {{tsType $field}}{{if (lt (add $index 1) (len $fields))}}; {{end}}{{end}} }>
{{end}}
{{- else -}}
export type {{.Name}} = {
{{- range .Fields}}
{{.Name}}?: {{tsType .}}
{{fieldName .Name}}?: {{tsType .}}
{{- end}}
}
{{end}}
Expand Down Expand Up @@ -207,6 +208,13 @@ func GetTemplate(r *registry.Registry) *template.Template {
},
"renderURL": renderURL,
"buildInitReq": buildInitReq,
"fieldName": func(name string) string {
if r.UseProtoNames {
return name
}

return strcase.ToLowerCamel(name)
},
})

t = template.Must(t.Parse(tmpl))
Expand Down
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ require (
github.com/golang/protobuf v1.4.3
github.com/grpc-ecosystem/grpc-gateway v1.15.2
github.com/huandu/xstrings v1.3.2 // indirect
github.com/iancoleman/strcase v0.1.2
github.com/imdario/mergo v0.3.11 // indirect
github.com/mitchellh/copystructure v1.0.0 // indirect
github.com/pkg/errors v0.9.1
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,8 @@ github.com/grpc-ecosystem/grpc-gateway v1.15.2 h1:HC+hWRWf+v5zTMPyoaYTKIJih+4sd4
github.com/grpc-ecosystem/grpc-gateway v1.15.2/go.mod h1:vO11I9oWA+KsxmfFQPhLnnIb1VDE24M+pdxZFiuZcA8=
github.com/huandu/xstrings v1.3.2 h1:L18LIDzqlW6xN2rEkpdV8+oL/IXWJ1APd+vsdYy4Wdw=
github.com/huandu/xstrings v1.3.2/go.mod h1:y5/lhBue+AyNmUVz9RLU9xbLR0o4KIIExikq4ovT0aE=
github.com/iancoleman/strcase v0.1.2 h1:gnomlvw9tnV3ITTAxzKSgTF+8kFWcU/f+TgttpXGz1U=
github.com/iancoleman/strcase v0.1.2/go.mod h1:SK73tn/9oHe+/Y0h39VT4UCxmurVJkR5NA7kMEAOgSE=
github.com/imdario/mergo v0.3.11 h1:3tnifQM4i+fbajXKBHXWEH+KvNHqojZ778UH75j3bGA=
github.com/imdario/mergo v0.3.11/go.mod h1:jmQim1M+e3UYxmgPu/WyfjB3N3VflVyUjjjwH0dnCYA=
github.com/mitchellh/copystructure v1.0.0 h1:Laisrj+bAB6b/yJwB5Bt3ITZhGJdqmxquMKeZ+mmkFQ=
Expand Down
2 changes: 1 addition & 1 deletion integration_tests/.gitignore
Original file line number Diff line number Diff line change
@@ -1 +1 @@
*.pb.ts
*.pb.*
16 changes: 0 additions & 16 deletions integration_tests/Makefile

This file was deleted.

16 changes: 14 additions & 2 deletions integration_tests/integration_test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,17 @@
import {CounterService} from "./service.pb";
import camelCase from 'lodash.camelcase';
import { pathOr } from 'ramda'
import {expect} from 'chai'

function getFieldName(name: string) {
const useCamelCase = pathOr(false, ['__karma__', 'config', 'useProtoNames'], window) === false
return useCamelCase ? camelCase(name) : name
}

function getField(obj: {[key: string]: any}, name: string) {
return obj[getFieldName(name)]
}

describe("test grpc-gateway-ts communication", () => {
it("unary request", async () => {
const result = await CounterService.Increment({counter: 199}, {pathPrefix: "http://localhost:8081"})
Expand All @@ -22,12 +33,13 @@ describe("test grpc-gateway-ts communication", () => {

it('http post body check request with nested body path', async () => {
const result = await CounterService.HTTPPostWithNestedBodyPath({a: 10, req: { b: 15 }}, {pathPrefix: "http://localhost:8081"})
expect(result.result).to.equal(25)
expect(getField(result, 'post_result')).to.equal(25)
})


it('http post body check request with star in path', async () => {
const result = await CounterService.HTTPPostWithStarBodyPath({a: 10, req: { b: 15 }, c: 23}, {pathPrefix: "http://localhost:8081"})
expect(result.result).to.equal(48)
expect(getField(result, 'post_result')).to.equal(48)
})

})
20 changes: 2 additions & 18 deletions integration_tests/karma.conf.ci.js
Original file line number Diff line number Diff line change
@@ -1,20 +1,4 @@
const getConf = require('./karma.conf.common')
module.exports = function(config) {
config.set({
frameworks: ['mocha', 'chai', 'karma-typescript'],
preprocessors: {
"**/*.ts": ["karma-typescript"]
},
files: ['**/*_test.ts', '**/*.pb.ts'],
reporters: ['progress', 'karma-typescript'],
port: 9876, // karma web server port
colors: true,
logLevel: config.LOG_INFO,
browsers: ['ChromeHeadless'],
autoWatch: false,
singleRun: true, // Karma captures browsers, runs the tests and exits
concurrency: Infinity,
karmaTypescriptConfig: {
tsconfig: './tsconfig.json'
}
})
config.set(getConf(true, config))
}
23 changes: 23 additions & 0 deletions integration_tests/karma.conf.common.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
module.exports = function(ci, config){
return {
frameworks: ['mocha', 'chai', 'karma-typescript'],
preprocessors: {
"**/*.ts": ["karma-typescript"]
},
files: ['**/*_test.ts', '**/*.pb.ts'],
reporters: ['progress', 'karma-typescript'],
port: 9876, // karma web server port
colors: true,
logLevel: config.LOG_INFO,
browsers: ['ChromeHeadless'],
autoWatch: false,
singleRun: ci, // Karma captures browsers, runs the tests and exits
concurrency: Infinity,
karmaTypescriptConfig: {
tsconfig: './tsconfig.json'
},
client: {
useProtoNames: process.env['USE_PROTO_NAMES'] === "true"
},
}
}
20 changes: 2 additions & 18 deletions integration_tests/karma.conf.js
Original file line number Diff line number Diff line change
@@ -1,20 +1,4 @@
const getConf = require('./karma.conf.common')
module.exports = function(config) {
config.set({
frameworks: ['mocha', 'chai', 'karma-typescript'],
preprocessors: {
"**/*.ts": ["karma-typescript"]
},
files: ['**/*_test.ts', '**/*.pb.ts'],
reporters: ['progress', 'karma-typescript'],
port: 9876, // karma web server port
colors: true,
logLevel: config.LOG_INFO,
browsers: ['ChromeHeadless'],
autoWatch: false,
// singleRun: true, // Karma captures browsers, runs the tests and exits
concurrency: Infinity,
karmaTypescriptConfig: {
tsconfig: './tsconfig.json'
}
})
config.set(getConf(false, config))
}
7 changes: 6 additions & 1 deletion integration_tests/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package main

import (
"context"
"flag"
"github.com/grpc-ecosystem/grpc-gateway/runtime"
"google.golang.org/grpc"
"net"
Expand Down Expand Up @@ -35,6 +36,8 @@ func allowCORS(h http.Handler) http.Handler {
}

func main() {
origName := flag.Bool("orig", false, "tell server to use origin name in jsonpb")
flag.Parse()
ctx := context.Background()
ctx, cancel := context.WithCancel(ctx)
defer cancel()
Expand Down Expand Up @@ -62,7 +65,9 @@ func main() {

// Register gRPC server endpoint
// Note: Make sure the gRPC server is running properly and accessible
mux := runtime.NewServeMux()
mux := runtime.NewServeMux(runtime.WithMarshalerOption(runtime.MIMEWildcard, &runtime.JSONPb{
OrigName: *origName,
}))
opts := []grpc.DialOption{grpc.WithInsecure()}
err = RegisterCounterServiceHandlerFromEndpoint(ctx, mux, "localhost:9000", opts)
if err != nil {
Expand Down
48 changes: 48 additions & 0 deletions integration_tests/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 5 additions & 0 deletions integration_tests/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,20 @@
"license": "ISC",
"devDependencies": {
"@types/chai": "^4.2.14",
"@types/lodash.camelcase": "^4.3.6",
"@types/mocha": "^8.0.3",
"@types/ramda": "^0.27.32",
"chai": "^4.2.0",
"karma": "^5.2.3",
"karma-chai": "^0.1.0",
"karma-chrome-launcher": "^3.1.0",
"karma-env-preprocessor": "^0.1.1",
"karma-mocha": "^2.0.1",
"karma-script-launcher": "^1.0.0",
"karma-typescript": "^5.2.0",
"lodash.camelcase": "^4.3.0",
"mocha": "^8.2.0",
"ramda": "^0.27.1",
"typescript": "^4.0.5"
}
}
6 changes: 6 additions & 0 deletions integration_tests/scripts/gen-protos.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
#!/bin/bash
USE_PROTO_NAMES=${1:-"false"}
cd .. && go install && cd integration_tests && \
protoc -I . \
--grpc-gateway-ts_out=logtostderr=true,use_proto_names=$USE_PROTO_NAMES,loglevel=debug:./ \
service.proto
7 changes: 7 additions & 0 deletions integration_tests/scripts/gen-server-proto.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
#!/bin/bash

protoc -I . --go_out ./ --go_opt plugins=grpc --go_opt paths=source_relative \
--grpc-gateway_out ./ --grpc-gateway_opt logtostderr=true \
--grpc-gateway_opt paths=source_relative \
--grpc-gateway_opt generate_unbound_methods=true \
service.proto
14 changes: 14 additions & 0 deletions integration_tests/scripts/source.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
#!/bin/bash

function runTest {
ORIG_NAME=${1:="false"}
CONFIG_NAME=${2:="karma.conf.js"}
./scripts/gen-protos.sh $ORIG_NAME
go run ./ -orig=$ORIG_NAME &
pid=$!

USE_PROTO_NAMES=$ORIG_NAME ./node_modules/.bin/karma start $CONFIG_NAME
pkill -P $pid
}


10 changes: 6 additions & 4 deletions integration_tests/scripts/test-ci.sh
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
#!/bin/bash

go run ./ &
pid=$!
source ./scripts/source.sh

CONF="karma.conf.ci.js"

runTest false $CONF
runTest true $CONF

./node_modules/.bin/karma start karma.conf.ci.js
pkill -P $pid
8 changes: 4 additions & 4 deletions integration_tests/scripts/test.sh
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
#!/bin/bash

go run ./ &
pid=$!
source ./scripts/source.sh

./node_modules/.bin/karma start karma.conf.js
pkill -P $pid
CONF="karma.conf.js"

runTest ${1:-false} $CONF
Loading

0 comments on commit d668aa2

Please sign in to comment.