Permalink
Cannot retrieve contributors at this time
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
foundation/solutions/07_unit_testing/database/todo.js
Go to fileThis commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
59 lines (49 sloc)
1.52 KB
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
'use strict' | |
const sqlite = require('sqlite-async') | |
module.exports = class ToDo { | |
constructor(dbName = ':memory:') { | |
return (async() => { | |
this.db = await sqlite.open(dbName) | |
const sql = 'CREATE TABLE IF NOT EXISTS items(id INTEGER PRIMARY KEY AUTOINCREMENT, item TEXT, qty NUMERIC)' | |
await this.db.run(sql) | |
return this | |
})() | |
} | |
async add(item, qty) { | |
if (item === '') throw new Error('item cannot be empty') | |
if (qty === '') throw new Error('qty cannot be empty') | |
qty = Number(qty) | |
if(isNaN(qty)) throw new Error('the quantity must be a number') | |
let sql = `SELECT * FROM items WHERE ITEM = "${item}"` | |
const data = await this.db.all(sql) | |
if(data.length === 0) { | |
sql = `INSERT INTO items(item, qty) VALUES("${item}", ${qty})` | |
await this.db.run(sql) | |
} else { | |
const newQty = data[0].qty + qty | |
sql = `UPDATE items SET qty=${newQty} WHERE ITEM = "${item}"` | |
await this.db.run(sql) | |
} | |
} | |
async getAll() { | |
const sql = 'SELECT * FROM items' | |
const data = await this.db.all(sql) | |
console.log(data) | |
return data | |
} | |
async delete(id) { | |
if (id === undefined) throw new Error('id cannot be undefined') | |
id = Number(id) | |
if (isNaN(id)) throw new Error('id must be a number') | |
const sql = `DELETE FROM items WHERE id=${id}` | |
if ((await this.db.run(sql)).changes === 0) throw new Error('id has to exist') | |
} | |
async countItems() { | |
const sql = 'SELECT COUNT(*) as items FROM items' | |
const data = await this.db.get(sql) | |
return data.items | |
} | |
async clear() { | |
await this.db.run('DELETE FROM items') | |
} | |
} |