planetscale/database-js

base64 compatibility

mattrobenolt opened this issue · 6 comments

We currently rely on btoa and atob, because that works in browsers and worked in versions of Node we tested against, but that's not as universal as we had hoped.

We should instead, provide some compatibility shim against the Buffer API that should more likely exist? We might need to provide a fallback for even that if neither Buffer nor btoa and friends exist.

But for now, it seems either way, it'd be more favorable to use the Buffer API when available over btoa.

I propose something like this, granted I dunno the best way to do this in JavaScript/TypeScript these days:

var b64encode;
var b64decode;
if(typeof Buffer !== "undefined") {
  b64encode = x => Buffer.from(x, 'latin1').toString('base64')
  b64decode = x => Buffer.from(x, 'base64').toString('latin1')
} else if (typeof btoa !== "undefined") {
  b64encode = btoa
  b64decode = atob
} else {
  // I dunno, natively has neither
}

console.log(b64encode('foo'))
console.log(b64decode('Zm9v'))

I think this is still reasonably applicable since we don't simply use it for the Authorization header. While that's the only use of btoa, atob is used to decode binary row data, which we do for every row in a QueryResult.

Refs: #47