YDN-DB - Delete DB then recreate and load when page is loaded/reloaded but not when refreshed - ydn-db

I'm converting some IndexedDB code to use YDN-DB and need some help in converting this. This code essentially deletes the DB if the page is loaded or reloaded but not when it is refreshed.
How would I accomplish that using YDN-DB?
var indexedDB = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDB || window.msIndexedDB;
var db;
window.refreshing = false;
$(document).ready(function(){
if(window.performance) {
if(performance.navigation.type == 0 ) {
// The db already exists so delete it and re-create it so we don't have stale records.
deleteDB();
} else {
window.refreshing = true;
open();
}
}
});
function deleteDB() {
var request = indexedDB.deleteDatabase("DocsDB");
request.onsuccess = function() {
open();
}
request.onerror = function(event) {
throw "Error in deleteDB.";
}
}
function open() {
var request = indexedDB.open("DocsDB");
var upgraded = false;
request.onupgradeneeded = function(evt) {
upgraded = true;
var dbnew = evt.target.result;
dbnew.onerror = function(event) {
console.log("IndexedDB error: " + evt.target.error.code);
};
var objectStore = dbnew.createObjectStore(
"docs", { keyPath: "id", autoIncrement: true });
objectStore.createIndex("docname", "DOC_NAME", { unique: false });
objectStore.createIndex("printdate", "PRINT_DATE", { unique: false });
}
request.onsuccess = function(evt) {
db = request.result;
if (!upgraded && !window.refreshing) {
throw "Not upgraded";
}
request.result.onversionchange = function(e) {
if (e.newVersion === null) { // An attempt is made to delete the db
e.target.close(); // Manually close our connection to the db
}
};
if(typeof db != 'undefined' && !window.refreshing) {
// We load the store with the records here, attempting to add records via ajax doesn't work
// looks like we'll ahve to load them via ajax before initialization?
var store = getObjectStore(db);
for (i=0; i<documents["Rows"].length-1;i++) {
store.add(documents["Rows"][i]);
}
}
}
request.onerror = function() {
throw "Error in open";
}
}
function getObjectStore(db, mode = 'readwrite') {
if(typeof db != 'undefined') {
var tx = db.transaction('docs', mode);
return tx.objectStore('docs');
} else {
return null;
}
}

To delete a database use, ydn.db.deleteDatabase("DocsDB").

Related

Return created item key

My app creates a new item, and I want to retrieve the key to use in a server script. The data variable returns null though. This is what I have:
function addItem(addButton) {
var addItemPage = addButton.root;
if (!addItemPage.validate()) {
return;
}
var props = addItemPage.properties;
var itemDs = addItemPage.datasource;
props.Creating = true;
itemDs.saveChanges({
success: function(key) {
props.Creating = false;
if (app.currentPage !== app.pages.EditItem) {
return;
}
var newProjectItem = itemDs.item;
newProjectItem._loadHistory();
gotoEditItemPage(newProjectItem._key, true);
return newProjectItem;
},
failure: function(error) {
props.Creating = false;
console.error(error);
}
});
gotoEditItemPage();
var data = app.datasources.ProjectItems.item._key;
google.script.run.withSuccessHandler(function(value){
alert("Created");
}).createDoco(data);
}
This is not neat by any means, but I fixed it by creating a new function:
function addItem(addButton, key) {
var addItemPage = addButton.root;
if (!addItemPage.validate()) {
return;
}
var props = addItemPage.properties;
var itemDs = addItemPage.datasource;
props.Creating = true;
itemDs.saveChanges({
success: function() {
props.Creating = false;
if (app.currentPage !== app.pages.EditItem) {
return;
}
var newProjectItem = itemDs.item;
newProjectItem._loadHistory();
gotoEditItemPage(newProjectItem._key, true);
var key = newProjectItem._key;
value(key);
},
failure: function(error) {
props.Creating = false;
console.error(error);
}
});
gotoEditItemPage();
function value(record){
var data = record;
google.script.run.withSuccessHandler(function(value){
alert("Created");
}).createDoco(data);
}
}

Cordova SQLite class - cannot return value from database

So, I'm building an app with Cordova and SQLite and below is the object Storage I created to handle the database properties and methods.
function Storage(connection, platform)
{
if (platform == 'mobile') {
this.db = window.sqlitePlugin.openDatabase({name: connection.name, location: connection.location});
} else if (platform == 'web') {
this.db = window.openDatabase(connection.name, connection.version, connection.mode, -1);
}
this.read = function(sql, vals) {
var rows = null;
this.db.transaction(function(tx) {
tx.executeSql(sql, vals, function(tx, res) {
rows = res.rows;
});
}, function(error) {
console.log('Transaction error: '+error.message);
});
return rows;
};
};
var connection = {
name: 'database.db',
version: '1.0',
mode: 'Development'
};
var db = new Storage(connection, 'web');
var sql = '';
sql += 'SELECT *';
sql += ' FROM countdown';
sql += ' WHERE countdown_status != ?;';
var rows = db.read(sql, [1]);
console.log(rows);
This code logs 'null' and I don't know why since I have data into my database. And when I try to log from within the tx.executeSql method, it logs the data from database.
Any ideas on why I cannot get this data out of that function?
Thanks a lot.
the db read is asynchronous - it needs to return the data to a callback function like so:
getHighScore: function (type,callback) {
var query = "SELECT Value FROM HighScore where Type = '" + type + "';";
playedDb.transaction(function (tx) {
tx.executeSql(query, [], function (tx, res) {
var out;
if (typeof res.rows.item(0) === "undefined") {
if (typeof callback === "function") {
callback(-1);
return;
};
} else {
out = res.rows.item(0).Value
//task 301 only allow alphanumeric and decimal point (for version)
out = String(out).replace(/[^0-9a-z\.]/gi, '');
if (typeof callback === "function") {
callback(out);
return;
};
}
}, function (e) {
console.log("getHighScore FAILED: " + e.message);
if (typeof callback === "function") {
callback(-2);
return;
};
});

Meteor. Problems with subscribe/publish

i have a problem.
I'm trying to build highcharts graphic.
How it works:
I'm going to my route ('ship.details'), and here i have not problems.
My problem:
subsription to (ships_snapshots_all) not working.
My publish.js:
Meteor.publish("ships_snapshots", function(user, options) {
if(!this.userId) return null;
if(this.userId) {
console.log('subsribed by ' + user);
return ships_snapshots.find({userId: user}, options);
}
});
Meteor.publish("ships_snapshots_all", function() {
return ships_snapshots.find({});
})
My subscribe.js (in lib folder):
Meteor.subscribe('ships_snapshots');
Meteor.subscribe('ships_snapshots_all');
Problem 100% in my subsription, because if i'm installing autopublish all working good. And problem in my router i think.
router.js:
Router.route('/ships/details', {
name: 'ship.details',
loadingTemplate: 'loading',
onBeforeAction: function() {
var shipId = Session.get('currentShipId');
if(!shipId) {
Router.go('user.ships');
} else {
this.next();
}
},
waitOn: function() {
if (Meteor.isClient) {
var getCompare = Meteor.user().profile.wows.compareWith;
console.log(getCompare);
var user2 = Meteor.users.findOne({"profile.wows.nickname": getCompare});
var user2Id = user2._id;
if (getCompare) {
var user2 = Meteor.users.findOne({"profile.wows.nickname": getCompare});
if (user2) {
var user2Id = user2._id;
}
}
if (getCompare) {
var handle = Meteor.subscribe('ships_snapshots', Meteor.user()._id) && Meteor.subscribe('ships_snapshots', user2Id) && Meteor.subscribe('userSearchInfo', getCompare);
Session.set('compareWith', user2);
console.log('user2 _____');
console.log(user2);
return handle
} else {
var handle = Meteor.subscribe('ships_snapshots', Meteor.user()._id) && Meteor.subscribe('ships_snapshots', user2Id);
return handle
}
}, data: function() {
if (handle.ready()) {
var shipname = this.params.shipName;
var obj = {};
var query = ships.findOne();
var shipId = Session.get('currentShipId');
var result;
_.each(Meteor.user().profile.wows.ships, function(row) {
if (row.ship_id === shipId) {
result = row;
}
});
return result;
}
}
});
I think my problem in subscripion for ship_snapshots. Something going wrong here, but i can't to resolve this problem.
What exactly do you mean by "not working"? From your code I would assume that you're always seeing all the ship snapshots.
You shouldn't have the subscribes in /lib if you have them in your router. If you have Meteor.subscribe('ships_snapshots_all'); in /lib then you should always be seeing all the ship snapshots (assuming you're not stopping that subscription anywhere).
Also your subscription to all should be:
Meteor.publish("ships_snapshots", function(user, options) {
if(this.userId) {
console.log('subsribed by ' + user);
return ships_snapshots.find({userId: user}, options);
} else this.ready();
});
You don't want to return null when there is no user, you can just mark the subscription as ready without finding any records. This is not the cause of your problem but just good practice.
Meteor.publish("ships_snapshots", function(user, options) {
if(!this.userId) return null;
if(this.userId) {
console.log('subsribed by ' + user);
return ships_snapshots.find({userId: user._id}, options);
}
});
In your publish script, is user really an id or is it a user object? I changed it to user._id. Please check that.

Mesosphere form validation call back is not working

This is the sample code written in the common.js.Its working both client and server side.Meteor.call not working Please help me.
Meteor.methods({
signupUser: function signupUser(rawData) {
Mesosphere.signupForm.validate(rawData, function(errors, callback){
if(!errors)
{
var username = '';
var password = '';
for(var i = 0;i < rawData.length ; i++)
{
var obj = rawData[i];
if(i == 0)
{
username = rawData[i].value;
}
else(i == 1)
{
password = rawData[i].value;
}
}
Meteor.call("ltest", username, password, function (error, luser)
{
if (luser != 'fail') {
Session.set('getuser', luser);
Session.set('getusername', luser);
alert("Login Successfuly");
Router.go('/dashboard');
}
});
}
});
}
});
How to call back for the signupUser function to client in meteor.

Meteor data not inserting or displaying after removing insecure package

Data is not getting inserted into the database after i removed autopublish and insecure packages. Please let me know what i am missing.
Userdata = new Meteor.Collection("Userdata");
if (Meteor.isClient) {
Template.sample.events({
"click button.clickeve": function (){
var e_value = $('input[name = "exampleInputEmail1"]').val();
var e_name = $('input[name = "exampleInputName"]').val();
doc = {user_id: Meteor.userId(), e_value:e_value, e_name:e_name}
}
});
Template.temp.list_item = function(){
return Userdata.find();
}
Meteor.subscribe("Userdata");
}
if (Meteor.isServer) {
Meteor.publish("Userdata", function() {
return Userdata.find();
});
Userdata.allow({
insert: function(userID,doc) {
return userID === doc.user_id;
}
});
}
You don't have an insert statement.
Userdata = new Meteor.Collection("Userdata");
if (Meteor.isServer) {
Meteor.publish("Userdata", function() {
return Userdata.find();
});
Userdata.allow({
insert: function(userID,doc) {
return userID === doc.user_id;
}
});
}
if (Meteor.isClient) {
Template.sample.events({
"click button.clickeve": function (e){
e.preventDefault(); // to prevent default action of the button
var e_value = $('input[name = "exampleInputEmail1"]').val();
var e_name = $('input[name = "exampleInputName"]').val();
doc = {user_id: Meteor.userId(), e_value:e_value, e_name:e_name};
Userdata.insert(doc); // actually inserting the document
}
});
Template.temp.list_item = function(){
return Userdata.find();
}
Meteor.subscribe("Userdata");
}

Resources