Skip to content

Commit 6e0a25d

Browse files
conghoangflovilmart
authored andcommitted
fix export Bytes data type to JSON (#2409)
1 parent 452887b commit 6e0a25d

File tree

2 files changed

+33
-3
lines changed

2 files changed

+33
-3
lines changed

spec/MongoTransform.spec.js

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -156,6 +156,18 @@ describe('parseObjectToMongoObjectForCreate', () => {
156156
done();
157157
});
158158

159+
it('bytes', (done) => {
160+
var input = {binaryData: "aGVsbG8gd29ybGQ="};
161+
var output = transform.mongoObjectToParseObject(null, input, {
162+
fields: { binaryData: { type: 'Bytes' }},
163+
});
164+
expect(typeof output.binaryData).toEqual('object');
165+
expect(output.binaryData).toEqual(
166+
{__type: 'Bytes', base64: "aGVsbG8gd29ybGQ="}
167+
);
168+
done();
169+
});
170+
159171
it('nested array', (done) => {
160172
var input = {arr: [{_testKey: 'testValue' }]};
161173
var output = transform.mongoObjectToParseObject(null, input, {

src/Adapters/Storage/Mongo/MongoTransform.js

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -781,6 +781,10 @@ const mongoObjectToParseObject = (className, mongoObject, schema) => {
781781
restObject[key] = GeoPointCoder.databaseToJSON(value);
782782
break;
783783
}
784+
if (schema.fields[key] && schema.fields[key].type === 'Bytes' && BytesCoder.isValidDatabaseObject(value)) {
785+
restObject[key] = BytesCoder.databaseToJSON(value);
786+
break;
787+
}
784788
}
785789
restObject[key] = nestedMongoObjectToNestedParseObject(mongoObject[key]);
786790
}
@@ -815,15 +819,29 @@ var DateCoder = {
815819
};
816820

817821
var BytesCoder = {
822+
base64Pattern: new RegExp("^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$"),
823+
isBase64Value(object) {
824+
if (typeof object !== 'string') {
825+
return false;
826+
}
827+
return this.base64Pattern.test(object);
828+
},
829+
818830
databaseToJSON(object) {
831+
let value;
832+
if (this.isBase64Value(object)) {
833+
value = object;
834+
} else {
835+
value = object.buffer.toString('base64');
836+
}
819837
return {
820838
__type: 'Bytes',
821-
base64: object.buffer.toString('base64')
839+
base64: value
822840
};
823841
},
824842

825-
isValidDatabaseObject(object) {
826-
return (object instanceof mongodb.Binary);
843+
isValidDatabaseObject(object) {
844+
return (object instanceof mongodb.Binary) || this.isBase64Value(object);
827845
},
828846

829847
JSONToDatabase(json) {

0 commit comments

Comments
 (0)