From c2dc6e99f0ae7d8c1ed5e76a430f83d03cf6fdcb Mon Sep 17 00:00:00 2001 From: Dallas Hoffman Date: Tue, 6 Aug 2024 00:06:58 -0400 Subject: [PATCH] Make getDatabaseFile safer --- src/client.ts | 11 +++++++++-- test/get-database-file.test.ts | 8 +++----- 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/src/client.ts b/src/client.ts index 1a36953..0e484ae 100644 --- a/src/client.ts +++ b/src/client.ts @@ -335,18 +335,25 @@ export class SQLocal { .filter((part) => part !== ''); const fileName = path.pop(); + const tempFileName = `backup-${Date.now()}--${fileName}`; + const tempFilePath = `${path.join('/')}/${tempFileName}`; + if (!fileName) { throw new Error('Failed to parse the database file name.'); } + await this.exec('VACUUM INTO ?', [tempFilePath]); + let dirHandle = await navigator.storage.getDirectory(); for (let dirName of path) dirHandle = await dirHandle.getDirectoryHandle(dirName); - const fileHandle = await dirHandle.getFileHandle(fileName); + const fileHandle = await dirHandle.getFileHandle(tempFileName); const file = await fileHandle.getFile(); + const fileBuffer = await file.arrayBuffer(); + await dirHandle.removeEntry(tempFileName); - return new File([file], fileName, { + return new File([fileBuffer], fileName, { type: 'application/x-sqlite3', }); }; diff --git a/test/get-database-file.test.ts b/test/get-database-file.test.ts index c61422f..d05088c 100644 --- a/test/get-database-file.test.ts +++ b/test/get-database-file.test.ts @@ -31,10 +31,8 @@ describe('getDatabaseFile', () => { } }); - it('should throw when requested database has not been created', async () => { - const { getDatabaseFile } = new SQLocal(fileName); - expect(async () => await getDatabaseFile()).rejects.toThrowError( - 'A requested file or directory could not be found at the time an operation was processed.' - ); + it('should not throw when requested database has not been created', async () => { + const { getDatabaseFile } = new SQLocal('blank.sqlite3'); + expect(getDatabaseFile()).resolves.not.toThrow(); }); });