-
Notifications
You must be signed in to change notification settings - Fork 17
/
v2.ts
78 lines (65 loc) · 1.93 KB
/
v2.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import { DBSchema } from 'idb/with-async-ittr';
import { IDBConstructor } from '../../../../../lib/idb/manager';
import { decodeStruct, type } from '../../../../../lib/types';
import { ITranslationEntry } from '../../data';
export type IDBTranslationsSchemaV2 = DBSchema & {
translations: {
key: number;
value: ITranslationEntry;
indexes: {
originalText: string;
};
};
};
const migration: IDBConstructor<IDBTranslationsSchemaV2> = {
version: 2,
apply: async (db, { transaction: tx, migrateFrom }) => {
const isMigrationNeeded = migrateFrom === 1;
// Prepare data
const translations: IDBTranslationsSchemaV2['translations']['value'][] = [];
if (isMigrationNeeded) {
const translationType = type.type({
from: type.string,
to: type.string,
text: type.string,
translate: type.string,
date: type.number,
});
const entries = await tx.objectStore('translations' as any).getAll();
for (const translation of entries) {
// Skip invalid data
const translationCodecResult = decodeStruct(translationType, translation);
if (translationCodecResult.errors !== null) {
continue;
}
const { from, to, text, translate, date } = translationCodecResult.data;
translations.push({
timestamp: date,
translation: {
from,
to,
originalText: text,
translatedText: translate,
},
});
}
db.deleteObjectStore(`translations`);
}
// Create store
const translationsStore = db.createObjectStore(`translations`, {
keyPath: 'id',
autoIncrement: true,
});
// `keyPath` with `.` separator: https://w3c.github.io/IndexedDB/#inject-key-into-value
translationsStore.createIndex('originalText', 'translation.originalText', {
unique: false,
});
// Insert data
if (isMigrationNeeded && translations.length > 0) {
for (const translation of translations) {
await translationsStore.add(translation);
}
}
},
};
export default migration;