Database Lokal (AsyncStorage / SQLite)
Slide 25: Menggunakan Transaction untuk Keamanan Data
Transaction memastikan konsistensi data (all or nothing):
const transferNote = (noteId, fromUserId, toUserId) => {
db.transaction(
(tx) => {
tx.executeSql(
"SELECT id FROM notes WHERE id = ? AND user_id = ?",
[noteId, fromUserId],
(_, { rows }) => {
if (rows.length === 0) {
throw new Error("Note not found or unauthorized");
}
}
);
tx.executeSql("UPDATE notes SET user_id = ? WHERE id = ?", [
toUserId,
noteId,
]);
tx.executeSql(
"INSERT INTO transfer_logs (note_id, from_user, to_user) VALUES (?, ?, ?)",
[noteId, fromUserId, toUserId]
);
},
(error) => {
console.error("Transaction failed:", error);
},
() => {
console.log("Transfer completed successfully");
}
);
};
const addNoteWithCategory = async (title, content, categoryName) => {
return new Promise((resolve, reject) => {
db.transaction((tx) => {
tx.executeSql(
"INSERT INTO categories (name) VALUES (?)",
[categoryName],
(_, result) => {
const categoryId = result.insertId;
tx.executeSql(
"INSERT INTO notes (title, content, category_id) VALUES (?, ?, ?)",
[title, content, categoryId],
(_, noteResult) => resolve(noteResult.insertId)
);
}
);
}, reject);
});
};