Tim Glasgow
2 years ago
1 changed files with 76 additions and 0 deletions
@ -0,0 +1,76 @@ |
|||
import Realm from "realm"; |
|||
|
|||
//Entities
|
|||
import {Score} from './entities/Score'; |
|||
import {System} from './entities/System'; |
|||
import {User} from './entities/User'; |
|||
|
|||
//Repos
|
|||
import {ScoreRepo} from './repos/ScoreRepo'; |
|||
import {SystemRepo} from './entities/System'; |
|||
import {UserRepo} from './entities/User'; |
|||
|
|||
//Migrations
|
|||
import {migrateV0} from './migrations/v0'; |
|||
import {migrateV1} from './migrations/v1'; |
|||
|
|||
//keys
|
|||
import { generateKey } from "../libs/Random"; |
|||
import * as KeyStore from '../services/Keystore'; |
|||
|
|||
let systemRepo = null; |
|||
let scoreRepo = null; |
|||
let userRepo = null; |
|||
|
|||
let realmDB = null; |
|||
|
|||
export async function initDB(){ |
|||
const dbKeyRef = 'squareDB'; |
|||
let fromStore = await KeyStore.getKey(dbKeyRef); |
|||
|
|||
if (fromStore === null) { |
|||
let newKey = generateKey(); |
|||
await KeyStore.setKey(newKey, dbKeyRef); |
|||
fromStore = await KeyStore.getKey(dbKeyRef); |
|||
} |
|||
|
|||
let dbKey = Uint8Array(64); |
|||
if (fromStore !== null){ |
|||
for (let i = 0; i < 64; ++i){ |
|||
dbKey[i] = fromStore.charAt(i); |
|||
} |
|||
} |
|||
|
|||
if (realmDB === null){ |
|||
let schemaList = [ |
|||
{schemaVersion: 0, schema: [System, User, Score], migration: migrateV0, encryptionKey: dbKey}, |
|||
{schemaVersion: 1, schema: [System, User, Score], migration: migrateV1, encryptionKey: dbKey} |
|||
] |
|||
|
|||
let currentSchema = Realm.schemaVersion(Realm.defaultPath, dbKey); |
|||
|
|||
if (currentSchema === -1) { |
|||
currentSchema = 0; |
|||
} |
|||
|
|||
while (currentSchema < schemaList.length) { |
|||
if (realmDB !== null) { |
|||
realmDB.close(); |
|||
} |
|||
|
|||
realmDB = new Realm(schemaList[currentSchema]); |
|||
currentSchema += 1; |
|||
} |
|||
|
|||
if (realmDB === null) { |
|||
realmDB = new Realm(schemaList[schemaList.length - 1]); |
|||
} |
|||
|
|||
systemRepo = new SystemRepo(realmDB); |
|||
userRepo = new UserRepo(realmDB); |
|||
scoreRepo = new ScoreRepo(realmDB) |
|||
} |
|||
|
|||
return realmDB; |
|||
|
|||
} |
Loading…
Reference in new issue