Skip to content

Commit

Permalink
refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
YaroslavPodorvanov committed Apr 21, 2020
1 parent 3ca6bc6 commit f408b8a
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 27 deletions.
30 changes: 18 additions & 12 deletions src/convert.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,18 +98,9 @@ function analyzeArray(array: Array<any>, options: Options): string {
const collector = new Collector();
const lines = [];

if (array.length === 0) {
collector.addImport(defaultImport);
const typeName = analyzeProperty("nested", array, collector, inlineShift)

lines.push(` repeated ${defaultAny} items = 1;`);

return render(collector.getImports(), [], lines, options);
}

const value = array[0];
const typeName = analyzeProperty("nested", value, collector, inlineShift)

lines.push(` repeated ${typeName} items = 1;`);
lines.push(` ${typeName} items = 1;`);

return render(collector.getImports(), collector.getMessages(), lines, options);
}
Expand All @@ -133,15 +124,30 @@ function analyzeObject(json: object, options: Options): string {

function analyzeProperty(key: string, value: any, collector: Collector, inlineShift: string): string {
if (Array.isArray(value)) {
// [] -> any
if (value.length === 0) {
collector.addImport(defaultImport);

return `repeated ${defaultAny}`;
}

return `repeated ${analyzeType(value[0], collector)}`;
// [[...]] -> any
const first = value[0];
if (Array.isArray(first)) {
collector.addImport(defaultImport);

return `repeated ${defaultAny}`;
}

const typeName = analyzeObjectProperty(key, value[0], collector, inlineShift);

return `repeated ${typeName}`;
}

return analyzeObjectProperty(key, value, collector, inlineShift);
}

function analyzeObjectProperty(key: string, value: any, collector: Collector, inlineShift: string) {
const typeName = analyzeType(value, collector);

if (typeName === "object") {
Expand Down
33 changes: 19 additions & 14 deletions src/tests/convert.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,44 +9,49 @@ test("convert test", (t) => {
t.equal(convert(json, options).success, protobuf);
}

// null
// primitives
{
assert("null", `syntax = "proto3";
// null
{
assert("null", `syntax = "proto3";
import "google/protobuf/any.proto";
message SomeMessage {
google.protobuf.Any first = 1;
}`)
}
}

// int32
{
assert("1", `syntax = "proto3";
// int32
{
assert("1", `syntax = "proto3";
message SomeMessage {
int32 first = 1;
}`)
}
}

// bool
{
assert("true", `syntax = "proto3";
// bool
{
assert("true", `syntax = "proto3";
message SomeMessage {
bool first = 1;
}`)
}
}

// string
{
assert(`"text"`, `syntax = "proto3";
// string
{
assert(`"text"`, `syntax = "proto3";
message SomeMessage {
string first = 1;
}`)
}

}


// object
{
assert("{}", `syntax = "proto3";
Expand Down
Loading

0 comments on commit f408b8a

Please sign in to comment.