Skip to content

Commit

Permalink
fix(codec): use index to determine array struct member value (#1775)
Browse files Browse the repository at this point in the history
Where the STRUCT value is an array, always determine inner member value using field index.

STRUCT value is represented by var 'decoded'.

Refs: #1774
  • Loading branch information
andrao authored Jan 23, 2023
1 parent 030115e commit fc2b695
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 6 deletions.
2 changes: 1 addition & 1 deletion src/codec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -411,7 +411,7 @@ function decode(value: Value, type: spannerClient.spanner.v1.Type): Value {
case 'STRUCT':
fields = type.structType!.fields!.map(({name, type}, index) => {
const value = decode(
decoded[name!] || decoded[index],
(!Array.isArray(decoded) && decoded[name!]) || decoded[index],
type as spannerClient.spanner.v1.Type
);
return {name, value};
Expand Down
61 changes: 56 additions & 5 deletions test/codec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -631,15 +631,22 @@ describe('codec', () => {
assert(decoded[0] instanceof codec.Int);
});

it('should decode STRUCT and inner members', () => {
it('should decode object STRUCT value and inner members', () => {
const value = {
fieldName: '1',
keys: 1,
fieldName: '2',
};

const decoded = codec.decode(value, {
code: google.spanner.v1.TypeCode.STRUCT,
structType: {
fields: [
{
name: 'keys',
type: {
code: google.spanner.v1.TypeCode.JSON,
},
},
{
name: 'fieldName',
type: {
Expand All @@ -650,11 +657,55 @@ describe('codec', () => {
},
});

const expectedStruct = new codec.Struct({
name: 'fieldName',
value: new codec.Int(value.fieldName),
const expectedStruct = new codec.Struct(
{
name: 'keys',
value: value.keys,
},
{
name: 'fieldName',
value: new codec.Int(value.fieldName),
}
);

assert(decoded instanceof codec.Struct);
assert.deepStrictEqual(decoded, expectedStruct);
});

it('should decode array STRUCT value and inner members', () => {
const value = ['1', '2'];

const decoded = codec.decode(value, {
code: google.spanner.v1.TypeCode.STRUCT,
structType: {
fields: [
{
name: 'keys',
type: {
code: google.spanner.v1.TypeCode.JSON,
},
},
{
name: 'fieldName',
type: {
code: google.spanner.v1.TypeCode.INT64,
},
},
],
},
});

const expectedStruct = new codec.Struct(
{
name: 'keys',
value: JSON.parse(value[0]),
},
{
name: 'fieldName',
value: new codec.Int(value[1]),
}
);

assert(decoded instanceof codec.Struct);
assert.deepStrictEqual(decoded, expectedStruct);
});
Expand Down

0 comments on commit fc2b695

Please sign in to comment.