Skip to content

Commit

Permalink
swap to using textdecoder
Browse files Browse the repository at this point in the history
  • Loading branch information
stainless-bot committed Nov 20, 2024
1 parent e6575de commit 9907273
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 1 deletion.
6 changes: 5 additions & 1 deletion src/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1185,7 +1185,11 @@ export const toBase64 = (str: string | Uint8Array | null | undefined): string =>
}

if (typeof btoa !== 'undefined') {
return btoa(typeof str === 'string' ? str : String(str));
if (typeof str === 'string') {
return btoa(str);
} else {
return btoa(new TextDecoder().decode(str));
}
}

throw new FinchError('Cannot generate b64 string; Expected `Buffer` or `btoa` to be defined');
Expand Down
43 changes: 43 additions & 0 deletions tests/core.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { toBase64 } from '@tryfinch/finch-api/core';

describe('toBase64', () => {
const testCases = [
{
input: 'hello world',
expected: 'aGVsbG8gd29ybGQ=',
},
{
input: new Uint8Array([104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]),
expected: 'aGVsbG8gd29ybGQ=',
},
{
input: undefined,
expected: '',
},
];
describe('with Buffer', () => {
test('it converts to base64', async () => {
testCases.forEach(({ input, expected }) => {
expect(toBase64(input)).toBe(expected);
});
});
});

describe('without buffer', () => {
let originalBuffer: BufferConstructor;
beforeAll(() => {
originalBuffer = globalThis.Buffer;
// @ts-expect-error Can't assign undefined to BufferConstructor
globalThis.Buffer = undefined;
});
afterAll(() => {
globalThis.Buffer = originalBuffer;
});

test('it converts to base64', async () => {
testCases.forEach(({ input, expected }) => {
expect(toBase64(input)).toBe(expected);
});
});
});
});

0 comments on commit 9907273

Please sign in to comment.