Skip to content

Commit 350fe17

Browse files
committed
🐛(sw) keep incremental versioning for IndexedDB
IndexDB need a integer versioning when upgrading the database, it has to be incremental. Before the fix, version 4.0.0 would give 400, when 3.10.0 would give 3100. That would cause an error and the database would be destroyed then recreated. We improve the way we compute the version number to ensure it is always incremental, avoiding such issues.
1 parent a0ddc6b commit 350fe17

File tree

2 files changed

+50
-5
lines changed

2 files changed

+50
-5
lines changed

src/frontend/apps/impress/src/features/service-worker/DocsDB.ts

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -33,12 +33,21 @@ interface IDocsDB extends DBSchema {
3333
type TableName = 'doc-list' | 'doc-item' | 'doc-mutation';
3434

3535
/**
36-
* IndexDB version must be a integer
37-
* @returns
36+
* IndexDB prefers incremental versioning when upgrading the database,
37+
* otherwise it may throw an error, and we need to destroy the database
38+
* and recreate it.
39+
* To calculate the version number, we use the following formula,
40+
* assuring incremental versioning:
41+
* version = major * 1000000 + minor * 1000 + patch
42+
* ex:
43+
* - version 1.2.3 => 1002003
44+
* - version 0.10.15 => 10015
45+
* - version 2.0.0 => 2000000
46+
* @returns number
3847
*/
39-
const getCurrentVersion = () => {
40-
const [major, minor, patch] = pkg.version.split('.');
41-
return parseFloat(`${major}${minor}${patch}`);
48+
export const getCurrentVersion = () => {
49+
const [major, minor, patch] = pkg.version.split('.').map(Number);
50+
return major * 1000000 + minor * 1000 + patch;
4251
};
4352

4453
/**
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
import { afterEach, describe, expect, it, vi } from 'vitest';
2+
3+
vi.mock('@/../package.json', () => ({
4+
default: { version: '0.0.0' },
5+
}));
6+
7+
describe('DocsDB', () => {
8+
afterEach(() => {
9+
vi.clearAllMocks();
10+
vi.resetModules();
11+
});
12+
13+
let previousExpected = 0;
14+
15+
[
16+
{ version: '0.0.1', expected: 1 },
17+
{ version: '0.10.15', expected: 10015 },
18+
{ version: '1.0.0', expected: 1000000 },
19+
{ version: '2.105.3', expected: 2105003 },
20+
{ version: '3.0.0', expected: 3000000 },
21+
{ version: '10.20.30', expected: 10020030 },
22+
].forEach(({ version, expected }) => {
23+
it(`correctly computes version for ${version}`, () => {
24+
vi.doMock('@/../package.json', () => ({
25+
default: { version },
26+
}));
27+
28+
return vi.importActual('../DocsDB').then((module: any) => {
29+
const result = module.getCurrentVersion();
30+
expect(result).toBe(expected);
31+
expect(result).toBeGreaterThan(previousExpected);
32+
previousExpected = result;
33+
});
34+
});
35+
});
36+
});

0 commit comments

Comments
 (0)