X-Git-Url: https://git.mdrn.pl/ReadingsJQM.git/blobdiff_plain/bdd9d26375a6489d7ff8eac944e29b0789f04a20..45f8b33043d9aad64b1f89906323bc477efda0f3:/js/app/Catalogue.coffee diff --git a/js/app/Catalogue.coffee b/js/app/Catalogue.coffee new file mode 100644 index 0000000..c556e5b --- /dev/null +++ b/js/app/Catalogue.coffee @@ -0,0 +1,75 @@ + +class Readings.Catalogue + open: () -> + version = Readings.config.get 'db_version' + console.log "opening db ver #{version}" + @db = openDatabase 'catalogue', version, 'Catalogue', 65535, @init + this + + init: (db) -> + if not db? + db = @db + console.log "initializing DB" + db.changeVersion "", Readings.config.get 'db_version' + $.ajax "initdb.sql" + type: "GET" + dataType: 'text' + success: (sql) => + sql = sql.split /;\n/ + sql = sql.slice(1,-2) + + create = (tx) => + for stmt in sql + console.log stmt + tx.executeSql stmt, [], + (tx,rs) => true, + (tx,err) => console.error(err) + + db.transaction create + error: => + console.error "can't get initial sql" + + wrap_error: (error_cb) -> + (tx, error) -> + window.last_error = error + alert "SQL ERROR: #{error.message}" + if error_cb + error_cb(error) + else + throw error + + map_rs: (rs, mapper) -> + objs = [] + for i in [0...rs.rows.length] + objs.push(mapper(rs.rows.item(i))) + return objs + +## TODO update method + withCategory: (category, callback, error) -> + rs_to_tags = (tx, data) -> + tags = [] + for i in [0...data.rows.length] + tags.push new Readings.Tag(data.rows.item(i)) + callback(tags) + + @db.readTransaction (tx)=> + tx.executeSql "SELECT * FROM tag WHERE category=? ORDER BY sort_key", + [category], rs_to_tags, @wrap_error(error) + + withTag: (tag_id, cb) -> + @db.readTransaction (tx) => + tx.executeSql "SELECT * FROM tag WHERE id=?", [tag_id], + (tx, rs) => + if rs.rows.length > 0 + tag = new Readings.Tag rs.rows.item(0) + return cb(tag) + else + alert "No tag id #{tag_id}" + , + @wrap_error() + + withBooks: (tag, cb) -> + @db.readTransaction (tx)=> + console.log "books in tag: #{tag.books}" + tx.executeSql "SELECT * FROM book WHERE id IN (#{tag.books}) ORDER BY sort_key", + [], ((tx, rs) => cb(@map_rs(rs, (rec)->new Readings.Book(rec)))), @wrap_error()