Inserting duplicate value in indexeddb - angularjs

When i insert on my database , it inserting same data twice.
Table Create
var oOptions = {
keyPath: account.primaryKey,
autoIncrement: true
};
var oStore = dbHandle.createObjectStore(account.tableName, oOptions);
var oIxOptions = {
unique: false
};
account.fields.forEach(function(item) {
oStore.createIndex(item + "Index", item, oIxOptions);
});
Insert
var defered = $q.defer();
try {
var objectStore = config.database.transaction(tableName, "readwrite").objectStore(tableName);
var result = objectStore.add(entity);
result.onerror = function(e) {
defered.reject("Can't insert into account");
throw e;
}
result.onsuccess = function(e) {
defered.resolve();
}
} catch (e) {
defered.reject("Can't insert into account");
throw e;
}
return defered.promise;
Retrive
var defered = $q.defer();
try {
var req = $window.indexedDB.open(config.databaseName, 1.0);
req.onsuccess = function(evt) {
config.database = evt.target.result;
var transaction = config.database.transaction(account.tableName, IDBTransaction.READ_ONLY);
var objectStore = transaction.objectStore(account.tableName);
var tmpData = [];
objectStore.openCursor().onsuccess = function(event) {
var cursor = event.target.result;
if (!cursor) {
defered.resolve(tmpData);
return;
}
tmpData.push(cursor.value);
cursor.continue();
};
}
} catch (e) {
defered.reject("Can't pull from account");
throw e;
}
return defered.promise;
Any suggestion ??

This might be less of a problem with indexedDB and more a problem with your use of try/catch and promises. Have you tested without try/catch and without promises? What is your rationale for using promises here? Consider that you don't need try/catch and you don't need promises to perform these simple tasks.

Related

node mssql stream return issue

I am attempting to stream the data from a procedure that returns multiple data sets using node and mssql. If using as a stand a long function it works, but I need it to return the dataset from the route i am using.
handler: function(request, reply) {
var inputValues = request.payload.inputParams;
var procName = request.params.procedureName;
var request = new sql.Request(mainsettings.connection);
request.stream = true;
var newGroup = [];
var count = 0;
var recordSetArr = [];
for(var key in inputValues) {
var currentParam = inputValues[key];
var paramType = getParamType(sql, currentParam.paramType);
try {
request.input(currentParam.paramName, paramType, currentParam.paramValue);
}
catch(err) {
console.error(err);
}
}
request.execute(procName);
request.on('recordset', function(columns) {
// Emitted once for each recordset in a query
count++;
if(count > 1) {
recordSetArr.push(newGroup);
}
newGroup = [];
});
request.on('row', function(row) {
// Emitted for each row in a recordset
newGroup.push(row);
});
request.on('error', function(err) {
// May be emitted multiple times
console.error(err);
});
request.on('done', function(returnValue) {
// Always emitted as the last one
return (recordSetArr);
});
}
I am getting the following error.
Debug: internal, implementation, error
Error: handler method did not return a value, a promise, or throw an error
at module.exports.internals.Manager.execute (F:\FARA_API\node_modules\hapi\l
ib\toolkit.js:52:29)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:188:7)
180406/194833.505, (1523044113505:MISOM-DEV-002:6976:jfod4ysa:10140) [error] mes
sage: handler method did not return a value, a promise, or throw an error, stack
: Error: handler method did not return a value, a promise, or throw an error
at module.exports.internals.Manager.execute (F:\FARA_API\node_modules\hapi\l
ib\toolkit.js:52:29)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:188:7)
Any suggestions on how I am supposed to return the data set properly?
Also tried the following
handler: function(request, reply) {
recordRouteCall("procedure");
var inputValues = request.payload.inputParams;
var procName = request.params.procedureName;
sql.connect(mainsettings.connection, err => {
var request = new sql.Request();
request.stream = true;
var newGroup = [];
var count = 0;
var recordSetArr = [];
for(var key in inputValues) {
var currentParam = inputValues[key];
var paramType = getParamType(sql, currentParam.paramType);
try {
request.input(currentParam.paramName, paramType, currentParam.paramValue);
}
catch(err) {
console.error(err);
}
}
request.execute(procName);
request.on('recordset', columns => {
// Emitted once for each recordset in a query
count++;
if(count > 1) {
recordSetArr.push(newGroup);
}
newGroup = [];
});
request.on('row', row => {
// Emitted for each row in a recordset
newGroup.push(row);
});
request.on('error', err => {
// May be emitted multiple times
console.error(err);
});
request.on('done', result => {
// Always emitted as the last one
console.log(recordSetArr);
return (recordSetArr);
});
});
sql.on('error', err => {
console.error(err);
return err;
});
}

nightmare how to looply select the selector

var Nightmare = require('nightmare');
var nightmare = Nightmare({ show: true });
var fs = require('fs');
var result;
nightmare
.goto('http://football-system.jp/fss/pub_penaltylist.php?lid=eBVesRz5C54=')
.wait('select[name="selectTeam"]')
.evaluate(function () {
var options = document.querySelectorAll('option'),i;
var values =[]
for (i = 1; i < options.length; ++i) {
values.push(options[i].value)
}
return values;
})
.then(function (values) {
console.log(values)
values.reduce(function(accumulator, value) {
return accumulator.then(function(results) {
return nightmare.goto("http://football-system.jp/fss/pub_penaltylist.php?lid=eBVesRz5C54=")
.wait('select[name="selectTeam"]')
.select('select[name="selectTeam"]', value)
.wait('button[onClick="selectData();"]')
.click('button[onClick="selectData();"]')
.wait('table[class="tableOutputDate"]')
.evaluate(function () {
return document.querySelector('table[class="tableOutputDate"]').textContent;
})
.then(function(result){
console.log(result)
results.push(result);
return results;
});
});
}, Promise.resolve([])).then(function(results){
console.log(results)
});
})
.catch(function (error) {
console.error('Search failed:', error);
});
That is my code .I want to looping select all the selector in that page and get the all html data.I asked a question in here that how to loop in nightmare,but that result cant solve this problem.please help me. Thank you.
I solve my question.the problem is happened in the deal time,not in the loop logic.I add some more wait(time).I think wait(time)is better than the wait(selector).so is over. thank u attention.
var run = function * () {
//var values = ['http://www.yahoo.com', 'http://example.com', 'http://w3c.org'];
var titles = [];
for (var i = 0; i < values.length; i++) {
var title = yield nightmare.goto('.............')
//.wait('select[name="selectTeam"]')
.wait(2000)
.select('select[name="selectTeam"]', values[i])
.wait(2000)
.click('button[onClick="selectData();"]')
//.wait('table[class="tableOutputDate"]')
.wait(2000)
.evaluate(function () {
//return document.querySelector('table[class="tableOutputDate"]').textContent;
var divs = document.querySelectorAll('table[class="tableOutputDate"]'),i;
var tables = []
for (i = 0; i < divs.length; ++i) {
tables.push(divs[i].textContent)
//result += divs[i].href.toString()+"\n";
}
return tables;
})
titles.push(title);
}
return titles;
}
vo(run)(function(err, titles) {
console.dir(titles);
});

How to make this asynchronous call, synchronous

I have an associative array date as key, the value in this case is an array of objects. Now in this object
while (tempDate < endDate) {
$scope.dates.push(tempDate.format("DD-MM-YYYY"));
var dailyTrips = response.data[tempDate.format("DD-MM-YYYY")];
for (var i = 0; i < dailyTrips.length; i++) {
// console.log(moment(dailyTrips[i].trip.startTime).format("hh:mm a"));
// console.log(moment(dailyTrips[i].trip.endTime).format("hh:mm a"));
geocode(dailyTrips, i);
}
tempDate.add(1, 'days');
}
$scope.data = response.data;
var geocode = function(dailyTrips, i) {
(function() {
var latlng = {
lat: dailyTrips[i].trip.source.latitude,
lng: dailyTrips[i].trip.source.longitude
};
console.log(latlng);
var geocoder = new google.maps.Geocoder;
geocoder.geocode({
'location': latlng
}, function(result, status) {
if (result[1]) {
console.log(result[1].address_components[0].long_name+" "+result[1].address_components[2].long_name);
}
});
}(i));
};
Now This code is working but running at completely different times as it's a callback. I wanted to have this all at one time so that I can use it in ng-repeat and show everything nicely. How do I do that?
Expected output
Trip StartTime Trip from
Trip EndLine Trip To
EDIT 1: Still not working
while (tempDate < endDate) {
$scope.dates.push(tempDate.format("DD-MM-YYYY"));
var dailyTrips = response.data[tempDate.format("DD-MM-YYYY")];
var promises = [];
for (var i = 0; i < dailyTrips.length; i++) {
promises[i] = geocode(dailyTrips, i);
}
$q.all(promises).then(function(result) {
console.log(result); //line 39
});
tempDate.add(1, 'days');
}
$scope.data = response.data;
}, function(error) {
console.log(error.data);
});
var geocode = function(dailyTrips, i) {
var q = $q.defer();
var latlng = {
lat: dailyTrips[i].trip.source.latitude,
lng: dailyTrips[i].trip.source.longitude
};
console.log(latlng);
var geocoder = new google.maps.Geocoder;
geocoder.geocode({
'location': latlng
}, function(result, status) {
console.log(status);
if (status === google.maps.GeocoderStatus.OK) {
console.log(result[1].address_components[0].long_name + " " + result[1].address_components[2].long_name);
q.resolve(result[1].address_components[0].long_name + " " + result[1].address_components[2].long_name);
} else if (status === google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
setTimeout(function() {
geocode(dailyTrips, i);
}, 500);
} else {
q.reject();
}
});
return q.promise;
};
You cannot make an async call synchronous, except by blocking your code, which you do no NOT want to do. Instead, I suggest you convert geocode into a promise
var geocode = function(dailyTrips, i) {
return this.$q((resolve, reject) => {
....
and then wait for all the promises to complete
var promises = [];
for (var i = 0; i < dailyTrips.length; i++) {
promises[i] = geocode(dailyTrips, i);
}
$q.all(promises).then( function(results) {...} );

Unable to get my data from $firebaseObject using AngularFire in a controller. View/ng-repeat works fine

I have different sections in Firebase with normalized data, and I have routines to get the information, but I cannot loop through the returned records to get data. I want to use the keys in the $firebaseArray() to get data from other $firebaseObject().
GetOneTeam() .... {
var DataRef = GetFireBaseObject.DataURL(Node + '/'); // xxx.firebaseio.com/Schedules/
var OneRecordRef = DataRef.child(Key); // Schedule Key - 1
return $firebaseObject(OneRecordRef);
}
...
var Sched = GetOneSchedule('Schedules', 1);
... // For Loop getting data - Put in HomeId
var TeamRec = GetOneTeam('Teams', HomeId);
var Name = TeamRec.TeamName; // Does not TeamName value from Schedule/1
The following is more of the actual code in case the snippet above is not clear enough. Sample common routine for getting data:
angular.module('MyApp')
.constant('FIREBASE_URL', 'https://xxxxxxxx.firebaseio.com/');
angular.module('MyApp')
.factory('GetFireBaseObject', function(FIREBASE_URL) {
return {
BaseURL: function() {
return new Firebase(FIREBASE_URL);
},
DataURL: function(Node) {
return new Firebase(FIREBASE_URL + Node);
}
};
}
);
// Common code for getting Array/Object from Firebase.
angular.module('MyApp')
.factory("FireBaseData", ["$firebaseArray", "$firebaseObject", "GetFireBaseObject",
function($firebaseArray, $firebaseObject, GetFireBaseObject) {
return {
AllRecords: function(Node) {
var DataRef = GetFireBaseObject.DataURL(Node + '/');
return $firebaseArray(DataRef);
},
OneRecordAllChildren: function(Node, Key) {
var DataRef = GetFireBaseObject.DataURL(Node + '/');
var ParentRecordRef = DataRef.child(Key);
return $firebaseArray(ParentRecordRef);
},
OneRecord: function(Node, Key) {
var DataRef = GetFireBaseObject.DataURL(Node + '/');
var OneRecordRef = DataRef.child(Key);
return $firebaseObject(OneRecordRef);
},
AddRecord: function(Node, Record) {
var DataRef = GetFireBaseObject.DataURL(Node + '/');
var AddRecordRef = DataRef.child(Record.Key);
AddRecordRef.update(Record);
return $firebaseObject(AddRecordRef); // Return Reference to added Record
},
DeleteRecord: function(Node, Key) {
var DataRef = GetFireBaseObject.DataURL(Node + '/');
var DeleteRecordRef = DataRef.child(Key);
DeleteRecordRef.remove();
}
};
}
]);
Individual Controller's retrieval of records from firebase.io:
angular.module('MyApp').service("ScheduleData", ["FireBaseData",
function(FireBaseData) {
var DataPath = 'Schedules';
this.AllSchedules = function() {
return FireBaseData.AllRecords(DataPath);
};
this.AddSchedule = function(GameInfo) {
return FireBaseData.AddRecord(DataPath, GameInfo);
};
this.DeleteSchedule = function(GameKey) {
FireBaseData.DeleteRecord(DataPath, GameKey);
};
this.GetOneSchedule = function(GameKey) {
return FireBaseData.OneRecord(DataPath, GameKey);
};
}
]);
// Structure of a record, including named fields to come from another object (Team/Venue using the OneRecord FireBaseData call to get a $firebaseObject
angular.module('MyApp').factory("ScheduleRecord", function() {
return {
Clear: function(GameInfo) {
GameInfo.Key = "";
GameInfo.HomeTeamId = "";
GameInfo.HomeTeamName = "";
GameInfo.AwayTeamId = "";
GameInfo.AwayTeamName = "";
GameInfo.VenueId = "";
GameInfo.VenueName = "";
GameInfo.GameDate = "";
GameInfo.GameTime = "";
}
};
}
);
Controller module start:
angular.module('MyApp').controller('ScheduleCtrl', ["$scope", "ScheduleData", "ScheduleRecord", "TeamData", "VenueData",
function ($scope, ScheduleData, ScheduleRecord, TeamData, VenueData) {
var ClearEditData = function() {
$scope.ScheduleEditMode = false;
ScheduleRecord.Clear($scope.schedule);
};
var GameSchedules = ScheduleData.AllSchedules();
This next piece is where my question lies. Once the promise returns the static schedule list, I want to loop through each record and translate the Team Id (Home/Away) and Venue Id to the names.
GameSchedules.$loaded().then(function() {
angular.forEach(GameSchedules, function(GameInfo) {
var HomeTeam = TeamData.GetOneTeam(GameInfo.HomeTeamId);
GameInfo.HomeTeamName = HomeTeam.Name;
The GetOneTeam returns a $firebaseObject, based on the HomeTeamId child record. This returns null all the time.
This is the TeamData.GetOneTeam return using the FireBaseData as well.
angular.module('MyApp').service("TeamData", ["FireBaseData",
function(FireBaseData) {
var DataPath = 'Teams';
this.AllTeams = function() {
return FireBaseData.AllRecords(DataPath);
};
this.AddTeam = function(TeamInfo) {
return FireBaseData.AddRecord(DataPath, TeamInfo);
};
this.DeleteTeam = function(TeamKey) {
FireBaseData.DeleteRecord(DataPath, TeamKey);
};
this.GetOneTeam = function(TeamKey) {
return FireBaseData.OneRecord(DataPath, TeamKey);
};
}
]);
As I have a Firebase Object, how can I get my named data objects from the $firebaseObject?
This is a mess. Use $firebaseArray for collections, not $firebaseObject. Most of these strange wrapper factories are unnecessary. AngularFire services already have methods for add, remove, and so on, and all these factories attempt to make AngularFire into a CRUD model and don't actually provide any additional functionality or enhancements.
app.factory('Ref', function(FIREBASE_URL) {
return new Firebase(FIREBASE_URL);
});
app.factory('Schedules', function($firebaseArray, Ref) {
return $firebaseArray(Ref.child('Schedules'));
});
// or if you want to pass in the path to the data...
//app.factory('Schedules', function($firebaseArray, Ref) {
// return function(pathToData) {
// return $firebaseArray(Ref.child(pathToData));
// };
//});
app.factory('Schedule', function($firebaseObject, Ref) {
return function(scheduleId) {
return $firebaseObject(Ref.child('Schedules').child(scheduleId));
}
});
app.controller('...', function(Schedules, Schedule, Ref) {
$scope.newSchedule(data) {
Schedules.$add(data);
};
$scope.removeSchedule(key) {
Schedules.$remove(key);
};
$scope.updateSchedule(key, newWidgetValue) {
var rec = Schedules.$getRecord(key);
rec.widgetValue = newWidgetValue;
Schedules.$save(rec);
};
// get one schedule
var sched = Schedule(key);
sched.$loaded(function() {
sched.widgetValue = 123;
sched.$save();
});
});

accessing items in firebase

I'm trying to learn firebase/angularjs by extending an app to use firebase as the backend.
My forge looks like this
.
In my program I have binded firebaseio.com/projects to $scope.projects.
How do I access the children?
Why doesn't $scope.projects.getIndex() return the keys to the children?
I know the items are in $scope.projects because I can see them if I do console.log($scope.projects)
app.js
angular.module('todo', ['ionic', 'firebase'])
/**
* The Projects factory handles saving and loading projects
* from localStorage, and also lets us save and load the
* last active project index.
*/
.factory('Projects', function() {
return {
all: function () {
var projectString = window.localStorage['projects'];
if(projectString) {
return angular.fromJson(projectString);
}
return [];
},
// just saves all the projects everytime
save: function(projects) {
window.localStorage['projects'] = angular.toJson(projects);
},
newProject: function(projectTitle) {
// Add a new project
return {
title: projectTitle,
tasks: []
};
},
getLastActiveIndex: function () {
return parseInt(window.localStorage['lastActiveProject']) || 0;
},
setLastActiveIndex: function (index) {
window.localStorage['lastActiveProject'] = index;
}
}
})
.controller('TodoCtrl', function($scope, $timeout, $ionicModal, Projects, $firebase) {
// Load or initialize projects
//$scope.projects = Projects.all();
var projectsUrl = "https://ionic-guide-harry.firebaseio.com/projects";
var projectRef = new Firebase(projectsUrl);
$scope.projects = $firebase(projectRef);
$scope.projects.$on("loaded", function() {
var keys = $scope.projects.$getIndex();
console.log($scope.projects.$child('-JGTmBu4aeToOSGmgCo1'));
// Grab the last active, or the first project
$scope.activeProject = $scope.projects.$child("" + keys[0]);
});
// A utility function for creating a new project
// with the given projectTitle
var createProject = function(projectTitle) {
var newProject = Projects.newProject(projectTitle);
$scope.projects.$add(newProject);
Projects.save($scope.projects);
$scope.selectProject(newProject, $scope.projects.length-1);
};
// Called to create a new project
$scope.newProject = function() {
var projectTitle = prompt('Project name');
if(projectTitle) {
createProject(projectTitle);
}
};
// Called to select the given project
$scope.selectProject = function(project, index) {
$scope.activeProject = project;
Projects.setLastActiveIndex(index);
$scope.sideMenuController.close();
};
// Create our modal
$ionicModal.fromTemplateUrl('new-task.html', function(modal) {
$scope.taskModal = modal;
}, {
scope: $scope
});
$scope.createTask = function(task) {
if(!$scope.activeProject || !task) {
return;
}
console.log($scope.activeProject.task);
$scope.activeProject.task.$add({
title: task.title
});
$scope.taskModal.hide();
// Inefficient, but save all the projects
Projects.save($scope.projects);
task.title = "";
};
$scope.newTask = function() {
$scope.taskModal.show();
};
$scope.closeNewTask = function() {
$scope.taskModal.hide();
};
$scope.toggleProjects = function() {
$scope.sideMenuController.toggleLeft();
};
// Try to create the first project, make sure to defer
// this by using $timeout so everything is initialized
// properly
$timeout(function() {
if($scope.projects.length == 0) {
while(true) {
var projectTitle = prompt('Your first project title:');
if(projectTitle) {
createProject(projectTitle);
break;
}
}
}
});
});
I'm interested in the objects at the bottom
console.log($scope.projects)
Update
After digging around it seems I may be accessing the data incorrectly. https://www.firebase.com/docs/reading-data.html
Here's my new approach
// Load or initialize projects
//$scope.projects = Projects.all();
var projectsUrl = "https://ionic-guide-harry.firebaseio.com/projects";
var projectRef = new Firebase(projectsUrl);
projectRef.on('value', function(snapshot) {
if(snapshot.val() === null) {
console.log('location does not exist');
} else {
console.log(snapshot.val()['-JGTdgGAfq7dqBpSk2ls']);
}
});
$scope.projects = $firebase(projectRef);
$scope.projects.$on("loaded", function() {
// Grab the last active, or the first project
$scope.activeProject = $scope.projects.$child("a");
});
I'm still not sure how to traverse the keys programmatically but I feel I'm getting close
It's an object containing more objects, loop it with for in:
for (var key in $scope.projects) {
if ($scope.projects.hasOwnProperty(key)) {
console.log("The key is: " + key);
console.log("The value is: " + $scope.projects[key]);
}
}
ok so val() returns an object. In order to traverse all the children of projects I do
// Load or initialize projects
//$scope.projects = Projects.all();
var projectsUrl = "https://ionic-guide-harry.firebaseio.com/projects";
var projectRef = new Firebase(projectsUrl);
projectRef.on('value', function(snapshot) {
if(snapshot.val() === null) {
console.log('location does not exist');
} else {
var keys = Object.keys(snapshot.val());
console.log(snapshot.val()[keys[0]]);
}
});
$scope.projects = $firebase(projectRef);
$scope.projects.$on("loaded", function() {
// Grab the last active, or the first project
$scope.activeProject = $scope.projects.$child("a");
});
Note the var keys = Object.keys() gets all the keys at firebaseio.com/projects then you can get the first child by doing snapshot.val()[keys[0])

Resources