Skip to content

Commit

Permalink
getDatabaseFile specifies MIME type and works with db in subfolder
Browse files Browse the repository at this point in the history
  • Loading branch information
DallasHoff committed Jul 11, 2024
1 parent 310329a commit 5992ed5
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 3 deletions.
20 changes: 17 additions & 3 deletions src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -275,9 +275,23 @@ export class SQLocal {
};

getDatabaseFile = async () => {
const opfs = await navigator.storage.getDirectory();
const fileHandle = await opfs.getFileHandle(this.databasePath);
return await fileHandle.getFile();
const path = this.databasePath.split(/[\\/]/).filter((part) => part !== '');
const fileName = path.pop();

if (!fileName) {
throw new Error('Failed to parse the database file name.');
}

let dirHandle = await navigator.storage.getDirectory();
for (let dirName of path)
dirHandle = await dirHandle.getDirectoryHandle(dirName);

const fileHandle = await dirHandle.getFileHandle(fileName);
const file = await fileHandle.getFile();

return new File([file], fileName, {
type: 'application/x-sqlite3',
});
};

overwriteDatabaseFile = async (
Expand Down
38 changes: 38 additions & 0 deletions test/get-database-file.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
import { describe, expect, it } from 'vitest';
import { SQLocal } from '../src/index';

describe('getDatabaseFile', () => {
const fileName = 'get-database-file-test.sqlite3';
const paths = [[], [''], ['top'], ['one', 'two']];

it('should return the requested database file', async () => {
for (let path of paths) {
const databasePath = [...path, fileName].join('/');
const { sql, getDatabaseFile } = new SQLocal(databasePath);

await sql`CREATE TABLE nums (num REAL NOT NULL)`;
const file = await getDatabaseFile();

expect(file).toBeInstanceOf(File);
expect(file.name).toBe(fileName);
expect(file.size).toBe(16384);
expect(file.type).toBe('application/x-sqlite3');

let dirHandle = await navigator.storage.getDirectory();

for (let dirName of path) {
if (dirName === '') continue;
dirHandle = await dirHandle.getDirectoryHandle(dirName);
}

await dirHandle.removeEntry(fileName);
}
});

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.'
);
});
});

0 comments on commit 5992ed5

Please sign in to comment.