Skip to content

Instantly share code, notes, and snippets.

@tanishqkancharla
Created May 20, 2024 02:13
Show Gist options
  • Save tanishqkancharla/f7dc0149ed94290bbbdc4c5fa596fd46 to your computer and use it in GitHub Desktop.
Save tanishqkancharla/f7dc0149ed94290bbbdc4c5fa596fd46 to your computer and use it in GitHub Desktop.
ExpoSqliteTupleStorageApi
class ExpoSqliteTupleStorageApi implements AsyncTupleStorageApi {
private db = SQLite.openDatabase("app.db");
constructor() {}
async prepare() {
await this.db.execAsync(
[
{
sql: `
CREATE TABLE IF NOT EXISTS tuples (
key TEXT PRIMARY KEY,
value TEXT
);
`,
args: [],
},
],
false,
);
}
scan: AsyncTupleStorageApi["scan"] = () => {
return new Promise((resolve, reject) => {
this.db.transaction((tx) => {
tx.executeSql(`SELECT key, value FROM tuples`, [], (_, result) => {
result.rows._array.map(({ value }) => {
return JSON.stringify(tap(value, "SELECTED VALUES"));
}, resolve([]));
});
}, reject);
});
};
transact(fn: (tx: SQLite.SQLTransaction) => void): Promise<void> {
return new Promise<void>((resolve, reject) => {
this.db.transaction(fn, reject, resolve);
});
}
commit: AsyncTupleStorageApi["commit"] = async (writes) => {
await this.transact((tx) => {
for (const { key, value } of writes.set ?? []) {
tx.executeSql(
`INSERT OR REPLACE INTO tuples (key, value) VALUES (?, ?)`,
[JSON.stringify(key), JSON.stringify(value)],
);
}
for (const key of writes.remove ?? []) {
tx.executeSql(`DELETE FROM tuples WHERE key = ?`, [
JSON.stringify(key),
]);
}
});
};
close: AsyncTupleStorageApi["close"] = async () => {
await this.db.closeAsync();
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment