Skip to content

fix export Bytes data type to JSON response #2409

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Aug 9, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions spec/MongoTransform.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,18 @@ describe('parseObjectToMongoObjectForCreate', () => {
done();
});

it('bytes', (done) => {
var input = {binaryData: "aGVsbG8gd29ybGQ="};
var output = transform.mongoObjectToParseObject(null, input, {
fields: { binaryData: { type: 'Bytes' }},
});
expect(typeof output.binaryData).toEqual('object');
expect(output.binaryData).toEqual(
{__type: 'Bytes', base64: "aGVsbG8gd29ybGQ="}
);
done();
});

it('nested array', (done) => {
var input = {arr: [{_testKey: 'testValue' }]};
var output = transform.mongoObjectToParseObject(null, input, {
Expand Down
24 changes: 21 additions & 3 deletions src/Adapters/Storage/Mongo/MongoTransform.js
Original file line number Diff line number Diff line change
Expand Up @@ -781,6 +781,10 @@ const mongoObjectToParseObject = (className, mongoObject, schema) => {
restObject[key] = GeoPointCoder.databaseToJSON(value);
break;
}
if (schema.fields[key] && schema.fields[key].type === 'Bytes' && BytesCoder.isValidDatabaseObject(value)) {
restObject[key] = BytesCoder.databaseToJSON(value);
break;
}
}
restObject[key] = nestedMongoObjectToNestedParseObject(mongoObject[key]);
}
Expand Down Expand Up @@ -815,15 +819,29 @@ var DateCoder = {
};

var BytesCoder = {
base64Pattern: new RegExp("^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$"),
isBase64Value(object) {
if (typeof object !== 'string') {
return false;
}
return this.base64Pattern.test(object);
},

databaseToJSON(object) {
let value;
if (this.isBase64Value(object)) {
value = object;
} else {
value = object.buffer.toString('base64');
}
return {
__type: 'Bytes',
base64: object.buffer.toString('base64')
base64: value
};
},

isValidDatabaseObject(object) {
return (object instanceof mongodb.Binary);
isValidDatabaseObject(object) {
return (object instanceof mongodb.Binary) || this.isBase64Value(object);
},

JSONToDatabase(json) {
Expand Down