Skip to content

Commit

Permalink
Make getDatabaseFile safer
Browse files Browse the repository at this point in the history
  • Loading branch information
DallasHoff committed Aug 6, 2024
1 parent 2ea16db commit c2dc6e9
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 7 deletions.
11 changes: 9 additions & 2 deletions src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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',
});
};
Expand Down
8 changes: 3 additions & 5 deletions test/get-database-file.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
});
});

0 comments on commit c2dc6e9

Please sign in to comment.