Skip to content

Commit

Permalink
deserialize buffers correctly
Browse files Browse the repository at this point in the history
  • Loading branch information
vkarpov15 committed Sep 29, 2024
1 parent 46861cc commit 003288b
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 4 deletions.
31 changes: 30 additions & 1 deletion src/client/deserialize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,36 @@ import { EJSON, ObjectId } from 'bson';
import mongoose from 'mongoose';

export function deserialize(data: Record<string, any>): Record<string, any> {
return data != null ? deserializeObjectIds(EJSON.deserialize(data)) : data;
return data != null ? deserializeObjectIds(EJSON.deserialize(deserializeBuffers(data))) : data;
}

function deserializeBuffers(data: Record<string, any>): Record<string, any> {
if (data == null) {
return data;
}
if (Array.isArray(data)) {
for (let i = 0; i < data.length; ++i) {
if (data[i] == null) {
continue;
}
if (typeof data[i].$binary === 'string') {
data[i] = Buffer.from(data[i].$binary, 'base64');
} else if (typeof data[i] === 'object') {
deserializeBuffers(data[i]);
}
}
}
for (const key of Object.keys(data)) {
if (data[key] == null) {
continue;
}
if (typeof data[key].$binary === 'string') {
data[key] = Buffer.from(data[key].$binary, 'base64');
} else if (typeof data[key] === 'object') {
deserializeBuffers(data[key]);
}
}
return data;
}

function deserializeObjectIds(data: Record<string, any>): Record<string, any> {
Expand Down
5 changes: 2 additions & 3 deletions tests/driver/api.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -759,9 +759,8 @@ describe('Mongoose Model API level tests', async () => {
const doc = new TestModel({ buf: Buffer.from('hello world') });
await doc.save();

// Still fails with [{"message":"Unexpected Binary Extended JSON format {\"$binary\":\"aGVsbG8gd29ybGQ=\"}"}]
// const fromDb = await TestModel.findOne();
// assert.equal(fromDb.buf.toString('utf8'), 'hello world');
const fromDb = await TestModel.findOne();
assert.equal(fromDb.buf.toString('utf8'), 'hello world');

await mongoose.disconnect();
});
Expand Down

0 comments on commit 003288b

Please sign in to comment.