Last active
October 9, 2024 07:29
-
-
Save kilbot/a27038adaf95d87259c154f12971ab6f to your computer and use it in GitHub Desktop.
RxStorage adapter for expo-sqlite
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { createRxDatabase } from 'rxdb'; | |
import { getRxStorageSQLite, SQLiteQueryWithParams } from 'rxdb-premium/plugins/sqlite'; | |
import { openDatabase, WebSQLDatabase, ResultSet } from 'expo-sqlite'; | |
/** | |
* Polyfill for TextEncoder | |
* fixes: ReferenceError: Can't find variable: TextEncoder | |
*/ | |
import 'fast-text-encoding'; | |
const getSQLiteBasicsExpoSQLite = (openDB: typeof openDatabase) => { | |
return { | |
open: async (name: string) => { | |
return Promise.resolve(openDB(name)); | |
}, | |
all: async (db: WebSQLDatabase, queryWithParams: SQLiteQueryWithParams) => { | |
const result = new Promise<ResultSet['rows']>((resolve, reject) => { | |
console.log(`all sql: ${queryWithParams.query}`, queryWithParams.params); | |
db.exec( | |
[{ sql: queryWithParams.query, args: queryWithParams.params }], | |
false, | |
(err, res) => { | |
console.log('sql response: ', res); | |
if (err) { | |
return reject(err); | |
} | |
if (Array.isArray(res)) { | |
const queryResult = res[0]; // there is only one query | |
if (Object.prototype.hasOwnProperty.call(queryResult, 'rows')) { | |
return resolve(queryResult.rows); | |
} | |
return reject(queryResult.error); | |
} | |
return reject(new Error(`Unexpected response from SQLite: ${res}`)); | |
} | |
); | |
}); | |
return result; | |
}, | |
run: async (db: WebSQLDatabase, queryWithParams: SQLiteQueryWithParams) => { | |
console.log(`run sql: ${queryWithParams.query}`, queryWithParams.params); | |
db.exec([{ sql: queryWithParams.query, args: queryWithParams.params }], false, () => {}); | |
}, | |
close: async (db: WebSQLDatabase) => { | |
return db.closeAsync(); | |
}, | |
journalMode: '', | |
}; | |
}; | |
const myRxDatabase = await createRxDatabase({ | |
name: 'exampledb', | |
storage: getRxStorageSQLite({ | |
sqliteBasics: getSQLiteBasicsExpoSQLite(openDatabase) | |
}), | |
multiInstance: false, | |
ignoreDuplicate: true, | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment